Full Stack Python
Full Stack Python
Input/Output
Example:
Example:
Example:
numbers = {1, 2, 3, 2, 1}
print(numbers) # Output: {1, 2, 3} (duplicates removed)
Example:
3.2 Example:
age_str = "25"
age_int = int(age_str) # Convert from str to int
num = 10
num_str = str(num) # Convert int to str
Example:
name = "Devita"
age = 24
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Devita and I am 24 years old.
Example Solution:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
city = input("Enter your city: ")
Summary Table
Concept Description Example
PythonOperators —
Introduction
"In Python, operators are special symbols or keywords that carry
out operations on values and variables. Operators are essential
because they allow us to manipulate data, perform calculations,
make decisions, and control flow."
1. Arithmetic Operators
Purpose: Perform mathematical calculations.
+ Addition 5+3 8
- Subtraction 5 - 3 2
* Multiplicati 5*3 15
on
// Floor 5 // 2 2
Division
(int)
% Modulo 5%2 1
(remainder)
** Exponentia 5 ** 2 25
tion
Example:
a = 10
b=3
print("a + b =", a + b) # 13
print("a - b =", a - b) #7
print("a * b =", a * b) # 30
Important Notes:
2. Assignment Operators
Purpose: Assign values to variables, or update existing
variables.
Operator Description Example Equivalent to
Example:
x=5
x += 3 #x=8
print(x)
x *=g 2 # x = 16
print(x)
Important Notes:
3. Comparison Operators
Purpose: Compare two values; result is always a Boolean (True or
False).
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
Example:
print(5 == 5) # True
print(5 != 3) # True
Important Notes:
4. Logical Operators
Purpose: Combine multiple Boolean expressions or invert
Boolean values.
Example:
a = True
b = False
Important Notes:
5. Membership Operators
Purpose: Check if a value is present (or absent) in a collection
like a list, tuple, string, set, or dictionary keys.
Example:
my_list = [1, 2, 3, 4]
6. Identity Operators
Purpose: Compare if two variables point to the same object in
memory (not just equal values).
Example:
x = [1, 2]
y = [1, 2]
z=x
Important Notes:
Tips
● Use arithmetic operators for math.
Operator Precedence
Operators have precedence (priority). For example, ** has higher
precedence than * or +.
Example:
python
CopyEdit
result = 2 + 3 * 4
10 Comparison ==, !=, >, <, >=, <=, is, Left to right
Operators is not, in, not in
● 1. Parentheses ( )
● Used to group expressions and override default
precedence.
●
● print((2 + 3) * 4) # Outputs: 20 (parentheses force 2+3 to
happen first)
●
●
● 2. Exponentiation **
● Evaluated right to left.
●
● print(2 ** 3 ** 2) # 3**2 = 9, then 2**9 = 512
●
●
● 3. Unary +, -, ~
● Unary operators applied right to left.
●
● x = -3
● print(+x, -x, ~x) # +(-3) = -3, -(-3) = 3, ~(-3) = 2 (bitwise NOT)
●
●
● 4. Multiplication, Division, Floor Division, Modulo * /
// %
●
● print(10 * 2 / 5 // 1 % 3) # Output: 2.0 (evaluated left to right)
●
●
● 5. Addition, Subtraction + -
●
● print(5 + 3 - 2) # Output: 6
●
●
● 6. Bitwise Shift << >>
●
● print(2 << 2) # 2 * 2^2 = 8
● print(8 >> 2) # 8 / 2^2 = 2
●
●
● 7. Bitwise AND &
●
● print(5 & 3) # 101 & 011 = 001 = 1
●
●
● 8. Bitwise XOR ^
●
● print(5 ^ 3) # 101 ^ 011 = 110 = 6
●
●
● 9. Bitwise OR |
●
● print(5 | 3) # 101 | 011 = 111 = 7
●
●
● 10. Comparison Operators == != > < is in
●
● print(5 > 3 and 3 != 2) # Output: True
● print(5 is 5, 'a' in 'abc') # True, True
●
●
● 11. Logical NOT not
●
● print(not True) # Output: False
●
●
● 12. Logical AND and
●
● print(True and False) # Output: False
●
●
● 13. Logical OR or
●
●
● print(False or True) # Output: True
●
●
● 14. Conditional Expression x if cond else y
●
● x = 10
● y = 20
● print(x if x > y else y) # Output: 20
●
●
● 15. Assignment = += -= ...
●
● a = 5
● a += 2
● print(a) # Output: 7
●
●
● 16. Lambda Expression
●
●
● f = lambda x: x * 2
● print(f(5)) # Output: 10
●
●
CopyEdit
print(3 + 4 * 2) # 3 + (4*2) = 3 + 8 = 11
Example 2:
python
CopyEdit
print(3 ** 2 ** 2) # 3 ** (2 ** 2) = 3 ** 4 = 81
Example 3:
python
CopyEdit
print(-3 ** 2) # -(3 ** 2) = -9
Example 4:
python
CopyEdit
1. if Statement
What is it?
The if statement is used to execute a block of code only if a
condition is true.
When to use?
Use it when you want to perform an action only if a specific
condition is met.
If (cond):
Syntax:
print ("yes")
print("no")
else: # otherwise
If a>9:
print("greater")
else:
print("lesser")
Example 1:
age = 18
Example 2:
temperature = 25
Example 3:
password = "admin123"
if password == "admin123":
print("Access granted.")
2. if-else Statement
What is it?
Executes one block of code if the condition is true, and another
if it is false.
When to use?
Use when there are two outcomes: one if a condition is true, and
another if false.
Syntax:
if condition:
else:
Example 1:
marks = 60
print("Pass")
else:
print("Fail")
Example 2:
user_input = "yes"
if user_input == "yes":
print("You agreed.")
else:
print("You disagreed.")
Example 3:
number = 5
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
3. if-elif-else Ladder
What is it?
Checks multiple conditions in sequence. Executes the first
condition that is true.
When to use?
Use when you have more than two possible outcomes.
Syntax:
if condition1:
# code block
elif condition2:
# another block
elif condition3:
# another block
else:
# final block
Example 1:
score = 85
print("Grade: A")
elif score >= 80:
print("Grade: B")
print("Grade: C")
else:
print("Grade: D")
Example 2:
day = "Wednesday"
if day == "Monday":
print("Weekend is near.")
print("Weekend!")
else:
Example 3:
temperature = 15
print("Nice weather.")
print("It's cool.")
else:
print("It's cold.")
4. Nested if Statements
What is it?
An if block inside another if block. It checks a second-level
condition only if the first is true.
When to use?
Use when decisions depend on multiple layers of logic.
Syntax:
if condition1:
if condition2:
has_id = True
if has_id:
print("Entry allowed.")
Example 2:
username = "admin"
password = "1234"
if username == "admin":
if password == "1234":
print("Login successful.")
Example 3:
num = 10
if num > 0:
if num % 2 == 0:
When to use?
Use only for simple logic that improves readability.
Single-line if Syntax:
if condition: action
x=5
if x > 0: print("Positive number")
print(result)
LOOPS IN PYTHON
What is a Loop?
A loop is a programming construct that repeats a block of code
multiple times, as long as a certain condition is true.
• while loops
• for loops
How it works:
1. The condition is checked first.
Syntax:
while condition:
# Statements to be repeated
Example:
i = 1
while i <= 5:
print(i)
i += 1
Output:
1,2,3,4,5
i Value Condition (i Action
<= 5)
1 True print 1, i = 2
2 True print 2, i = 3
3 True print 3, i = 4
4 True print 4, i = 5
5 True print 5, i = 6
Example 2
i=0
while i < 5: # print "Neha" – 5 times!
print("Neha")
i=i+1
● A tuple
● A string
● A range of numbers
Syntax:
Example:
l = [1, 7, 8]
for item in l:
print(item)
Flow:
3. print(item)
How it works:
Iteration Value of Action
item
1st 1 print(1)
2nd 7 print(7)
3rd 8 print(8)
Output:
1,7,8
for i in range(5):
print(i)
Output:
0,1,2,3,4
print(i) # prints 0 to 6
Output:
Index: 0 Value: 10
Index: 1 Value: 20
Index: 2 Value: 30
Important Points:
● for loop is used when you know how many times to repeat.
loops exhausts.
Example:
l= [1,7,8]
for item in l:
print(item)
else:
done
Syntax
for item in iterable:
if condition:
while condition:
if condition2:
Example:
for i in range (0,80):
print(i) # this will print 0,1,2 and 3
if i==3
Break
if i == 5:
break
print("Current number:", i)
Output:
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Found 5! Breaking the loop.
count = 1
if count == 4:
break
count += 1
Output:
Count is 1
Count is 2
Count is 3
Stopping loop at 4
Note:
● After break, the loop is completely exited.
search = "Devita"
if name == search:
break
for i in range(5)://
if i == 3:
break
print(i)
The continue Statement in Python
Definition:
Syntax:
while condition:
if condition2:
continue
Output:
Odd number: 1
Odd number: 3
Odd number: 5
i = 0
while i < 5:
i += 1
if i == 3:
continue
print("i is", i)
Output:
i is 1
i is 2
i is 4
i is 5
Comparison with break:
Feature break continue
Summary:
1. What is a Function?
A function is a block of code that runs only when it is called. It
helps break programs into smaller, reusable pieces.
2. Function Syntax
def function_name(parameters):
# code block
return result
1.Example:
def greet():
print("Hello, welcome to Python!")
greet("Devita")
Output:
Hello Devita
4. Return Statement
You can use return to return a value from a function.
result = add(5, 3)
print(result) # Output: 8
5. Types of Arguments
Type Description
Examples:
Default Argument:
def greet(name="Guest"):
print("Hello", name)
greet()
greet("Devita")
Variable-length Argument:
def add_all(*numbers):
total = 0
for num in numbers:
total += num
return total
6. Scope of Variables
● Local Variable: Defined inside a function, used
only inside it
x = 10 # Global
def func():
x = 5 # Local
print("Inside:", x)
func()
print("Outside:", x)
Output:
Inside: 5
Outside: 10
Example: Factorial
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
square = lambda x: x * x
print(square(5)) # Output: 25
def outer():
def inner():
print("Inner function")
inner()
outer()
print(args)
print(kwargs)
Summary Chart:
Task:
1. Write a program using functions to find the greatest
of three numbers.
1.Basic Functions
Function Description
Function Description
3.Mathematical Functions
Function Description
Description:
Write a Python program to play Rock, Paper, Scissors
with the user. Use random module to generate computer’s
choice.
Description:
The program randomly picks a number between 1 and 100.
The user must guess the number. After each guess, the
program tells the user whether the guess is too low,
too high, or correct.
Description:
Ask the user to input a number. The computer randomly
chooses one too. If the sum of both is even, the "Even"
player wins, else "Odd" player wins. Alternate
user/computer roles each time.
Description:
Make a basic calculator that takes two numbers and an
operator (+, -, *, /) from the user and returns the
result.
Description:
Create a program where 10 random names are put in a
list. The program randomly selects one as the winner.
Concepts Used: random.choice(), lists, functions
1. What is OOP?
OOP is a programming style based on objects and
classes. It helps you structure code by bundling
data and behavior together.
Key Benefits:
● Reusability
● Scalability
● Organization
● Real-world modeling
Create a Class
To create a class, use the keyword class:
class MyClass:
x = 5
print(MyClass)
Create Object
Now we can use the class named MyClass to create objects:
class MyClass:
x = 5
p1 = MyClass()
print(p1.x)
What is __init__()?
● It is a built-in method.
Imagine you want each student object to have a name and age
assigned as soon as it is created. The __init__() method lets
you do that immediately without needing to call a separate
setup function.
class ClassName:
self.property1 = parameter1
self.property2 = parameter2
class Student:
def display(self):
print("Name:", self.name)
print("Age:", self.age)
student1.display()
student2.display()
Output:
Name: Devita
Age: 22
Name: Ishita
Age: 25
class Student:
self.name = name
self.age = age
def display(self):
print("Name:", self.name)
print("Age:", self.age)
student1 = Student()
student2 = Student("Devita")
student1.display()
student2.display()
student3.display()
l=[student1,student2,student3]
Output:
Name: Unknown
Age: 18
Name: Devita
Age: 18
Name: Ishita
Age: 25
Syntax:
class Parent:
def func1(self):
class Child(Parent):
def func2(self):
print("This is Child class")
# Code
# Code
TYPES OF INHERITANCE
• Single inheritance
• Multiple inheritance
• Multilevel inheritance
SINGLE INHERITANCE
Single inheritance occurs when child class inherits only a single parent
class
Base
||
Derived
# Parent Class
class Animal:
def speak(self):
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
Dog can use both speak() (from Animal) and bark() (its own method).
MULTIPLE INHERITANCE
Multiple Inheritance occurs when the child class inherits from more than
one parent classes.
Example:
# First Parent Class
class Father:
def skills(self):
class Mother:
def skills(self):
def own_skills(self):
c = Child()
3.MULTILEVEL INHERITANCE
class Grandfather:
def show_grandfather(self):
class Father(Grandfather):
def show_father(self):
class Son(Father):
def show_son(self):
s = Son()
The Son class can access all methods from Father and
Grandfather.
● SUPER() METHOD
Example:
# Parent class
class Person:
def __init__(self):
# Child class
class Student(Person):
def __init__(self):
# Create an object
s = Student()
Why use super()?
Example:
class Animal:
def sound(self):
class Dog(Animal):
def sound(self):
print("Dog barks")
d = Dog()
d.sound()
CLASS METHOD
A class method is a method which is bound to the class and not
the object of the class.
Syntax:
class MyClass:
class_variable = 0
@classmethod
def my_class_method(cls):
print("Accessing class_variable:",
cls.class_variable)
Example:
class Student:
cls.school_name = new_name
# Before changing
print(Student.school_name)
Student.change_school("XYZ School")
# After changing
print(Student.school_name)
Output:
ABC School
XYZ School
Exception Handling in Python –
1. What is an Exception?
Examples of exceptions:
print(10 / 0) # ZeroDivisionError
int("abc") # ValueError
my_list = [1, 2]
print(my_list[5]) # IndexError
try:
except ExceptionType:
try:
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
Explanation:
try:
print("Result:", result)
except ZeroDivisionError:
except ValueError:
try:
y = 10 / x
except Exception as e:
7. else Clause
The else block executes only if the try block runs
without any exception.
try:
except ValueError:
else:
print("Valid input:", x)
8. finally Clause
try:
f = open("data.txt", "r")
print(f.read())
except FileNotFoundError:
finally:
print("Finished trying to read the file.")
try:
print(10 / num)
print("Error occurred:", e)
try:
a = int(input("Enter A: "))
try:
b = int(input("Enter B: "))
print(a / b)
except ZeroDivisionError:
except ValueError:
else:
print("Access granted.")
class AgeTooSmallError(Exception):
pass
try:
content = file.read()
print(content)
except FileNotFoundError:
finally:
try:
print("Student:", students[index])
except IndexError:
except ValueError:
Keyword Description
Task
● ValueError
● ZeroDivisionError
● Invalid operator
1.
try:
print("Age accepted.")
except ValueError as ve:
print("Error:", ve)
2.class PasswordTooShortError(Exception):
pass
try:
if len(password) < 6:
print("Password accepted.")
except PasswordTooShortError as e:
print("Error:", e)
3.
try:
if num2 == 0:
else:
print("Result:", result)
Multithreading and
Multiprocessing in Python
1. Introduction
What is a Thread?
import threading
import time
def display():
for i in range(5):
time.sleep(1)
# Creating two threads
t1 = threading.Thread(target=display)
t2 = threading.Thread(target=display)
# Starting threads
t1.start()
t2.start()
t1.join()
t2.join()
print("Multithreading complete")
Key Points
● Downloading files
● Web scraping
● Network calls
3. Multiprocessing in Python
What is a Process?
import multiprocessing
import time
def compute():
for i in range(5):
time.sleep(1)
if __name__ == '__main__':
p1 = multiprocessing.Process(target=compute)
p2 = multiprocessing.Process(target=compute)
# Starting processes
p1.start()
p2.start()
p1.join()
p2.join()
print("Multiprocessing complete")
Key Points
● Scientific computing
5. Comparison Table
7. Real-world Examples
import threading
import requests
def download(url):
print(f"Downloading {url}")
response = requests.get(url)
print(f"Finished downloading {url}:
{len(response.content)} bytes")
urls = [
"https://example.com",
"https://example.org",
"https://example.net"
threads = []
t = threading.Thread(target=download,
args=(url,))
threads.append(t)
t.start()
for t in threads:
t.join()
print("All downloads completed")
import multiprocessing
def calculate_squares(numbers):
print(f"Squares: {result}")
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
p =
multiprocessing.Process(target=calculate_squares,
args=(numbers,))
p.start()
p.join()
8. Summary