Python Beginner Notes with Examples & Exercises
1. Strings - Working with Text
Strings are used to store text.
Examples:
message = "Hello World"
print(message) # Hello World
Common String Functions:
- len("Hello") => 5
- "Hello".lower() => "hello"
- "hello".upper() => "HELLO"
- "hello".count("l") => 2
- "hello world".find("world") => 6
- "hello world".replace("world", "Python") => "hello Python"
Formatted String:
name = "John"
greeting = f"Hello, {name}!" # f-string
print(greeting) # Hello, John!
2. Numbers - Integers and Floats
Numbers in Python are either integers (whole) or floats (decimals).
Examples:
num = 3.14
print(type(num)) # <class 'float'>
Arithmetic Operations:
- 3 + 2 => 5
- 3 - 2 => 1
- 3 * 2 => 6
Python Beginner Notes with Examples & Exercises
- 3 / 2 => 1.5
- 3 // 2 => 1 (floor division)
- 3 ** 2 => 9 (exponent)
- 3 % 2 => 1 (modulus)
Useful Functions:
- abs(-5) => 5
- round(3.75) => 4
- round(3.75, 1) => 3.8
3. Lists, Tuples, and Sets
Lists:
courses = ["Math", "History", "Art"]
courses.append("Physics")
courses.insert(0, "Biology")
courses.remove("Math")
courses.pop() # Removes last
courses.sort()
courses.reverse()
Tuple:
Immutable list (can't change)
tup = ("Math", "Art")
Set:
No duplicates, unordered
subjects = {"Math", "Art", "Math"} # Only one "Math"
Set Functions:
- intersection()
- difference()
Python Beginner Notes with Examples & Exercises
- union()
4. Exercises
1. Create a string variable called `greeting` with value "Hi There", and print its uppercase version.
2. Use math operators to calculate: (4 + 5) * 3
3. Create a list of 3 fruits. Add one more fruit and remove the second fruit.
4. Create a set with duplicates. Print the set.
5. Write a formatted string to say "Welcome, Alex!" using variable `name = "Alex"`.
6. What is the output of: "hello".find("e") ?