Python Examples

Python Examples for Tutoring

When tutoring Python, real-world examples and hands-on coding help students grasp concepts better. Here’s a collection of basic to advanced Python examples covering key topics.


1. Basic Python Examples

1.1 Hello, World! (First Python Program)

print("Hello, World!")

Concept: print() function to display output.


1.2 Variables and Data Types

name = "Alice"
age = 25
height = 5.6
is_student = True

print(type(name))    # <class 'str'>
print(type(age))     # <class 'int'>
print(type(height))  # <class 'float'>
print(type(is_student))  # <class 'bool'>

Concept: String, Integer, Float, Boolean.


1.3 Taking User Input

name = input("Enter your name: ")
print("Hello, " + name + "!")

Concept: input() function to take user input.


2. Conditional Statements & Loops

2.1 If-Else Condition

num = int(input("Enter a number: "))
if num % 2 == 0:
    print("Even number")
else:
    print("Odd number")

Concept: Conditional if-else statements.


2.2 For Loop (Print Numbers 1 to 5)

for i in range(1, 6):
    print(i)

Concept: for loop with range().


2.3 While Loop (Countdown Timer)

count = 5
while count > 0:
    print(count)
    count -= 1
print("Time's up!")

Concept: while loop with decrement.


3. Functions & Lists

3.1 Creating a Function

def greet(name):
    return "Hello, " + name + "!"

print(greet("Alice"))

Concept: Defining and calling functions.


3.2 List Operations

fruits = ["Apple", "Banana", "Cherry"]
fruits.append("Mango")  # Add item
fruits.remove("Banana")  # Remove item
print(fruits)  # ['Apple', 'Cherry', 'Mango']

Concept: Lists, append(), remove().


4. Object-Oriented Programming (OOP)

4.1 Creating a Class and Object

class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def details(self):
        return f"Car: {self.brand} {self.model}"

car1 = Car("Toyota", "Corolla")
print(car1.details())  # Car: Toyota Corolla

Concept: Classes, Objects, Constructors.


5. File Handling

5.1 Writing to a File

with open("sample.txt", "w") as file:
    file.write("Hello, Python!")

Concept: Writing files using open() with w mode.


5.2 Reading from a File

with open("sample.txt", "r") as file:
    content = file.read()
    print(content)

Concept: Reading files with r mode.


6. Advanced Python Examples

6.1 Exception Handling

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid input! Please enter a number.")

Concept: Try-Except for error handling.


6.2 List Comprehension

squares = [x**2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

Concept: Shorter syntax for loops.


6.3 Web Scraping Example (Using BeautifulSoup)

import requests
from bs4 import BeautifulSoup

url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")

print(soup.title.text)  # Extracts the webpage title

Concept: Scraping web data using requests and BeautifulSoup.


6.4 API Request Example

import requests

response = requests.get("https://api.github.com")
print(response.json())  # Prints GitHub API response

Concept: Fetching API data using requests.


Conclusion

These Python examples provide a structured learning path from basic to advanced concepts. When tutoring, encourage students to experiment with the code, modify examples, and build small projects for hands-on learning.

Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment