Python code is built from these basic elements:
if, for, def, True).my_var, age).10, "Hello", 3.14).+, =, >).(, ), #, :).age = 25.age in age = 25).25 in age = 25, or age + 1).#.Python is dynamically-typed, meaning you don't need to declare a variable's type.
| Category | Type | Example | Mutable/Immutable? |
|---|---|---|---|
| Number | int |
10, -50 |
Immutable |
float |
3.14, -0.5 |
Immutable | |
complex |
3 + 4j |
Immutable | |
| Boolean | bool |
True, False |
Immutable |
| Sequence | str (string) |
"Hello", 'Python' |
Immutable |
list |
[1, "a", 3.5] |
Mutable | |
tuple |
(1, "a", 3.5) |
Immutable | |
| None Type | NoneType |
None |
Immutable |
| Mapping | dict (dictionary) |
{"key": "value"} |
Mutable |
| Set | set |
{1, 2, 3} |
Mutable |
+, -, *, / (float division), // (floor division), % (modulus), ** (exponent).==, !=, >, <, >=, <=.and, or, not.=+=, -=, *=, etc.is, is not (Checks if two variables point to the *same* object in memory).in, not in (Checks if a value is present in a sequence).x + 5).x = 5).int + float becomes float).int(), float(), str().input("Prompt: "): Accepts data from the console. Returns a string.print(...): Displays output to the console.
name = input("Enter your name: ")
age_str = input("Enter your age: ")
age = int(age_str) # Explicit conversion
print("Hello,", name, "you are", age, "years old.")
{}. This is mandatory.if: Executes a block if a condition is true.if-else: Executes one block if true, another if false.if-elif-else: A chain of conditions.
if x > 10:
print("Large")
elif x > 5:
print("Medium")
else:
print("Small")
for loop: Iterates over a sequence (like a list, string, or range()).
for i in range(5): # i will be 0, 1, 2, 3, 4
print(i)
while loop: Repeats a block as long as a condition is true.
count = 0
while count < 5:
print(count)
count += 1
break: Exits the loop immediately.continue: Skips the rest of the current iteration and moves to the next.+ (Concatenation): "Hello" + " " + "World"* (Repetition): "Go" * 3 (produces "GoGoGo")in (Membership): "H" in "Hello" (produces True)s[start:end:step]. Very powerful.
s = "Python" s[0] # 'P' s[1:4] # 'yth' s[:3] # 'Pyt' s[-1] # 'n' (last character) s[::-1] # 'nohtyP' (reverses the string)
for loop: for char in my_string: print(char)len(), .upper(), .lower(), .find(), .split(), .strip().+, *, in, len()..append(item), .insert(index, item), .pop(index), .remove(item), .sort(), .reverse().matrix = [[1,2],[3,4]]).().len().{} (or set() for an empty set)..add(item), .remove(item).| (Union): set1 | set2& (Intersection): set1 & set2- (Difference): set1 - set2{}.my_dict['key']. Accessing a non-existent key causes an error.my_dict['new_key'] = "new_value"
for key in my_dict:
print(key, my_dict[key])
for key, value in my_dict.items():
print(key, value)
.keys(), .values(), .items(), .get(key) (safe access, returns None if key not found)..py) containing functions and variables.import : Imports the whole module. You access members with module.member.
import math print(math.pi)
from import : Imports a specific member into your namespace.
from math import pi print(pi)
def keyword.
def greet(name):
print("Hello,", name)
greet("Alice").def greet(name="Guest")greet(name="Alice").py file.__init__.py (can be empty).Used to read from and write to files on your disk.
Best Practice (with open): This automatically closes the file for you.
# Writing to a file (overwrites)
with open("output.txt", "w") as f:
f.write("Hello, file!\n")
f.write("This is a new line.\n")
# Reading from a file
with open("output.txt", "r") as f:
content = f.read()print(content)
Modes: "r" (read), "w" (write, overwrites), "a" (append), "r+" (read/write).
How to handle errors gracefully without crashing the program.
try: The block of code that *might* cause an error.except: The block that runs *if* an error occurs. You can catch specific exceptions (e.g., ZeroDivisionError, FileNotFoundError).finally: This block runs *no matter what* (whether an error occurred or not). Used for cleanup.
try:
x = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
finally:
print("This always runs.")
Exception class.Matplotlib is a powerful library for creating static, animated, and interactive visualizations.
Installation: You must first install it: pip install matplotlib
Basic Example (Line Plot):
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 4, 1, 5]
plt.plot(x, y) # Create the line plot
plt.title("Simple Line Plot")
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
plt.show() # Display the plot
Other common plots include plt.bar() (bar chart), plt.hist() (histogram), and plt.pie() (pie chart).