Python Programming Tutorial

 

Python is widely considered the best programming language for machine learning. It has gained immense popularity in the field of data science and machine learning.

  • Python basics, Variables, Operators, Conditional Statements

1. Python Basics

# Print a message
print("Welcome to Python Programming!")

Output:

Welcome to Python Programming!

2. Variables

# Variables are containers for storing data
name = "Alice"      # String
age = 25            # Integer
height = 5.5        # Float
is_student = True   # Boolean

print(f"Name: {name}, Age: {age}, Height: {height}, Student: {is_student}")

Output:

Name: Alice, Age: 25, Height: 5.5, Student: True


3. Operators


# Arithmetic Operators
x, y = 10, 3
print("Addition:", x + y)
print("Division:", x / y)

# Comparison Operators
print("Is x greater than y?", x > y)

# Logical Operators
a, b = True, False
print("a and b:", a and b)
print("a or b:", a or b)

Output:

Addition: 13
Division: 3.3333333333333335
a and b: False
a or b: True

4. Conditional Statements

age = 18
if age >= 18:
    print("You are an adult.")
elif 13 <= age < 18:
    print("You are a teenager.")
else:
    print("You are a child.")

Output:

You are an adult.


  • List and Strings

1. Lists

# Lists are mutable collections
fruits = ["apple", "banana", "cherry"]
print("Original List:", fruits)

# Add, remove, and access elements
fruits.append("orange")
print("After Adding:", fruits)
print("Second Fruit:", fruits[1])

Output:

Original List: ['apple', 'banana', 'cherry']
After Adding: ['apple', 'banana', 'cherry', 'orange']
Second Fruit: banana


2. Strings

# Strings are immutable sequences of characters
greeting = "Hello, Python!"
print("Uppercase:", greeting.upper())
print("Substring:", greeting[7:13])

Output:

Uppercase: HELLO, PYTHON!
Substring: Python


  • Dictionary, Tuple, Set

1. Dictionary

# Dictionary stores key-value pairs
person = {"name": "Alice", "age": 25}
print("Name:", person["name"])
person["age"] = 26  # Update
print("Updated Dictionary:", person)

Output:

Name: Alice
Updated Dictionary: {'name': 'Alice', 'age': 26}

2. Tuple

# Tuples are immutable
colors = ("red", "green", "blue")
print("First Color:", colors[0])

Output:

First Color: red

3. Set

# Sets are unordered collections of unique items
numbers = {1, 2, 3, 3}
print("Set:", numbers)
numbers.add(4)
print("After Adding:", numbers)

Output:

Set: {1, 2, 3}
After Adding: {1, 2, 3, 4}


  • While Loop, Nested Loops, Loop Else

1. While Loop

count = 0
while count < 5:
    print("Count:", count)
    count += 1

Output:

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

2. Nested Loops

for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")

Output:

i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1

3. Loop Else

count = 3
while count > 0:
    print(count)
    count -= 1
else:
    print("Countdown Finished!")

Output:

3
2
1
Countdown Finished!


  • For Loop, Break, and Continue statements

1. For Loop

for i in range(5):
    print("Number:", i)

Output:

Number: 0
Number: 1
Number: 2
Number: 3
Number: 4

2. Break Statement

for i in range(10):
    if i == 5:
        break
    print("Number:", i)

Output:

Number: 0
Number: 1
Number: 2
Number: 3
Number: 4


3. Continue Statement

for i in range(10):
    if i % 2 == 0:
        continue
    print("Odd Number:", i)

Output:

Odd Number: 1
Odd Number: 3
Odd Number: 5
Odd Number: 7
Odd Number: 9


  • Functions, Return Statement, Recursion

1. Functions

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

print(greet("Alice"))

Output:

Hello, Alice!

2. Recursion

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

print("Factorial of 5:", factorial(5))

Output:

Factorial of 5: 120


  • File Handling, Exception Handling

1. File Handling

# Write to a file
with open("sample.txt", "w") as file:
    file.write("Hello, File Handling!")

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

Output:

File Content: Hello, File Handling!

2. Exception Handling

try:
    num = int(input("Enter a number: "))
    print("Square:", num ** 2)
except ValueError:
    print("Invalid Input. Please enter a number.")

Input:

5


Output:

Enter a number: 5
Square: 25


  • Object-Oriented Programming

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

    def greet(self):
        return f"Hi, I'm {self.name} and I'm {self.age} years old."

alice = Person("Alice", 25)
print(alice.greet())

Output:

Hi, I'm Alice and I'm 25 years old.


Comments

Popular posts from this blog

Different Data Plotting

🚀 NumPy Arrays vs Python Lists: Key Differences & Performance Comparison! 🚀