COS 101 Notes PT Ii_111706
COS 101 Notes PT Ii_111706
1. Variables
Definition
A variable is a named location in memory used to store a value. In Python, variables do not
require explicit declaration; they are created when a value is assigned.
Example
Key Points
Variable names should be meaningful.
Python is dynamically typed, meaning you don’t need to specify a data type.
Use lowercase letters with underscores for readability ( user_age instead of userAge ).
2. Conditional Statements
Definition
Conditional statements allow a program to make decisions based on conditions. Python
provides if , elif , and else statements.
Example
age = 18
Key Points
The if block executes if the condition is True .
The elif block is checked if the if condition is False .
The else block runs when all previous conditions are False .
number = 7
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
3. Functions
Definition
A function is a reusable block of code that performs a specific task. Functions improve code
organization and reusability.
Example
def greet(name):
return "Hello, " + name
print(greet("Alice"))
Key Points
Functions start with the def keyword.
Arguments (parameters) are passed inside parentheses.
The return statement sends back a result.
Functions help in modularizing code.
result = add_numbers(5, 3)
print("Sum:", result) # Output: Sum: 8
def greet(name="Guest"):
return "Hello, " + name
Lists Example
# Defining a list
names = ["Alice", "Bob", "Charlie"]
# Accessing elements
print(names[0]) # Output: Alice
print(names[-1]) # Output: Charlie (last element)
count = 0
while count < 5:
print("Count:", count)
count += 1
Key Points
for loops iterate over sequences (lists, tuples, strings).
while loops run as long as a condition is True .
5. Dictionary
Definition
A dictionary is a data structure that stores key-value pairs.
Example
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Accessing values
print(person["name"]) # Output: Alice
Key Points
Dictionaries use {} with key-value pairs.
Keys must be unique and immutable (strings, numbers, or tuples).
Use .items() to loop through key-value pairs.
2. List Comprehension
numbers = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in numbers]
print(squared) # Output: [1, 4, 9, 16, 25]
3. Exception Handling
try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Invalid input! Please enter a valid number.")
Break and Continue in Loops
These statements are used to alter the flow of loops.
1. break Statement
The break statement is used to exit a loop prematurely when a certain condition is met.
Output:
0
1
2
3
4
Stopping at 5
count = 0
while count < 10:
if count == 5:
print("Loop stopped at", count)
break
print(count)
count += 1
Output:
0
1
2
3
4
Loop stopped at 5
2. continue Statement
The continue statement skips the current iteration and moves to the next one.
Output:
1
3
5
7
9
count = 0
while count < 10:
count += 1
if count == 5:
continue # Skip printing 5
print(count)
Output:
1
2
3
4
6
7
8
9
10
Would you like more real-world examples of where break and continue are useful?