Python Examples

Python is one of the most versatile and beginner-friendly programming languages. To master Python, it’s crucial to understand how to apply its features in real-world scenarios. In this post, we’ll showcase a variety of Python examples, from basic syntax to advanced applications, to help you learn and practice effectively.

At The Coding College, we provide practical Python tutorials to empower your coding journey.

Table of Contents

  1. Hello World Example
  2. Basic Arithmetic
  3. Working with Strings
  4. Conditional Statements
  5. Loops in Python
  6. Functions
  7. Working with Lists
  8. File Handling Example
  9. Python and Databases
  10. Advanced Python Examples

1. Hello World Example

The classic first step in any programming language.

# Print "Hello, World!" to the console  
print("Hello, World!")  

2. Basic Arithmetic

Performing calculations is simple with Python.

# Addition, subtraction, multiplication, and division  
a = 10  
b = 5  

print("Addition:", a + b)  
print("Subtraction:", a - b)  
print("Multiplication:", a * b)  
print("Division:", a / b)  

3. Working with Strings

Manipulate and format text easily.

# String operations  
name = "The Coding College"  
print("Uppercase:", name.upper())  
print("Lowercase:", name.lower())  
print("Reversed:", name[::-1])  

4. Conditional Statements

Make decisions in your code using if, elif, and else.

age = 20  

if age < 18:  
    print("You are a minor.")  
elif age == 18:  
    print("You just became an adult!")  
else:  
    print("You are an adult.")  

5. Loops in Python

Automate repetitive tasks with loops.

# For loop example  
for i in range(5):  
    print("Iteration:", i)  

# While loop example  
count = 0  
while count < 5:  
    print("Count:", count)  
    count += 1  

6. Functions

Create reusable code blocks.

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

print(greet("Student"))  # Output: Hello, Student!  

7. Working with Lists

Store and manipulate collections of data.

# List example  
fruits = ["apple", "banana", "cherry"]  
fruits.append("orange")  

for fruit in fruits:  
    print(fruit)  

8. File Handling Example

Learn how to read and write to files.

# Write to a file  
with open("example.txt", "w") as file:  
    file.write("Hello, World!")  

# Read from a file  
with open("example.txt", "r") as file:  
    content = file.read()  
    print(content)  

9. Python and Databases

Connect Python to databases for real-world applications.

import sqlite3  

# Connect to database  
connection = sqlite3.connect("example.db")  
cursor = connection.cursor()  

# Create table  
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER, name TEXT)")  

# Insert data  
cursor.execute("INSERT INTO users (id, name) VALUES (1, 'Alice')")  
connection.commit()  

# Query data  
cursor.execute("SELECT * FROM users")  
print(cursor.fetchall())  

connection.close()  

10. Advanced Python Examples

Here are some advanced examples:

a. List Comprehension

# Generate squares of even numbers  
squares = [x**2 for x in range(10) if x % 2 == 0]  
print(squares)  

b. Using Classes

class Person:  
    def __init__(self, name):  
        self.name = name  

    def greet(self):  
        return f"Hi, I am {self.name}."  

p = Person("Alice")  
print(p.greet())  

c. Exception Handling

try:  
    result = 10 / 0  
except ZeroDivisionError:  
    print("Cannot divide by zero!")  

Explore More Python Examples

Python’s simplicity and versatility allow you to create anything from simple scripts to complex systems. These examples are just the beginning. Visit The Coding College for more in-depth tutorials and examples to enhance your coding skills.

Leave a Comment