Running Python Scripts
To execute a Python script, navigate to the file's directory in the command line and run:
python script_name.py
Alternatively, use the terminal in your development environment.
Basic Data Types
Identifiers
Identifiers are user-defined names for variables, functions, and classes.
- Composed of letters, digits, underscores, or dollar signs
- Cannot start with a digit
- Cannot contain spaces
Naming conventions:
- camelCase: variables and functions (e.g.,
myVariable) - PascalCase: classes (e.g.,
MyClass) - snake_case: underscores between words (e.g.,
my_variable)
Keywords
Reserved words in Python that cannot be used as identifiers:
import keyword
print(keyword.kwlist)
Comments
Single-line comments start with #. Multiline comments use triple quotes:
# Single-line comment
"""
Multiline
comment
"""
Constants
Constants are immutable values:
- Integers:
10(decimal),0b1010(binary),0o12(octal),0xA(hexadecimal) - Floats:
3.14,1.2e3 - Strings:
"Hello"or'World' - Booleans:
True,False - Complex numbers:
3+4jorcomplex(3,4)
Variables
Variables store references to data objects:
value = 10
x, y, z = 1, 2, 3
a = b = c = 5
Type Conversion
int_value = int(3.14) # 3
float_val = float(10) # 10.0
str_val = str(123) # '123'
bool_val = bool("text") # True
bin_str = bin(10) # '0b1010'
oct_str = oct(10) # '0o12'
hex_str = hex(10) # '0xa'
char_code = ord('A') # 65
character = chr(66) # 'B'
Mathematical Functions
absolute = abs(-5) # 5
power = pow(2, 3) # 8
maximum = max(1, 5, 2) # 5
rounded = round(3.14159, 2) # 3.14
Input and Output
user_input = input("Enter a number: ")
number = eval(user_input)
print("Result:", number + 1)
name = "Alice"
age = 25
print(f"{name} is {age} years old.")
Operators
Arithmetic
sum = 5 + 3 # 8
diff = 10 - 4 # 6
product = 7 * 2 # 14
quotient = 10 / 3 # 3.333...
floor_div = 10 // 3 # 3
remainder = 10 % 3 # 1
exponent = 2 ** 4 # 16
Comparison
equals = (5 == 5) # True
not_equal = (5 != 3) # True
greater = (10 > 5) # True
chained = (1 < 2 < 3) # True
Logical
and_result = (True and False) # False
or_result = (True or False) # True
not_result = not True # False
Bitwise
bit_and = 13 & 7 # 5
bit_or = 13 | 7 # 15
right_shift = 16 >> 2 # 4
left_shift = 2 << 3 # 16
bit_xor = 13 ^ 7 # 10
Membership and Identity
in_list = 3 in [1,2,3] # True
is_same = (1000 is 1000) # False (different objects)
equals_val = (1000 == 1000) # True (same value)
Conditional Statements
if condition:
# execute if true
elif other_condition:
# execute if previous false and this true
else:
# execute if all false
Loop Structures
for i in range(5):
print(i)
for char in "Hello":
print(char)
count = 0
while count < 5:
print(count)
count += 1
Sequences and Indexing
items = ['a', 'b', 'c', 'd']
first = items[0] # 'a'
last = items[-1] # 'd'