Python Study Guide
1. Data Types
● Integers: Whole numbers, e.g., 5, -10
● Floats: Decimal numbers, e.g., 3.14, -2.5
● Strings: Text, surrounded by quotes, e.g., "hello", 'world'
● Booleans: Represent True or False
● None: Represents the absence of a value, e.g., None
● Type Checking: Use type(variable) to determine the data type of a variable.
Example:
x = 5 # integer
y = 2.5 # float
name = "Alex" # string
is_active = True # boolean
2. Input / Basic Console Interactions
● Use input() to get user input from the console. It always returns a string, so you may need to
convert it.
● Basic print output with print()
Example:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello, {name}! You are {age} years old.")
3. Conditionals
● Used for decision-making.
● if, elif, and else statements allow you to execute code based on conditions.
Example:
age = 18
if age >= 18:
print("You're an adult.")
elif age >= 13:
print("You're a teenager.")
else:
print("You're a child.")
4. Loops
● - For Loops: Iterate over a sequence (like a list, string, or range).
● - While Loops: Repeat as long as a condition is true.
Examples:
# For loop
for i in range(5):
print(i) # Prints numbers from 0 to 4
# While loop
count = 0
while count < 5:
print(count)
count += 1
5. Functions and Exceptions
● Functions: Reusable blocks of code, defined with `def`.
● Exceptions: Handle errors using try-except blocks.
Example Function:
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
Example of Exception Handling:
try:
x = int(input("Enter a number: "))
print("You entered:", x)
except ValueError:
print("That's not a valid number!")
6. Lists / Tuples
● Lists: Mutable sequences that hold items, defined with square brackets `[]`.
● Tuples: Immutable sequences, defined with parentheses `()`.
Examples:
# List
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits) # ['apple', 'banana', 'cherry', 'orange']
# Tuple
colors = ("red", "green", "blue")
print(colors[0]) # Accesses first element
Quick Tips:
● Remember to indent blocks consistently, as Python relies on indentation for code structure.
● Use built-in functions like `len()`, `sum()`, and `max()` to simplify code.
● Functions, conditionals, and loops are foundational for building complex logic, so practice
combining them for various scenarios.
Happy studying!