Python Basics Summary
Python Interpreter and Interactive Mode
Python Interpreter executes code line by line.
Interactive Mode allows quick testing.
Example:
>>> 2 + 2
Data Types
Common Python Data Types:
- int: a = 10
- float: b = 3.14
- str: c = 'Hello'
- bool: d = True
- list: e = [1, 2, 3]
- tuple: f = (1, 2)
- dict: g = {'key': 'value'}
- set: h = {1, 2, 3}
Statements
Python statements are instructions.
Examples:
- Assignment: x = 5
- Conditional: if x > 0:
print('Positive')
- Loop: for i in range(3):
print(i)
Expressions
An expression is a combination of values, variables, and operators.
Python Basics Summary
Example:
- result = 3 + 4 * 2 # evaluates to 11
Boolean Values and Operators
Boolean Values: True, False
Operators:
- and: True and False -> False
- or: True or False -> True
- not: not True -> False
- Comparison: 5 > 3 -> True, 5 == 5 -> True
Strings
Strings are sequences of characters.
Examples:
s = 'Python'
- s[0] -> 'P'
- len(s) -> 6
- s.upper() -> 'PYTHON'
- 'Py' in s -> True
Arrays of Numbers
Use 'array' module or 'numpy'.
Example with array module:
import array
arr = array.array('i', [1, 2, 3])
print(arr[0]) -> 1
Lists
Lists are mutable sequences.
Python Basics Summary
lst = [1, 2, 3]
lst.append(4)
print(lst) -> [1, 2, 3, 4]
lst[1] = 5
print(lst) -> [1, 5, 3, 4]
Tuples
Tuples are immutable sequences.
tup = (1, 2, 3)
print(tup[0]) -> 1
Dictionaries
Dictionaries store key-value pairs.
d = {'name': 'Alice', 'age': 25}
print(d['name']) -> 'Alice'
d['age'] = 26
Functions
Functions are defined using 'def'.
Example:
def greet(name):
return 'Hello, ' + name
print(greet('Vincy')) -> 'Hello, Vincy'
File Reading and Writing
Reading a file:
with open('file.txt', 'r') as f:
content = f.read()
Writing to a file:
Python Basics Summary
with open('file.txt', 'w') as f:
f.write('Hello World')