Variables, loops, functions, and more — learn Python the right way
March 20, 2025
9 min read
Python is the world's most popular programming language — and for good reason. Its clean syntax, massive ecosystem, and versatility make it perfect for beginners. Whether you want to build web apps, automate tasks, or dive into data science, Python is the ideal starting point.
Download Python from python.org and install it. Verify with:
bashpython --version # Python 3.12.x
We recommend using VS Code with the Python extension, or PyCharm Community Edition as your IDE.
Python is dynamically typed — no need to declare variable types:
python# Basic types name = "Alice" # str age = 25 # int height = 5.7 # float is_student = True # bool # Python infers types automatically print(type(name)) # <class 'str'> print(type(age)) # <class 'int'> # Multiple assignment x, y, z = 1, 2, 3 # String formatting greeting = f"Hello, {name}! You are {age} years old." print(greeting) # Hello, Alice! You are 25 years old.
python# List — mutable, ordered fruits = ["apple", "banana", "cherry"] fruits.append("mango") # add to end fruits.insert(1, "blueberry") # insert at index fruits.remove("banana") # remove by value print(fruits[0]) # "apple" print(fruits[-1]) # last item # Tuple — immutable, ordered coordinates = (10.5, 20.3) lat, lon = coordinates # unpacking # Dictionary — key-value pairs person = { "name": "Alice", "age": 25, "city": "New York" } print(person["name"]) # "Alice" person["email"] = "alice@example.com" # add key print(person.get("phone", "N/A")) # "N/A" (safe access) # Set — unique values unique_nums = {1, 2, 3, 2, 1} print(unique_nums) # {1, 2, 3}
python# if / elif / else score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" else: grade = "F" print(f"Grade: {grade}") # Grade: B # for loop for fruit in fruits: print(fruit) # range — counting loops for i in range(1, 6): print(i) # 1 2 3 4 5 # while loop count = 0 while count < 5: print(f"Count: {count}") count += 1 # List comprehension — Pythonic! squares = [x**2 for x in range(1, 6)] # [1, 4, 9, 16, 25] evens = [x for x in range(20) if x % 2 == 0] # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
python# Basic function def greet(name): return f"Hello, {name}!" print(greet("Alice")) # Hello, Alice! # Default parameters def greet(name, greeting="Hello"): return f"{greeting}, {name}!" greet("Bob") # "Hello, Bob!" greet("Bob", "Hi") # "Hi, Bob!" # *args — variable number of arguments def total(*numbers): return sum(numbers) print(total(1, 2, 3, 4)) # 10 # **kwargs — keyword arguments def describe_person(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") describe_person(name="Alice", age=25, city="NY") # Lambda — anonymous one-liner function double = lambda x: x * 2 square = lambda x: x ** 2 nums = [3, 1, 4, 1, 5, 9] nums.sort(key=lambda x: -x) # sort descending
pythonclass Animal: def __init__(self, name, species): self.name = name self.species = species def speak(self): return f"{self.name} makes a sound." def __str__(self): return f"{self.name} ({self.species})" class Dog(Animal): def __init__(self, name): super().__init__(name, "Canis lupus") def speak(self): # override parent method return f"{self.name} says Woof!" dog = Dog("Rex") print(dog.speak()) # Rex says Woof! print(str(dog)) # Rex (Canis lupus)
python# Write to file with open("notes.txt", "w") as file: file.write("Hello from Python! ") file.write("This is line 2. ") # Read entire file with open("notes.txt", "r") as file: content = file.read() print(content) # Read line by line with open("notes.txt", "r") as file: for line in file: print(line.strip()) # Append to file with open("notes.txt", "a") as file: file.write("Appended line. ")
Always use the with statement when working with files — it automatically closes the file even if an error occurs.
python# Basic try/except try: result = 10 / 0 except ZeroDivisionError: print("Can't divide by zero!") # Multiple exceptions try: num = int(input("Enter a number: ")) result = 100 / num print(f"Result: {result}") except ValueError: print("That's not a number!") except ZeroDivisionError: print("Can't divide by zero!") finally: print("Done.") # Always runs # Raise your own exceptions def validate_age(age): if age < 0: raise ValueError(f"Age cannot be negative: {age}") return age
pythonnums = [3, 1, 4, 1, 5, 9, 2, 6] print(len(nums)) # 8 — length print(max(nums)) # 9 — max value print(min(nums)) # 1 — min value print(sum(nums)) # 31 — sum print(sorted(nums)) # [1, 1, 2, 3, 4, 5, 6, 9] # zip — pair two lists names = ["Alice", "Bob", "Charlie"] scores = [90, 85, 78] for name, score in zip(names, scores): print(f"{name}: {score}") # enumerate — index + value for i, name in enumerate(names): print(f"{i}: {name}") # map & filter doubled = list(map(lambda x: x * 2, nums)) positive = list(filter(lambda x: x > 3, nums))
What's Next?