Learn Python programming with simple, clear examples
CONTENTS
In this course, you’ll learn about the basics of python programming.
Let’s print “Hello World”.
print("Hello World")
Variables store values. Python figures out the type automatically.
name = "Alice"
age = 25
Python handles integers and floats. Math works as expected.
x = 10
y = 3
sum = x + y
Strings are text wrapped in quotes. Use + to combine them.
greeting = "Hello"
name = "World"
message = greeting + " " + name
Lists hold multiple items in a specific order. Each item has a position number called an index, starting from 0.
fruits = ["apple", "banana", "orange"]
first_fruit = fruits[0]
Lists are created with square brackets and items separated by commas. You can access any item by using its index number in square brackets.
Create a list called colors
with “red”, “green”, and “blue”. Remember to use quotes around each color name.
Functions are reusable blocks of code that perform specific tasks. They can take input (parameters) and return output (results).
def greet(name):
return "Hello, " + name
message = greet("Alice")
Functions are defined with the def
keyword, followed by the function name and parameters in parentheses. The return
statement sends a value back to whoever called the function.
Create a function called add
that takes two numbers as parameters and returns their sum. Use the def
keyword and return
statement.
Loops repeat. For each item. Do something.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num * 2)
Print each number from 1 to 5.
Conditions check. If true, do this. If false, do that.
age = 18
if age >= 18:
print("Adult")
else:
print("Minor")
Check if a number is positive. Print “Positive” or “Negative”.
Dictionaries map keys to values. Look up. Find.
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(person["name"])
Create a dictionary called book
with “title” and “author” keys.
Classes create objects. Blueprint. Template.
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return "Hello, I'm " + self.name
alice = Person("Alice")
print(alice.greet())
Create a class called Car
with a brand
attribute and a start
method.
Errors happen. Catch them. Handle them.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Try to access an index that doesn’t exist in a list. Catch the error.
Create a simple program. Use everything you learned.
class Calculator:
def __init__(self):
self.history = []
def add(self, a, b):
result = a + b
self.history.append(f"{a} + {b} = {result}")
return result
def show_history(self):
for entry in self.history:
print(entry)
calc = Calculator()
calc.add(5, 3)
calc.add(10, 20)
calc.show_history()
Create your own calculator with multiply and divide methods.
Conclusion
You learned Python. Variables. Functions. Classes. Loops. Conditions.
Simple. Clear. Direct.
Python is powerful. You are ready.