Python Exercises šŸŽÆ

beginner
17 min

Python Exercises šŸŽÆ

Welcome to the Python Exercises lesson! In this comprehensive guide, we'll dive deep into Python programming, covering basic and intermediate concepts with practical examples. Let's get started!

Introduction to Python šŸ“

Python is a popular, easy-to-learn, and powerful programming language. It's great for beginners because of its clear syntax and readability. Python is used in various fields, including web development, data analysis, artificial intelligence, and more!

Python Basics

  • Variables: These are used to store data in Python. For example:
python
my_variable = 5 print(my_variable) # Output: 5

šŸ’” Pro Tip: Always give meaningful names to your variables.

  • Data Types: Python has several data types like integers, floats, strings, lists, and dictionaries.

Control Structures šŸ’”

Control structures help us control the flow of our code. Let's explore two common ones: if and for loops.

if Statements

python
age = 20 if age >= 18: print("You are an adult.") else: print("You are a minor.")

for Loops

python
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)

Functions šŸ’”

Functions allow us to group related code and make our programs more modular.

python
def greet(name): print(f"Hello, {name}!") greet("John") # Output: Hello, John!

Practical Examples šŸ’”

Let's put our knowledge into practice by solving some exercises.

Exercise 1: Simple Calculator

Create a simple calculator that takes two numbers and performs addition, subtraction, multiplication, and division.

python
def calculator(): num1 = float(input("Enter first number: ")) operator = input("Enter operator (+, -, *, /): ") num2 = float(input("Enter second number: ")) if operator == "+": result = num1 + num2 elif operator == "-": result = num1 - num2 elif operator == "*": result = num1 * num2 elif operator == "/": result = num1 / num2 else: print("Invalid operator. Please try again.") return print(f"The result is: {result}") calculator()

Exercise 2: Fibonacci Sequence

Create a program that generates the Fibonacci sequence up to a given number.

python
def fibonacci(n): sequence = [0, 1] while len(sequence) < n: next_number = sequence[-1] + sequence[-2] sequence.append(next_number) return sequence n = int(input("Enter the number of terms in the Fibonacci sequence: ")) fib_sequence = fibonacci(n) print(f"The Fibonacci sequence up to {n} terms is: {fib_sequence}")
Quick Quiz
Question 1 of 1

What does Python's `if` statement do?

That's it for our Python exercises! We've covered the basics and some practical examples to help you get started with Python programming. Keep practicing, and happy coding! šŸš€