python

Live URL: https://aminbiography.github.io/python/


python.py


Essential Python Concepts with Examples and Outputs

Python Basics

print, input, variables, if-else, loops, functions, lists, dictionaries, import, try-except

01: Printing and Input

print("Hello, World!")
Output:
Hello, World!
name = "Alice"  # Simulated input
print("Hello,", name)
Output:
Hello, Alice

02: Variables and Data Types

age = 25
name = "Alice"
pi = 3.14
is_active = True
print(age, name, pi, is_active)
Output:
25 Alice 3.14 True
print(type(name))
Output:
<class 'str'>

03: Conditional Statements

age = 15
if age >= 18:
    print("Adult")
elif age > 12:
    print("Teen")
else:
    print("Child")
Output:
Teen

04: Loops

for i in range(5):
    print(i)
Output:
0
1
2
3
4
count = 0
while count < 5:
    print(count)
    count += 1
Output:
0
1
2
3
4

05: Functions

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

print(greet("Alice"))
Output:
Hello, Alice!

06: Lists

fruits = ["apple", "banana", "cherry"]
print(fruits[0])
Output:
apple
fruits.append("orange")
fruits.remove("banana")
print(fruits)
Output:
['apple', 'cherry', 'orange']

07: Dictionaries

person = {"name": "Bob", "age": 30}
print(person["name"])
Output:
Bob
person["city"] = "New York"
del person["age"]
print(person)
Output:
{'name': 'Bob', 'city': 'New York'}

08: Importing Modules

import math
print(math.sqrt(16))
Output:
4.0
from math import pi
print(pi)
Output:
3.141592653589793

09: File Handling

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

with open("file.txt", "r") as f:
    content = f.read()
    print(content)
Output:
Hello, file!

10: Exception Handling

try:
    num = 5
    print(10 / num)
except ZeroDivisionError:
    print("Cannot divide by zero.")
except ValueError:
    print("Invalid input.")
Output:
2.0

11: Classes and Objects

class Person:
    def __init__(self, name):
        self.name = name
    def greet(self):
        print(f"Hello, my name is {self.name}.")

p = Person("Alice")
p.greet()
Output:
Hello, my name is Alice.

12: List Comprehensions

numbers = [x**2 for x in range(5)]
print(numbers)
Output:
[0, 1, 4, 9, 16]

13: Lambda Functions

square = lambda x: x**2
print(square(4))
Output:
16

14: Map, Filter, Reduce

nums = [1, 2, 3, 4]
print(list(map(lambda x: x*2, nums)))
Output:
[2, 4, 6, 8]
print(list(filter(lambda x: x%2==0, nums)))
Output:
[2, 4]
from functools import reduce
print(reduce(lambda a, b: a+b, nums))
Output:
10

15: Virtual Environments

python -m venv env
source env/bin/activate   # Linux/Mac
env\Scripts\activate      # Windows

python.py