🐍 Python Lessons
Welcome to Python Lessons! Learn Python programming step by step with clear explanations, fun examples, and interactive practice questions. Perfect for beginners!
Lesson 1: Python Basics
In this lesson, you'll learn the fundamental building blocks of Python programming. These are the essential skills every programmer needs!
1. Variables - Storing Information
What are variables? Think of variables like labeled boxes where you can store information. You give the box a name and put something inside it!
Why use variables? Variables help us remember and reuse information in our programs. Instead of typing the same number or text over and over, we store it once and use it many times.
Examples:
# Storing a number
age = 12
score = 100
# Storing text (called a string)
name = "Alex"
favorite_color = "blue"
# Storing a decimal number
height = 5.5
temperature = 98.6
Rules for variable names:
- Start with a letter or underscore (_)
- Can contain letters, numbers, and underscores
- Cannot use spaces (use _ instead)
- Cannot use Python keywords like
print,if, etc. - Use descriptive names:
student_ageis better thana
2. Print Command - Displaying Information
What is print? The print() function displays text or numbers on the screen. It's like talking to the computer and asking it to show you something!
Why use print? Print helps us see what our program is doing. It's essential for debugging (finding mistakes) and showing results to users.
Examples:
# Print simple text
print("Hello, World!")
# Output: Hello, World!
# Print a number
print(42)
# Output: 42
# Print a variable
name = "Sam"
print(name)
# Output: Sam
# Print multiple things
print("My name is", name, "and I am", 12, "years old")
# Output: My name is Sam and I am 12 years old
# Print with f-strings (fancy way to combine text and variables)
age = 12
print(f"I am {age} years old")
# Output: I am 12 years old
3. Input Command - Getting Information from Users
What is input? The input() function lets your program ask the user for information. The program waits for the user to type something and press Enter.
Why use input? Input makes your programs interactive! Instead of hardcoding values, users can provide their own information.
Examples:
# Simple input
name = input("What is your name? ")
print(f"Hello, {name}!")
# Input for numbers (you need to convert!)
age = input("How old are you? ")
age = int(age) # Convert string to integer
print(f"Next year you will be {age + 1} years old")
# Shorter way to convert input to number
score = int(input("What is your test score? "))
print(f"Your score is {score}")
Important: The input() function always returns text (a string). If you want to do math with the input, you must convert it using int() for whole numbers or float() for decimal numbers.
4. Arithmetic Operations - Doing Math
What are arithmetic operations? These are the basic math operations you can do in Python: addition, subtraction, multiplication, division, and more!
Why use arithmetic? Computers are great at math! You can use arithmetic to calculate scores, distances, averages, and much more.
Basic Operations:
# Addition (+)
sum = 5 + 3
print(sum) # Output: 8
# Subtraction (-)
difference = 10 - 4
print(difference) # Output: 6
# Multiplication (*)
product = 7 * 3
print(product) # Output: 21
# Division (/)
quotient = 15 / 3
print(quotient) # Output: 5.0
# Integer Division (//) - gives whole number result
result = 17 // 5
print(result) # Output: 3
# Modulo (%) - gives the remainder
remainder = 17 % 5
print(remainder) # Output: 2
# Exponentiation (**) - power
power = 2 ** 3
print(power) # Output: 8 (2 to the power of 3)
Using Variables in Math:
num1 = 10
num2 = 5
# Add variables
total = num1 + num2
print(f"{num1} + {num2} = {total}")
# Calculate average
test1 = 85
test2 = 92
test3 = 78
average = (test1 + test2 + test3) / 3
print(f"Average score: {average}")
5. If, Else, and Elif - Making Decisions
What are if/else/elif? These are conditional statements that let your program make decisions. Like choosing what to do based on different situations!
Why use conditionals? Conditionals make programs smart! They let programs react differently to different situations, just like making choices in real life.
Basic If Statement:
age = 15
if age >= 13:
print("You are a teenager!")
If-Else Statement:
score = 85
if score >= 70:
print("You passed!")
else:
print("You need to study more.")
If-Elif-Else Statement:
grade = 92
if grade >= 90:
print("Excellent! You got an A!")
elif grade >= 80:
print("Good job! You got a B!")
elif grade >= 70:
print("Not bad! You got a C!")
else:
print("Keep trying! You can do better!")
Comparison Operators:
==- Equal to!=- Not equal to>- Greater than<- Less than>=- Greater than or equal to<=- Less than or equal to
More Examples:
# Check if a number is positive, negative, or zero
number = int(input("Enter a number: "))
if number > 0:
print("The number is positive!")
elif number < 0:
print("The number is negative!")
else:
print("The number is zero!")
# Check password
password = input("Enter password: ")
if password == "secret123":
print("Access granted!")
else:
print("Access denied!")
6. Data Types - Different Kinds of Information
What are data types? Python has different types of data: numbers, text, and more. Understanding data types helps you write better programs!
Common Data Types:
- int - Integer (whole numbers):
5,100,-42 - float - Floating point (decimal numbers):
3.14,2.5,-0.5 - str - String (text):
"Hello",'Python',"123"(text, not a number!) - bool - Boolean (True or False):
True,False
Examples:
# Integer
age = 12
print(type(age)) # Output: <class 'int'>
# Float
height = 5.5
print(type(height)) # Output: <class 'float'>
# String
name = "Alex"
print(type(name)) # Output: <class 'str'>
# Boolean
is_student = True
print(type(is_student)) # Output: <class 'bool'>
# Converting between types
number_str = "42"
number_int = int(number_str) # Convert string to integer
number_float = float(number_str) # Convert string to float
7. Comments - Notes for Yourself
What are comments? Comments are notes you write in your code that Python ignores. They help you and others understand what your code does!
Why use comments? Comments make your code easier to read and understand. They're like notes in a textbook!
Examples:
# This is a single-line comment
# Comments start with a # symbol
# Calculate the area of a rectangle
length = 10 # Length in meters
width = 5 # Width in meters
area = length * width # Calculate area
print(f"The area is {area} square meters")
# Multi-line comments use multiple # symbols
# This program asks for a name
# and prints a greeting
name = input("What's your name? ")
print(f"Hello, {name}!")
🎯 Practice Questions - Python Basics
Test your understanding! Click on each question to see the answer. Try to solve them yourself first!
print("Hello" + " " + "World")?
Answer: Hello World
Explanation: The + operator can be used to combine (concatenate) strings together. The three strings "Hello", " " (a space), and "World" are combined into one string.
result after this code runs: result = 15 // 4?
Answer: 3
Explanation: The // operator performs integer division (floor division). 15 divided by 4 is 3.75, but integer division gives us the whole number part, which is 3.
remainder after this code runs: remainder = 17 % 5?
Answer: 2
Explanation: The % operator gives the remainder after division. 17 divided by 5 is 3 with a remainder of 2.
age = 12
if age >= 13:
print("Teenager")
else:
print("Not a teenager")
Answer: Not a teenager
Explanation: Since age is 12, which is less than 13, the condition age >= 13 is False. Therefore, the else block executes and prints "Not a teenager".
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("F")
Answer: B
Explanation: The score is 85. It's not >= 90, so the first condition is False. However, 85 >= 80 is True, so the first elif block executes and prints "B". Once a condition is True, Python stops checking the rest.
2nd_place?
Answer: Variable names cannot start with a number!
Explanation: In Python, variable names must start with a letter or underscore. A valid name would be second_place or place_2nd.
user_input after this code: user_input = input("Enter a number: ")?
Answer: str (string)
Explanation: The input() function always returns a string, even if the user types a number. To use it as a number, you need to convert it: int(user_input) or float(user_input).
x = 5
y = 3
print(f"{x} + {y} = {x + y}")
Answer: 5 + 3 = 8
Explanation: This uses an f-string (formatted string) to combine text and variables. The {x} and {y} are replaced with their values, and {x + y} calculates and displays the sum.
result after: result = 2 ** 4?
Answer: 16
Explanation: The ** operator is exponentiation (power). 2 ** 4 means 2 to the power of 4, which is 2 × 2 × 2 × 2 = 16.
Answer:
name = input("What is your name? ")
age = int(input("How old are you? "))
future_age = age + 10
print(f"{name}, in 10 years you will be {future_age} years old!")
Explanation: This program uses input() to get the name (string) and age (converted to integer). It then calculates the future age by adding 10, and uses an f-string to print a personalized message.