Home >Backend Development >Python Tutorial >Day Python Control Structures, Functions, Modules, and Data Structures
Welcome to Day 2! Today, we’ll not only wrap up Python’s control structures but also explore functions, modules, and fundamental data structures. By the end, you’ll be equipped to build efficient, reusable, and organized code. Let’s get started!
We learned how if, elif, and else help us make decisions and how loops (for and while) help repeat tasks. Here's a quick practice problem for reinforcement:
Challenge: Write a program that checks whether numbers from 1 to 10 are odd or even.
for i in range(1, 11): if i % 2 == 0: print(f"{i} is even.") else: print(f"{i} is odd.")
Functions are blocks of reusable code that perform specific tasks.
def greet(name): return f"Hello, {name}!" print(greet("Arjun"))
Example:
def add_numbers(a, b): return a + b result = add_numbers(5, 3) print(f"The sum is {result}.")
Modules are collections of functions and variables. Python has built-in modules, and you can create your own.
import math import random print(math.sqrt(16)) # Square root of 16 print(random.randint(1, 10)) # Random number between 1 and 10
Save the following in a file named calculator.py:
def add(a, b): return a + b def subtract(a, b): return a - b
Use it in another script:
from calculator import add, subtract print(add(10, 5)) # Output: 15 print(subtract(10, 5)) # Output: 5
Python provides versatile data structures like lists, tuples, sets, and dictionaries for managing data.
A list is a collection of ordered, mutable items.
fruits = ["apple", "banana", "cherry"] fruits.append("orange") print(fruits[1]) # Access item at index 1
Tuples are immutable lists.
dimensions = (10, 20, 30) print(dimensions[0]) # Access item at index 0
Sets are unordered collections of unique items.
numbers = {1, 2, 3, 3} numbers.add(4) print(numbers) # Output: {1, 2, 3, 4}
Dictionaries store key-value pairs.
for i in range(1, 11): if i % 2 == 0: print(f"{i} is even.") else: print(f"{i} is odd.")
Create a dictionary to store and retrieve user information:
def greet(name): return f"Hello, {name}!" print(greet("Arjun"))
Today, we:
Practice these concepts thoroughly, as they form the backbone of Python programming. Tomorrow, we’ll delve into file handling and exception management to take your skills further. ?
The above is the detailed content of Day Python Control Structures, Functions, Modules, and Data Structures. For more information, please follow other related articles on the PHP Chinese website!