python
python
Python:
1.Int
2.float
3.boolean
4.string
5.Complex
Collection data types= list, tuple, dictionary, set, forzenset, byte, bytearray,
none, range etc.
OOps concenpt:
I/O system:
1. we can take input through eval and input.
result = eval(input("Enter a mathematical expression: "))
eval doesn't took number as a string. Another Tip💡= eval treat float as
float , int as int and etc.
print("hello, "+first) #this doesnot add space coz here we are just concatinating
two string. so, we had to create a space by ourself.
print("hello,",Name) # this helps to give the space automatically.
print("hello,", sep=" ",end="") # it doesn't work because it needs to be multiple
arguement
#escape sequence:
#special string:
print(f"hello, {Name}")
#capitlize()=> this helps to capitalize 1st letter of the 1st word of the str
#title()=> this helps to capitalize the 1sst letter of the every word
#if you want to do code into the terminal just type the python in the terminal.
x= float(input("what's x?"))
y= float(input("what's y?"))
z=round(x+y,2)
print (f"{z:,}")
print (f"{z:.2f}") #this also helps ot round the number to the two digits
def main():
Name= input("what's your Name?")
def hello(to):
print("hello,", to)
hello(Name)
main()
def main():
x=int(input(" enter a number to get the square: "))
print(f"square of the {x} is ",square(x))
def square(x):
return x**2 #pow(n,2)
main()
chapter 1: conditionals
Ternary operator:
number1=int(input("1st number"))
number2=int(input("2nd number"))
print(greaterNumber)
match(switch):
match name:
case 'harry'| 'ram' | 'sita':
print("bhamake")
case 'arjun':
print("dang")
case 'sandip':
print("kamalPhokhari")
case _:
print("i don't have information.")
def main():
return True if n%2==0 else False or return n%2==0
Tip💡:
even we can return the boolean from the expression so, it can make short
and good practice of code
CHAPTER 2: lOOPS
Loops: It is a special structuree which helps to do same type of work many times in
short and quick period of time.
while loop:
I=3
WHILE I!=0:
PRINT("MOMO")
I-=1
for loop:
eg: of for loop:
str="string"
count=0
for i in str:
if i==str[count]:
print(f"{i}")
count+=1
chapter 3: function()
def Sandip():
....
....
code:
def add(a, b):
return a + b
code:
def greet():
return "Hello, World!"
code:
def say_hello():
print("Hello, World!") # No return value
code:
def display_message(name):
print(f"Hello, {name}!") # No return value
Arguments are passed in the order they appear in the function definition.
Example:
2. Keyword Arguments
Arguments are passed using the parameter name, regardless of their order.
Example:
3. Default Arguments
Arguments have default values, and you can override them if needed.
Example:
4. Variable-Length Arguments
def add(*numbers):
print(sum(numbers))
add(1, 2, 3, 4) # Output: 10
b. **kwargs (Keyworded)
Local Variable
def func():
x = 10 # Local variable
print(x)
func()
# print(x) # Error: x is not accessible outside the function
Global Variable
y = 20 # Global variable
def func():
print(y) # Accessible inside the function
func()
print(y) # Accessible outside the function
def factorial(n):
if n == 0 or n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call
# Example usage
print(factorial(5)) # Output: 120
Example:
1. Basic Lambda Function
square = lambda x: x ** 2
print(square(5)) # Output: 25
add = lambda x, y: x + y
print(add(3, 7)) # Output: 10
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, nums))
print(squares) # Output: [1, 4, 9, 16]
Key Characteristics:
1. map()
Example:
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, nums))
print(squares) # Output: [1, 4, 9, 16]
2. filter()
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [2, 4, 6]
3. reduce()
Example:
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(product) # Output: 24 (1 * 2 * 3 * 4)
function aliasing:
Function aliasing in Python refers to the practice of creating an alternative name
(or alias) for a function. Both the original function name and the alias can be
used interchangeably to call the function.
Example:
def greet(name):
return f"Hello, {name}!"
chapter 4= string
membersip operator=>
s='kathmandu'
if 'kath' in s: it will result in True
tips💡:
like in string during the comparison, pvm compares three things that is case,
length, order so, to be equal all these three should be equal. ascii value of A is
65 and a is 97
strip(): Removes leading and trailing whitespace (or specified characters) from a
string.
Example: " hello ".strip() → "hello".
rjust(): Right-aligns a string within a specified width, padding with spaces (or a
specified character).
Example: "Python".rjust(10) → " Python".
ljust(): Left-aligns a string within a specified width, padding with spaces (or a
specified character).
Example: "Python".ljust(10) → "Python ".
startswith(): Returns True if the string starts with the specified prefix,
otherwise False.
Example: "Python".startswith("Py") → True.
endswith(): Returns True if the string ends with the specified suffix, otherwise
False.
Example: "Python".endswith("on") → True.
capitalize(): Converts the first character of the string to uppercase and the rest
to lowercase.
Example: "python programming".capitalize() → "Python programming".
title(): Converts the first character of each word to uppercase and the rest to
lowercase.
Example: "python programming".title() → "Python Programming".
to check the type of character present in the string:
isalnum(): True if all characters are alphanumeric and not empty.
Example: "Python123".isalnum() → True.
chapter 5= List
Accessing:
accessing list element:
slicing concept and indexing concept
my_list = [1, 2, 3]
print(len(my_list)) # Output: 3
count(): Counts occurrences of a specific element in a list.
my_list = [1, 2, 2, 3]
print(my_list.count(2)) # Output: 2
my_list = [1, 2, 3]
print(my_list.index(2)) # Output: 1
my_list = [1, 2]
my_list.append(3)
print(my_list) # Output: [1, 2, 3]
my_list = [1, 3]
my_list.insert(1, 2)
print(my_list) # Output: [1, 2, 3]
my_list = [1, 2]
my_list.extend([3, 4])
print(my_list) # Output: [1, 2, 3, 4]
my_list = [1, 2, 3]
my_list.remove(2)
print(my_list) # Output: [1, 3]
pop(): Removes and returns the element at a specified position (default is the last
element).
my_list = [1, 2, 3]
print(my_list.pop()) # Output: 3
print(my_list) # Output: [1, 2]
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]
sort(): Sorts the list in ascending order (can use reverse=True for descending).
my_list = [3, 1, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3]
my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []
List Aliasing: List aliasing occurs when multiple variables reference the same list
object in memory. Changes made through one variable affect the other(s).
Example:
list1 = [1, 2, 3]
list2 = list1 # Both refer to the same list
list2.append(4)
print(list1) # Output: [1, 2, 3, 4]
print(list2) # Output: [1, 2, 3, 4]
list comprehensive: A concise way to create lists using a single line of code,
often with a for loop and an optional condition.
Syntax:
[expression for item in iterable if condition]
Examples:
Basic Comprehension:
nums = [1, 2, 3, 4]
squares = [x**2 for x in nums]
print(squares) # Output: [1, 4, 9, 16]
With Condition:
nums = [1, 2, 3, 4]
even_nums = [x for x in nums if x % 2 == 0]
print(even_nums) # Output: [2, 4]
chapter 6=Tuple
denoted by()
insertion order is preserved
indexing
slicing
dynamically growable and shrinkable (X)=> it is not possible
not support mutability
support homogenous and heterogenous element
t=()
t=tuple()
tuple with known element
t=(10,20,30,40,50,60)
t=tuple()
eval()
t=eval(input('enter any tuple: ')
tuple()
t=tuple(l)
(10,20,30,40)
1. len()
2. count()
Definition: Returns the number of times a specific element appears in the tuple.
Example: For the tuple (1, 2, 2, 3), calling count(2) will return 2.
3. index()
Definition: Returns the index of the first occurrence of a specified element in the
tuple. If the element does not exist, an error is raised.
Example: For the tuple (4, 5, 6, 5), calling index(5) will return 1.
4. sorted()
Definition: Returns a new list containing the sorted elements of the tuple in
ascending order (does not modify the original tuple).
Example: For the tuple (3, 1, 4, 2), sorted() will return [1, 2, 3, 4].
5. min()
6. max()
Definition: You can use the * symbol to collect extra elements into a list during
unpacking.
Example:
For a tuple (1, 2, 3, 4), if you unpack it with *, you can get 1, a list of middle
values [2, 3], and 4.
Nested Unpacking
empty set:
s={} not valid in set coz the data type will say this is dict
s=set{} this is valid
set():
l=[10,10,20,3,5,5]
s= set(l) the output will be 10,20,3,5
set operation
union=> s|s1
intersection=>s&s1
difference=>s-s1
symmetric difference=>s^s1
print(s)=>{10,20,100,30,40,5}
update():
s = {1, 2, 3}
s.update([4, 5])
# Result: {1, 2, 3, 4, 5}
copy():
s = {1, 2, 3}
new_set = s.copy()
# Result: new_set = {1, 2, 3}
pop():
s = {1, 2, 3}
popped_item = s.pop()
# Result: popped_item = 1 (could be any element), s = {2, 3}
remove():
Removes a specific element from the set, raises a KeyError if not found.
s = {1, 2, 3}
s.remove(2)
# Result: s = {1, 3}
discard():
Removes a specific element from the set, but does nothing if not found.
s = {1, 2, 3}
s.discard(2)
# Result: s = {1, 3}
clear():
s = {1, 2, 3}
s.clear()
# Result: s = set()
A set comprehension is a concise way to create sets in Python using a single line
of code. It follows the syntax:
Dictionary:
properties:
denoted by '{}'=> key-value pair
indexing & slicing not applicable
supports mutability
value duplicate
. clear()
d = {'a': 1, 'b': 2}
d.clear()
print(d) # Output: {}
2. get(key, default=None)
Returns the value for the specified key. If the key is not found, returns the
default value (or None if not provided).
d = {'a': 1, 'b': 2}
print(d.get('a')) # Output: 1
print(d.get('z')) # Output: None
print(d.get('z', 'NA')) # Output: NA
3. pop(key, default=None)
Removes the specified key and returns its value. If the key is not found, returns
the default value (or raises a KeyError if no default is provided).
d = {'a': 1, 'b': 2}
print(d.pop('a')) # Output: 1
print(d) # Output: {'b': 2}
print(d.pop('z', 'NA')) # Output: NA
4. popitem()
Removes and returns the last key-value pair as a tuple. Raises a KeyError if the
dictionary is empty (in Python 3.7+).
d = {'a': 1, 'b': 2}
print(d.popitem()) # Output: ('b', 2)
print(d) # Output: {'a': 1}
5. keys()
d = {'a': 1, 'b': 2}
print(d.keys()) # Output: dict_keys(['a', 'b'])
To convert to a list:
keys_list = list(d.keys())
print(keys_list) # Output: ['a', 'b']
6. values()
d = {'a': 1, 'b': 2}
print(d.values()) # Output: dict_values([1, 2])
To convert to a list:
values_list = list(d.values())
print(values_list) # Output: [1, 2]
7. copy()
d = {'a': 1, 'b': 2}
copy_d = d.copy()
print(copy_d) # Output: {'a': 1, 'b': 2}
# Modifying the copy won't affect the original
copy_d['a'] = 99
print(d) # Output: {'a': 1, 'b': 2}
8. setdefault(key, default=None)
If the key exists, returns its value. If the key does not exist, adds the key with
the specified default value and returns the default.
d = {'a': 1, 'b': 2}
print(d.setdefault('a', 10)) # Output: 1
print(d.setdefault('z', 10)) # Output: 10
print(d) # Output: {'a': 1, 'b': 2, 'z': 10}
9. update([other])
Updates the dictionary with the key-value pairs from another dictionary or an
iterable of key-value pairs. If a key already exists, its value is updated.
d = {'a': 1, 'b': 2}
d.update({'b': 20, 'c': 30})
print(d) # Output: {'a': 1, 'b': 20, 'c': 30}
del keyword
Use del with the key you want to remove from the dictionary.
dictionary comprehension:
Basic Syntax:
Tip💡:
✅file.write("\n".join(lines)) # Joins list with newlines
✅seek() → Moves the cursor.
✅ tell() → Shows where the cursor is.