"Learn Python from basics to advanced level"
Python is a versatile, high-level programming language used for web development, data science, automation, and more.
print("Hello, World!")
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
is_active = True # Boolean
nums = [1,2,3] # List
person = {"name":"Bob","age":25} # Dictionary
a, b = 10, 5
print(a + b) # 15
print(a - b) # 5
print(a * b) # 50
print(a / b) # 2.0
print(a % b) # 0
print(a > b) # True
age = 18
if age >= 18:
print("Adult")
else:
print("Minor")
# For loop
for i in range(5):
print(i)
# While loop
j = 0
while j < 5:
print(j)
j += 1
def greet(name):
return "Hello " + name
print(greet("Alice"))
# Lambda
add = lambda x, y: x + y
print(add(2,3))
fruits = ["apple","banana","cherry"]
fruits.append("orange")
print(fruits[0])
for f in fruits:
print(f)
person = {"name":"Alice","age":25}
print(person["name"])
person["age"] = 30
for k,v in person.items():
print(k, v)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, I am {self.name}")
p1 = Person("Alice", 25)
p1.greet()
# Write
with open("test.txt", "w") as f:
f.write("Hello File")
# Read
with open("test.txt", "r") as f:
print(f.read())
try:
x = 10 / 0
except ZeroDivisionError as e:
print("Error:", e)
finally:
print("Done")
# math module
import math
print(math.sqrt(16))
# custom module
# utils.py
def add(a,b): return a+b
# main.py
from utils import add
print(add(2,3))
python -m venv myenv
source myenv/bin/activate # Linux/Mac
myenv\Scripts\activate # Windows
pip install requests
pip list
pip uninstall requests
class Animal:
def speak(self):
print("Some sound")
class Dog(Animal):
def speak(self):
print("Woof!")
d = Dog()
d.speak()
def my_decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
def counter():
for i in range(3):
yield i
for val in counter():
print(val)
import asyncio
async def hello():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(hello())