Home Backend Development Python Tutorial Day Python Control Structures, Functions, Modules, and Data Structures

Day Python Control Structures, Functions, Modules, and Data Structures

Dec 14, 2024 am 02:30 AM

Day Python Control Structures, Functions, Modules, and Data Structures

Day 2: 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!


Python Control Structures Recap

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.")
Copy after login
Copy after login

Functions in Python

Functions are blocks of reusable code that perform specific tasks.

1. Defining and Calling Functions

def greet(name):
    return f"Hello, {name}!"

print(greet("Arjun"))
Copy after login
Copy after login
  • Defining: Use def followed by the function name and parameters.
  • Calling: Use the function name with arguments to execute it.

2. Function Arguments and Return Values

  • Arguments: Input values passed to the function.
  • Return Values: Results returned by the function.

Example:

def add_numbers(a, b):
    return a + b

result = add_numbers(5, 3)
print(f"The sum is {result}.")
Copy after login

Modules in Python

Modules are collections of functions and variables. Python has built-in modules, and you can create your own.

1. Using Built-In Modules

import math
import random

print(math.sqrt(16))  # Square root of 16
print(random.randint(1, 10))  # Random number between 1 and 10
Copy after login

2. Writing Your Own Module

Save the following in a file named calculator.py:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b
Copy after login

Use it in another script:

from calculator import add, subtract

print(add(10, 5))  # Output: 15
print(subtract(10, 5))  # Output: 5
Copy after login

Data Structures in Python

Python provides versatile data structures like lists, tuples, sets, and dictionaries for managing data.

1. Lists

A list is a collection of ordered, mutable items.

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits[1])  # Access item at index 1
Copy after login

2. Tuples

Tuples are immutable lists.

dimensions = (10, 20, 30)
print(dimensions[0])  # Access item at index 0
Copy after login

3. Sets

Sets are unordered collections of unique items.

numbers = {1, 2, 3, 3}
numbers.add(4)
print(numbers)  # Output: {1, 2, 3, 4}
Copy after login

4. Dictionaries

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.")
Copy after login
Copy after login

Practice Example: Real-World Application

Create a dictionary to store and retrieve user information:

def greet(name):
    return f"Hello, {name}!"

print(greet("Arjun"))
Copy after login
Copy after login

Conclusion

Today, we:

  1. Wrapped up control structures.
  2. Explored the power of functions and learned to create reusable code.
  3. Leveraged modules for efficiency, including writing custom ones.
  4. Learned about Python's versatile data structures.

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

What is the reason why pipeline files cannot be written when using Scapy crawler? What is the reason why pipeline files cannot be written when using Scapy crawler? Apr 02, 2025 am 06:45 AM

Discussion on the reasons why pipeline files cannot be written when using Scapy crawlers When learning and using Scapy crawlers for persistent data storage, you may encounter pipeline files...

See all articles