Statements
Statements and Comments in Python
•Definition: Instructions that Python can
execute
•Examples:
print("Hello, World!")
x=5
result = 2 + 3
Comments
•Single-line: # This is a comment
•Multi-line:
python
'‘’
This is a multi-line comment or docstring
'''
•Purpose: Explain code, disable code temporarily,
document functions
Indentation
Python's Unique Feature
•No braces {} like other languages
•Uses whitespace (4 spaces recommended) to define code
blocks
•Examples:
if True:
print("This is indented") # 4 spaces
print("So is this") # same level
print("This is not") # back to outer level
•Importance
•Syntax error if indentation is inconsistent
•Defines scope of loops, functions, conditionals
Arithmetic Operators
• + Addition #5+3=8
• - Subtraction # 5 - 3 = 2
• * Multiplication # 5 * 3 = 15
• / Division # 5 / 3 = 1.666...
• // Floor Division # 5 // 3 = 1
• % Modulus #5%3=2
• ** Exponentiation # 5 ** 3 = 125
Comparison Operators
• == Equal to
• != Not equal to
• > Greater than
• < Less than
• >= Greater than or equal to
• <= Less than or equal to
Logical Operators
• and # Both conditions True
• or # At least one condition True
• not # Reverse the condition
Assignment Operators
• = # Basic assignment
• += # x += 3 → x = x + 3
• -= # x -= 3 → x = x - 3
• *= # x *= 3 → x = x * 3
• /= # x /= 3 → x = x / 3
Working with Data Types
• Strings
• name = "Alice"
• message = 'Hello, World!'
• multiline = """This is
• a multi-line
• string"""
String Operations
• # Concatenation
• full_name = "Alice" + " " + "Smith"
• # Repetition
• stars = "*" * 10
• # Indexing
• first_char = name[0] # 'A'
• # Slicing
• substring = name[0:3] # 'Ali'
# Methods
• [Link]() # 'ALICE'
• [Link]() # 'alice'
• [Link]() # remove whitespace
• [Link]("A", "E") # 'Elice'
Numbers
• # Integers
• age = 25
• # Floats
• price = 19.99
• # Complex
• z = 3 + 4j
• # Type conversion
• int("25") # 25
• float("3.14") # 3.14
• str(42) # "42"
Boolean
• is_student = True
• is_employed = False
• # Truthy and Falsy values
• bool(0) # False
• bool(1) # True
• bool("") # False
• bool("Hi") # True
• bool([]) # False
• bool([1,2]) # True
Data Structures
• Lists (Mutable, Ordered)
• fruits = ["apple", "banana", "cherry"]
• fruits[0] = "orange" # Modifiable
• [Link]("grape")
• [Link]("banana")
Tuples (Immutable, Ordered)
• coordinates = (10, 20)
• # coordinates[0] = 15 # ERROR - immutable
Sets (Mutable, Unordered, Unique)
• unique_numbers = {1, 2, 3, 2, 1} # {1, 2, 3}
• unique_numbers.add(4)
• unique_numbers.remove(2)
Dictionaries (Key-Value Pairs)
• person = {
• "name": "Alice",
• "age": 25,
• "city": "New York"
•}
• person["age"] = 26 # Modify value
• person["country"] = "USA" # Add new key
Arrays (via array module - for homogeneous data)
•import array
•numbers = [Link]('i', [1, 2, 3, 4]) # 'i' for integers
Variables and Functions
Variables
# Naming conventions
student_name = "Alice" # snake_case
MAX_SCORE = 100 # UPPERCASE for constants
# Dynamic typing
x=5 # integer
x = "hello" # now string
Functions
# Definition
def greet(name):
"""Greets a person by name"""
return f"Hello, {name}!"
# Calling
message = greet("Bob")
print(message) # "Hello, Bob!"
# Parameters with default values
def power(base, exponent=2):
return base ** exponent
power(3) # 9
power(3, 3) # 27
Accepting User Input
• # Basic input
• name = input("Enter your name: ")
• print(f"Hello, {name}!")
• # Numeric input (needs conversion)
• age = int(input("Enter your age: "))
• price = float(input("Enter price: "))
Input Validation with Conditionals
age = input("Enter your age: ")
if [Link]():
age = int(age)
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
else:
print("You are a child")
else:
print("Please enter a valid number")
Error Handling with Try-Except
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")
else:
print("Operation successful!") # Runs if no exception
finally:
print("Execution completed") # Always runs
Looping
For Loop
# Iterate through list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# With index
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
While Loop
• count = 0
• while count < 5:
• print(count)
• count += 1
• # Infinite loop with break condition
• while True:
• user_input = input("Enter 'quit' to exit: ")
• if user_input.lower() == 'quit':
• break
The range() Statement
• # Basic range
• range(5) # 0,1,2,3,4
• # With start and end
• range(2, 6) # 2,3,4,5
• # With step
• range(0, 10, 2) # 0,2,4,6,8
• # Practical usage
• for i in range(5):
• print(i) # 0,1,2,3,4
• # Creating lists
• numbers = list(range(1, 6)) # [1,2,3,4,5]
Break and Continue
• # Break - exit loop entirely
• for number in range(10):
• if number == 5:
• break
• print(number) # Prints 0,1,2,3,4
• # Continue - skip current iteration
• for number in range(10):
• if number % 2 == 0:
• continue
• print(number) # Prints 1,3,5,7,9
SUMMARY ✅
• Python uses indentation instead of braces for code blocks
• Comments help document your code
• Various operators perform different operations
• Multiple data types serve different purposes
• Data structures organize data in different ways
• Functions encapsulate reusable code
• Input validation ensures program robustness
• Error handling prevents crashes
• Loops automate repetitive tasks
Practice Exercises 🏋
1. Create a program that accepts user input and validates it
2. Write functions for common mathematical operations
3. Create and manipulate different data structures
4. Implement error handling for division operations
5. Use loops to process lists of data