Python Programming Fundamentals
Start your Python journey with this comprehensive guide to programming fundamentals. Learn syntax, data types, functions, and build your first Python programs.
What You'll Learn
Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and readability. Created by Guido van Rossum in 1991, Python has become one of the most popular programming languages in the world.
Why Learn Python?
- Easy to Learn: Simple, readable syntax that's perfect for beginners
- Versatile: Used for web development, data science, AI, automation, and more
- Large Community: Extensive libraries and active community support
- High Demand: One of the most in-demand programming skills in the job market
Getting Started
Before we start coding, you'll need to install Python on your computer. Visit python.org and download the latest version.
Your First Python Program
print("Hello, World!") print("Welcome to Python programming!")
Save this code in a file called hello.py
and run it with:
python hello.py
Variables and Data Types
Variables in Python are used to store data. You don't need to declare the type explicitly - Python figures it out automatically.
# Numbers age = 25 height = 5.9 temperature = -10 # Strings name = "Alice" message = 'Hello, Python!' paragraph = """This is a multi-line string""" # Boolean is_student = True is_working = False # Lists fruits = ["apple", "banana", "orange"] numbers = [1, 2, 3, 4, 5] # Dictionaries person = { "name": "Bob", "age": 30, "city": "New York" }
Working with Variables
# Variable operations x = 10 y = 3 print(x + y) # Addition: 13 print(x - y) # Subtraction: 7 print(x * y) # Multiplication: 30 print(x / y) # Division: 3.333... print(x // y) # Floor division: 3 print(x % y) # Modulus: 1 print(x ** y) # Exponentiation: 1000 # String operations first_name = "John" last_name = "Doe" full_name = first_name + " " + last_name print(full_name) # John Doe # String formatting age = 25 message = f"I am {age} years old" print(message) # I am 25 years old
Control Flow
Control flow statements let you control the execution of your program based on conditions.
If Statements
age = 18 if age >= 18: print("You are an adult") elif age >= 13: print("You are a teenager") else: print("You are a child") # Multiple conditions temperature = 25 weather = "sunny" if temperature > 20 and weather == "sunny": print("Perfect day for a picnic!") elif temperature > 20 or weather == "cloudy": print("Good day to go outside") else: print("Maybe stay inside today")
Loops
# For loops fruits = ["apple", "banana", "orange"] for fruit in fruits: print(f"I like {fruit}") # Range function for i in range(5): print(f"Number: {i}") for i in range(1, 6): print(f"Count: {i}") # While loops count = 0 while count < 5: print(f"Count is {count}") count += 1 # Loop with break and continue for i in range(10): if i == 3: continue # Skip 3 if i == 7: break # Stop at 7 print(i)
Functions
Functions help you organize your code into reusable blocks. They make your programs more modular and easier to maintain.
# Basic function def greet(): print("Hello, World!") greet() # Call the function # Function with parameters def greet_person(name): print(f"Hello, {name}!") greet_person("Alice") # Function with return value def add_numbers(a, b): return a + b result = add_numbers(5, 3) print(result) # 8 # Function with default parameters def introduce(name, age=25): print(f"Hi, I'm {name} and I'm {age} years old") introduce("Bob") # Uses default age introduce("Alice", 30) # Uses provided age # Function with multiple return values def get_name_age(): return "John", 28 name, age = get_name_age() print(f"Name: {name}, Age: {age}")
Working with Lists
Lists are one of the most useful data types in Python. They can store multiple items and are very flexible.
# Creating and modifying lists shopping_list = ["milk", "bread", "eggs"] # Adding items shopping_list.append("butter") shopping_list.insert(1, "cheese") print(shopping_list) # ['milk', 'cheese', 'bread', 'eggs', 'butter'] # Accessing items first_item = shopping_list[0] last_item = shopping_list[-1] # Slicing first_three = shopping_list[:3] last_two = shopping_list[-2:] # List methods numbers = [3, 1, 4, 1, 5, 9, 2, 6] numbers.sort() # Sort in place print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9] numbers.reverse() # Reverse in place print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1] # List comprehensions squares = [x**2 for x in range(1, 6)] print(squares) # [1, 4, 9, 16, 25] even_numbers = [x for x in range(1, 11) if x % 2 == 0] print(even_numbers) # [2, 4, 6, 8, 10]
Dictionaries
Dictionaries store data in key-value pairs, making them perfect for representing structured information.
# Creating dictionaries student = { "name": "Alice", "age": 20, "major": "Computer Science", "gpa": 3.8 } # Accessing values print(student["name"]) # Alice print(student.get("age")) # 20 print(student.get("phone", "Not provided")) # Not provided # Modifying dictionaries student["age"] = 21 # Update existing key student["phone"] = "555-1234" # Add new key # Dictionary methods print(student.keys()) # dict_keys(['name', 'age', 'major', 'gpa', 'phone']) print(student.values()) # dict_values(['Alice', 21, 'Computer Science', 3.8, '555-1234']) # Looping through dictionaries for key, value in student.items(): print(f"{key}: {value}") # Dictionary comprehension squares_dict = {x: x**2 for x in range(1, 6)} print(squares_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Practical Example: Grade Calculator
Let's put everything together with a practical example - a grade calculator program.
def calculate_grade(scores): """Calculate the average grade and letter grade""" if not scores: return 0, "No grades" average = sum(scores) / len(scores) if average >= 90: letter = "A" elif average >= 80: letter = "B" elif average >= 70: letter = "C" elif average >= 60: letter = "D" else: letter = "F" return average, letter def main(): """Main program function""" print("Grade Calculator") print("-" * 20) # Get student information student_name = input("Enter student name: ") # Get grades grades = [] while True: grade_input = input("Enter a grade (or 'done' to finish): ") if grade_input.lower() == 'done': break try: grade = float(grade_input) if 0 <= grade <= 100: grades.append(grade) else: print("Please enter a grade between 0 and 100") except ValueError: print("Please enter a valid number") # Calculate and display results if grades: average, letter = calculate_grade(grades) print(f" Results for {student_name}:") print(f"Grades: {grades}") print(f"Average: {average:.2f}") print(f"Letter Grade: {letter}") else: print("No grades entered.") # Run the program if __name__ == "__main__": main()
Next Steps
Congratulations! You've learned the fundamentals of Python programming. Here are some areas to explore next:
- Object-Oriented Programming (Classes and Objects)
- File handling and working with external data
- Error handling with try/except
- Working with modules and packages
- Web development with Flask or Django
- Data analysis with pandas and numpy
🐍 Practice Tip
The best way to learn Python is by writing code every day. Try building small projects like a calculator, password generator, or simple games to reinforce these concepts.