# Arithmeticsum=1+2# Additiondiff=5-3# Subtractionprod=2*3# Multiplicationquot=10/2# Divisionmod=10%3# Modulus# Assignmentx=10x+=5# x = x + 5x-=3# x = x - 3x*=2# x = x * 2x/=2# x = x / 2# Comparisonis_equal=(1==1)# Trueis_not_equal=(1!=2)# Trueis_greater=(5>3)# Trueis_lesser=(3<5)# True
Control Structures
# Conditional Statementsifa>b:# code if trueelifa==b:# code if equalelse:# code if false# Loops# For Loopforiinrange(5):# code# While Loopwhilea<10:# codea+=1
Functions
# Function Definitiondefgreet(name):return"Hello, "+name# Function Callgreet("John")
Lists
fruits=["Apple","Banana","Cherry"]# Access Elementsfirst_fruit=fruits[0]# List Methodsfruits.append("Orange")# Add to endfruits.pop()# Remove from endfruits.remove("Banana")# Remove specific elementsliced=fruits[1:3]# Slice list# Loop through Listforfruitinfruits:print(fruit)
Dictionaries
person={"name":"John","age":30}# Access Valuesname=person["name"]# Add/Modify Valuesperson["email"]="john@example.com"# Loop through Dictionaryforkey,valueinperson.items():print(key,value)
# Write to Filewithopen("file.txt","w")asfile:file.write("Hello, World!")# Read from Filewithopen("file.txt","r")asfile:content=file.read()
Classes
# Class DefinitionclassPerson:def__init__(self,name,age):self.name=nameself.age=agedefgreet(self):return"Hello, "+self.name# InheritanceclassStudent(Person):def__init__(self,name,age,grade):super().__init__(name,age)self.grade=gradedefstudy(self):returnself.name+" is studying."# Create Objectstudent=Student("John",20,"A")print(student.greet())print(student.study())
Modules
# Importing Modulesimportmath# Using Functions from Modulesresult=math.sqrt(16)# 4.0# Importing Specific Functionsfrommathimportsqrtresult=sqrt(16)# 4.0
Exception Handling
try:# code that might raise an exceptionresult=10/0exceptZeroDivisionError:# code that runs if exception occursprint("Cannot divide by zero")finally:# code that always runsprint("This is the finally block")
List Comprehensions
# Basic List Comprehensionsquares=[x**2forxinrange(10)]# Conditional List Comprehensionevens=[xforxinrange(10)ifx%2==0]