PYTHON
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a=4
A = "Sally"
#A will not overwrite a
Get the Type
You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
print(type(x))
print(type(y))
Example(type error):
x=5
y = "John"
print(x + y)
FIX:
print(str(x) + y) # Output: 5John
Python does not have a char data type like C, C++, or Java.
Here’s how Python handles it:
1. Single characters are just strings of length 1.
ch = 'A'
print(type(ch)) # <class 'str'>
DATATYPES:
# 1. Numeric Types
x = 10
y = 3.14
z = 2 + 3j
print(x, type(x)) # int
print(y, type(y)) # float
print(z, type(z)) # complex
print()
# 2. Sequence Types
# String
s = "Hello"
print(s, type(s))
# List
lst = [1, 2, 3]
print(lst, type(lst))
# Tuple
t = (10, 20, 30)
print(t, type(t))
# Range
for i in range(5):
print(i) #01234
# 3. Set Types
x = set((1, 2, 2, 3)) # duplicates removed
print(x, type(x))
# 4. Mapping Type
d = {"name": "Alice", "age": 22}
print(d, type(d))
print(d["name"])
print()
# 5. Boolean Type
flag = True
print(flag, type(flag))
print(10 > 5)
print(10 < 5)
print()
# 6. None Type
n = None
print(n, type(n))
OUTPUT:
10 <class 'int'>
3.14 <class 'float'>
(2+3j) <class 'complex'>
Hello <class 'str'>
[1, 2, 3] <class 'list'>
(10, 20, 30) <class 'tuple'>
[0, 1, 2, 3, 4] <class 'range'>
{'name': 'Alice', 'age': 22} <class 'dict'>
Alice
True <class 'bool'>
True
False
None <class 'NoneType'>
Check String:
To check if a certain phrase or character is present in a string, we can use
the keyword in.
Example 1:
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt) // True
Example 2:
txt = "The best things in life are free!"
print("free" not in txt) // True
What is Operator Precedence?
Operator precedence = the priority order Python follows when evaluating
expressions.
If multiple operators appear in an expression, the one with higher
precedence executes first.
If operators have the same precedence, Python uses associativity (usually
left-to-right).
Python Operator Precedence (from highest → lowest)
1. Parentheses ()
2. Exponents **
3. Unary +, - , ~ (signs, bitwise NOT)
4. Multiplication / Division / Floor Division / Modulus * / // %
5. Addition / Subtraction + -
6. Bitwise shifts << >>
7. Bitwise AND &
8. Bitwise XOR ^
9. Bitwise OR |
10. Comparisons (<, >, <=, >=, ==, !=)
11. Logical NOT not
12. Logical AND and
13. Logical OR or
14. Assignment operators (=, +=, -=, *=, …)
15. Comma (tuple, function arguments)
Python Collections (Arrays)
There are four collection data types in the Python programming language:
• List is a collection which is ordered and changeable. Allows duplicate
members.
• Tuple is a collection which is ordered and unchangeable. Allows
duplicate members.
• Set is a collection which is unordered, unchangeable*, and
unindexed. No duplicate members.
• Dictionary is a collection which is ordered** and changeable. No
duplicate members.
Slicing
1. Definition (Simple Words)
“Slicing is a way to extract a portion of a sequence (like a string, list, or
tuple) by specifying start, end, and step indexes.”
Example String
text = "Python"
Indexes:
P y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
Examples
1. Basic slicing
print(text[0:4]) # Pyt
Output:
Pyth
Starts at index 0, goes up to 4-1 = 3
2. Omitting start or end
print(text[:3]) # Pyt
print(text[2:]) # thon
print(text[:]) # Python (whole string)
3. Negative indexes
print(text[-4:-1]) # tho
print(text[-3:]) # hon
4. Using step
print(text[::2]) # Picks every 2nd character → Pto
print(text[1::2]) # Picks every 2nd character starting at index 1 → yhn
5. Reversing a string
print(text[::-1]) # nohtyP
Step = -1 → move backwards
6. Combining negative indexes and step
print(text[-1::-2]) # nht
• Start from last character (-1), move backwards, step = 2
CODE:
1. Reverse a String (without built-in reverse)
def reverse_string(s):
reverse = ""
for char in s:
reverse = char + reverse
return reverse
print(reverse_string("lavanya")) # Output: aynaval
2. Palindrome Checker
def is_palindrome(s):
return s == s[::-1] # compares original with reversed
print(is_palindrome("madam")) # True
print(is_palindrome("hello")) # False
3. Find Intersection of Two Lists
def intersection(list1, list2):
return list(set(list1) & set(list2))
print(intersection([1, 2, 3, 4], [3, 4, 5, 6])) # [3, 4]
5. Fibonacci Series (first n numbers)
def fibonacci(n):
a, b = 0, 1
result = []
for _ in range(n):
result.append(a)
a, b = b, a + b
return result
print(fibonacci(7)) # [0, 1, 1, 2, 3, 5, 8]
6. Factorial of a Number
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(factorial(5)) # 120
7. Prime Number Check
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
print(is_prime(7)) # True
print(is_prime(10)) # False
8. Find Largest Element in a List
def find_max(lst):
max_val = lst[0]
for num in lst:
if num > max_val:
max_val = num
return max_val
print(find_max([3, 7, 2, 9, 5])) # 9
9. Remove Duplicates from a List
def remove_duplicates(lst):
return list(set(lst))
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5])) # [1, 2, 3, 4, 5]
10. Sum of Digits of a Number
def sum_of_digits(n):
total = 0
while n > 0:
total += n % 10
n //= 10
return total
print(sum_of_digits(12345)) # 15
11. simple calculator
class Calculator:
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
def multiply(self, a, b):
return a * b
def divide(self, a, b):
try:
return a / b
except ZeroDivisionError:
return "Error: Division by zero!"
# Example usage
calc = Calculator()
print(calc.add(10, 5)) # 15
print(calc.subtract(10, 5)) # 5
print(calc.multiply(10, 5)) # 50
print(calc.divide(10, 0)) # Error: Division by zero!
12. count of all occurrences
def count_characters(s):
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
return char_count
# Example
print(count_characters("hello world"))
# Output: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
EXCEPTION:
An exception in Python is an unexpected event or error that happens
during program execution and disrupts the normal flow of the program.
Instead of the program crashing, we can handle exceptions using try,
except, finally, and raise.
🔹 1. Division by Zero
try:
a = 10
b=0
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed!")
🔹 2. Handling Wrong Input (ValueError)
try:
num = int(input("Enter a number: ")) # if input is "abc", error occurs
print("Square:", num * num)
except ValueError:
print("Error: Please enter a valid integer!")
🔹 3. File Not Found Error
try:
f = open("non_existing_file.txt", "r")
content = f.read()
f.close()
except FileNotFoundError:
print("Error: File not found!")
4. Using finally (always runs)
try:
x = int("123a") # invalid conversion
except ValueError:
print("Error: Cannot convert to integer")
finally:
print("This block always runs")
1. Decorators
Definition
A decorator in Python is a function that takes another function as input,
adds some extra behavior, and returns the modified function — without
changing the original code.
They are written using the @decorator_name syntax.
Simple Code Example
def my_decorator(func): # decorator function
def wrapper():
print("Before function runs")
func()
print("After function runs")
return wrapper
@my_decorator
def say_hello(): # normal function
print("Hello!")
say_hello()
Output:
Before function runs
Hello!
After function runs
The decorator wrapped say_hello() with extra print statements.
2. Generators
Definition
A generator is a special type of function that uses yield instead of return.
• It returns values one at a time when requested.
• Saves memory because it doesn’t generate the whole sequence at
once.
Simple Code Example
def my_generator():
yield 1
yield 2
yield 3
for value in my_generator():
print(value)
Output:
Here, the function pauses at each yield and continues from there next
time.
BASICS:
https://www.w3schools.com/python/