0% found this document useful (0 votes)
145 views

Python Notes

The document provides notes on Python programming concepts including: 1. Variables, data types, input functions and type casting. 2. Strings - indexing, slicing, string methods like lower(), upper(), title(), etc. 3. Control flow statements - if/else conditions, and, or operators, while and for loops. 4. Functions - defining and calling functions. Various examples are given to explain each concept along with exercises to practice the concepts. The document serves as a good reference for Python programming fundamentals.

Uploaded by

vikas
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
145 views

Python Notes

The document provides notes on Python programming concepts including: 1. Variables, data types, input functions and type casting. 2. Strings - indexing, slicing, string methods like lower(), upper(), title(), etc. 3. Control flow statements - if/else conditions, and, or operators, while and for loops. 4. Functions - defining and calling functions. Various examples are given to explain each concept along with exercises to practice the concepts. The document serves as a good reference for Python programming fundamentals.

Uploaded by

vikas
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

………………………………PYTHON NOTES……………………………

#1.varibles………………………………………….

num =2
print(num)
num=4
print(num)
#string,num,int,float
name ="vikas"
print(name)
name=123
print(name)
# cant start variable name with digits 0,1,2,3,4,5,6,7,8,9
#can use undersore as first letter as well as in btw
#_ is only special symbol can be used 
#can use digits in btw
user_one_name ="vikas"          #snake case writing(python convention)
userOneName="vikas"             #camel case writing(java convention)

#2.strings……………………………………………

first_name="vikas"
last_name="yadav"
full_name=first_name+" "+last_name
print(full_name)
print(first_name+str(3)) #string can only sum with string
print(first_name*3)

#3.input……………………………………………………

name=input("type your name")
print("hello "+name)
#input takes string by default
age=input("what is your age ?")
print("your age is"+age)

#4.variables++………………………………………………..

name ,age ="vikas","20"     #declaring two or more variables
print("hello"+name+"your age is "+age)
x=y=z=23
print(x+y+z)

#5.two or more inputs……………………………………………………

name,age=input("enter your name and age").split()
print(name)
print(age)
#should enter space in btw inputs
name,age=input("enter your name and age").split(",")
print(name)
print(age)
#split by , 

#6.int function…………………………………………………………………

num1=int(input("enter first num"))
num2=int(input("enter second num"))
total=num1+num2
print("toatal is "+str(total))
#int , str ,float as type cast operator

#7.string formatting…………………………………………………………

name ,age ,age1="vikas","20",20
print("hello "+name+" your age is "+age)       #ugly syntax
print("hello {} your age is {} ".format(name,age))    #python 3
print(f"hello {name} your age is {age}")     #python 3.6
print(f"hello {name} your age is {age1+2}") 

#8.chapter2 exercise 1…………………………………………………………

#average.py
num1,num2,num3=(input("enter 3 numbers :").split())
print(f"avg of 3 numbers entered : {(int(num1)+int(num2)+int(num3))/3}")

#9.string indexing……………………………………………………………………………

language="python"
#positions
# p =0 , -6
# y =1 , -5
#...
# n =5 , -1
print(language[-1]) #-> n

#10.string slicing………………………………………………………………………

#slicing / selecting sub sequences
lang  = "python"
# syntax - [start : stop +1]
print(lang[0:3])
print(lang[:])      #complete string 
print(lang)         #complete string
print(lang[2:])     #no stop 
print(lang[:3])     #no start
#step argument
#syntax - [start : stop +1 : step]
print(lang[0::2])
print(lang[::1])
print(lang[::-1])    #reverses string trick

#11.chapter 2 exercise 2……………………………………………………………

name=input("enter your name")
print(f"your name in reverse order is  : {name[::-1]}")

#12.string methods…………………………………………………………………………………

# string methods part one 
name="VikaS YadaV"
#1. len() func
length=len(name)
print(length)               # ->11
#2. lower() method
print(name.lower())         # ->vikas yadav
#3. upper() method
print(name.upper())         # ->VIKAS YADAV
#4. title() method
print(name.title())         # ->Vikas Yadav
#5. count() method
print(name.count("a"))      # ->3
#13.chapter 2 exercise 2……………………………………………………………

name,ch=input("enter your name and a sigle character").split(",")
print(f"length of your name is {len(name)}")
print(f"{ch} is present {name.lower().count(ch.lower())} times in your name")

#14. Strip method…………………………………………………………………….

name="     vikas     "
dots="..............."
#strip() methods
print(name+dots)
print(name.lstrip()+dots)
print(name.rstrip()+dots)
print(name.strip()+dots)
print(name.replace(" ","")+dots)

#15. Replace() and find()……………………………………………………………………

string="she is beautiful and she is a good dancer"
print(string.replace("is","was",1)) #replaces 1st “is” only

print(string.find("is",5)) #start searching from 5th pos


is_pos1=string.find("is")
is_pos2=string.find("is",is_pos1+1)

#16. Center method………………………………………………………………………………

#center(total no. of characters in string , ”symbol to be added in both start


and end”) 
name="vikas"
#***vikas*** , 5+6=11
print(name.center(11,"*"))
name =input("enter name : ")
print(name.center(len(name)+6,"*"))

#17. Strings are immutable………………………………………

string="vikas"
string.replace('v','B') #original string cant be changed once declared
print(string) -> vikas
name[1]=”d” #error
#18. If statement…………………………………………………………………………

age=int(input("enter your age : "))
if age>=18:
    print("u r above 18")
if age<18:
    pass      
 #pass statement for not icluding any code after if statement 

#19. Else statement…………………………………………………………

age=int(input("enter your age : "))
if age>=18:
    print("u r above 18")
else:
    print("u r underage")

#20. Chapter 3 exercise 1……………………………………………………………

win_no=23
a=int(input("guess a no. between 1 and 100 : "))
if a==win_no:
    print("congrats u win")
elif a<win_no :
    print("too low")
else :
    print("too high")

#21. And , or statement…………………………………………………………

age=19
name='vikas'
if name=='vikas' and age==19:
    print("and condition true")
else:
    print("and condition false")
if name=='vikas' or age==19:
    print("or condition true")
else:
    print("or condition false")

#22. Chapter 3 exercise 2………………………………………………………………

user_age=int(input("enter your age : "))
user_name=input("enter your name : ")
if user_age>=10 and (user_name[0]=='a' or user_name[0]=='A'):
    print("u can watch coco")
else :
    print("u cannot watch coco")

#23. If elif else statement……………………………………………………………

age=int(input("please enter your age : "))
if age<=0:
    print("u cannot watch")
if 0<age<=3:
    print("ticket price : free")
elif 3<age<=10:
    print("ticket price : 150")
elif 10<age<=60:
    print("ticket price : 250")
else:
    print("ticket price : 200")

#24. In keyword………………………………………………………………………

name='vikas'
if 'a' in name:
    print("a is present in name")
else:
    print("a is not present in name")

#25. Check empty or not………………………………………………………………………

name='vikas'
if name :       #true if not empty
    print("string is not empty")
else:           #if empty
    print("string is empty")

#26. While loop…………………………………………………………………………………

i = 1
while i<=10:
    print(f"hello world {i}")
    i+=1
print(i)

#27. Sum of n natural no…………………………………………………………………

total=0
i=1
n=int(input("enter value of n : "))
while i<=n:
    total+=i
    i+=1
print(f"total = {total}")

#28. Chapter 3 exercise 3………………………………………………………………

a=input("enter a no. : ")
total=0
i=0
while i<len(a):
    total+=int(a[i])
    i+=1
print(f"total = {total}")

#29. Chapter 3 exercise 4……………………………………………………………………

name=input("enter the name")
i=0
temp=""
while i<len(name):
    if name[i] not in temp:
        temp+=name[i]
        print(f"{name[i]} : {name.count(name[i])}")
    i+=1
#30. Infinite loop ……………………………………………………………………

while True:
    print("hacked")     #to abort infinite loop press ctrl+c

#31. For loop………………………………………………………………………………………………

for i in range(10):
    print(f"hello world {i}")        #no increment in loop block
for i in range(1,11):               #(start: stop+1: step)
    print(f"hello world again {i}")

#32. For loop sum of integers

total=0
for i in range(1,11):
    total+=i
print(total)

n=int(input("enter the number"))
total=0
for i in range(1,n+1):
    total+=i
print(total)

#33. For loop practice 1……………………………………………………………………

n=input("enter a number")
total=0
for i in range(0,len(n)):
    total+=int(n[i])
print(total)

#34. For loop practice 2…………………………………………………………………………

name=input("enter your name")
temp=""
for i in range(len(name)):
    if name[i] not in temp:
        print(f"{name[i]} : {name.count(name[i])}")
        temp+=name[i]
#35. Break and continue……………………………………………………………

#break and continue
for i in range(1,11):
    if i==5:
        break           #break exits the execution out of loop
    print(i)

for i in range(1,11):
    if i==5:
        continue
    print(i)            #continue skips the current iteration

#36. Number guessing game……………………………………………………………………

win_number=55
guess=1
num=int(input("guess a number between 1 and 100 : "))
game_over=False
while not game_over:
    if num==win_number:
        print(f"you win, and you guessed in {guess} times")
        break
    else:
        if num < win_number:
            print("too low")
        else :
            print("too high")
        guess+=1                                        #DRY principle 
        num=int(input("guess again :"))     

#37. Step argument in range………………………………………………………

for i in range(0,11,2):
    print(i)
for i in range(10,0,-1):
    print(i)
for i in range(10,-1,-2):
    print(i)

#38. For loop and strings……………………………………………………………………

name="vikas yadav"
for i in name:
    print(i)
num=input("enter a number : ")
total=0
for i in num:
    total+=int(i)
print(total)

#39. Functions………………………………………………………………………

#functions 
def add_two(a,b):
    return a+b

sum=add_two(5,4)
print(add_two(5,4))

a=int(input("enter first num : "))
b=int(input("enter second num : "))
total=add_two(a,b) 
print(total)
 
first_name=input("enter first name : ")
last_name=input("enter last name : ")
print(add_two(first_name,last_name))
 

#40. Functions 2……………………………………………………………………………………………

def add_three(a,b,c):
    print (a+b+c)

add_three(2,4,6)

#41. Function practice……………………………………………………………………………………

def last_char(name):
    return name[-1]

print(last_char("vikas"))

def odd_even(num):
    if num%2==0:
        return "even"
    return "odd"
    
print(odd_even(10))
def is_even(num):
    if num%2==0:
        return True
    return False

def is_even1(num):
    return num%2==0         #returns True or False same as func is_even

print(is_even(9))
print(is_even1(9))

def song():
    return "amplifier imran khan"
print(song())

#42. Chapter 4 exercise 1……………………………………………………………………………

def greater(a,b):
    if a>b:
        return a
    return b

num1=int(input("enter 1st number : "))
num2=int(input("enter 2nd number : "))
bigger=greater(num1,num2)
print(f"{bigger} is greater")

#43. Greatest function…………………………………………………………………………

def greatest(a,b,c):
    if a>b and a>c:
        return a
    elif b>a and b>c:
        return b
    else:
        return c

print(greatest(100,40,30))

#44. Function in function………………………………………………………………………

def greater(a,b):
    if a>b:
        return a
    return b
def new_greatest(a,b,c):
    return greater(greater(a,b),c)

print(new_greatest(10,30,40))

#45. Chapter 4 exercise 2………………………………………………………………….

def is_palindrome(word):
    return word==word[::-1]

print(is_palindrome("nitin"))
print(is_palindrome("vikas"))

#46. Fibonacci series……………………………………………………………………………………

def fibonacci(n):
    a=0     #first num
    b=1     #second num
    if n==1:
        print(a)
    elif n==2:
        print(a, b)
    else :
        print(a,b, end=" ")
        for i in range(n-2):
            c=a+b
            a=b
            b=c
            print(b,end=" ") 
print(fibonacci(10))

#47. Default arguments……………………………………………………………………………………

def user_info(first_name, last_name='unknown', age=None):
    print(f"first name is : {first_name}")
    print(f"last name is : {last_name}")
    print(f"age is : {age}")

user_info('vikas','yadav',20)

#48. LISTS……………………………………………………………………………………………………………………

#list = ordered sequence of items
#we can store aything int ,float, string
numbers=[1,2,3,4,5]
print(numbers)

words=["word1","word2","word3"]
print(words[:2])

mixed=[1,2,3,4,"five","six",None]
print(mixed[-1])

mixed[1:]=['three','four']      #can change the data in list 
print(mixed)

#49. Append method…………………………………………………………………………………………………

fruits=['grapes','apple','mango']
fruits.append('banana')
print(fruits)

foods=[]
foods.append('milk')
foods.append('rice')
print(foods)

#50. Adding data in list……………………………………………………………………………………

#insert , append ,extend methods 

fruits1=['mango','apple']
fruits1.insert(1,'grapes')      #can insert any object at any pos
print(fruits1)

fruits2=['orange']
fruits =fruits1+fruits2         #list concatenation
print(fruits)

fruits1.extend(fruits2)         #extends list by joining another list's elem
ents
print(fruits1)
fruits1.append(fruits2)         #appends list fruits2 as an item in fruits 1
print(fruits1)                  

#51. Split and join method……………………………………………………………………………

#split method
user_info="vikas,yadav,20".split(',')       #splits a string into list
name,surname,age=input("enter your name, surname, age").split(",")  #takes 2 
input seperated by ','
print(name,surname,age)

#join method
user_info=['vikas','yadav','20']
print(' '.join(user_info))                  #list to string

#52. Deletion from list…………………………………………………………………………………

fruits=['apple','orange','pear','banana','kiwi','mango','apple']

#pop method
fruits.pop()         #delete last element
fruits.pop(1) #deletes at specific pos

#del operator
del fruits[1]

#remove method
fruits.remove('banana')
fruits.remove('apple')          #deletes only 1st apple

print(fruits)

#53. Use of ‘in’ in list………………………………………………………………

fruits=['apple','orange','pear','banana','kiwi','mango','apple','pomegranete']
if 'apple' in fruits:
    print("apple is present")
else :
    print("not present")

#54 List methods………………………………………………………………………………………

fruits=['apple','orange','pear','banana','kiwi','mango','apple','pomegranete']
print(fruits.count('apple'))        #count
fruits.sort()                       #sort
print(fruits)
numbers=[3,5,1,9,10]
numbers.sort()
print(numbers)
print(sorted(numbers))            #sorted(doesnt change the original list)
numbers_copy=numbers.copy()      #copy
numbers.clear()                  #clear
print(numbers)
print(numbers_copy)

#55. Compare lists…………………………………………………………………………………………

fruits1=['orange','apple','pear']
fruits2=["orange","apple","pear"]
fruits3=['banana','kiwi','apple','banana']
print(fruits1==fruits2)         #True if all values are same
print(fruits1 is fruits2)       #true if both points to same memory location

#56. Loops in list……………………………………………………………………………………………

fruits=['orange','apple','pear','banan','kiwi']

#for loop
for i in fruits:
    print(i)

#while loop
i=0
while i<len(fruits):
    print(fruits[i])
    i+=1

#57. Nested list………………………………………………………………………………………………

matrix=[[1,2,3],[4,5,6],[7,8,9]]
for sublist in matrix:
    for i in sublist:
        print(i)

print(type(matrix))     #----->    <class list>

#58. More about list…………………………………………………………………………………………………………

numbers= list(range(1,11))      #creating list with range function

print(numbers)
print(numbers.pop())            #shows poped value
print(numbers)
numbers =[1,2,3,4,5,6,7,8,9,10,1,11,2,3]
print(numbers.index(1,2,13))  #searches element 1 start from 2 and stops at 
13
def negative_list(l):
    negative=[]
    for i in l:
        negative.append(-i)
    return negative

print(negative_list(numbers))

#59. Chapter 5 exercise 1………………………………………………………………………………………

def square_list(l):
    square=[]
    for i in l:
        square.append(i**2)
    return square

numbers=list(range(1,11))
print(square_list(numbers))

#60. Chapter 5 exercise 2

def reverse_list(l):         #can be easily done by l.reverse() return rever
se
    reverse=[]               #or return l[::-1] 
    for i in range(len(l)):
        reverse.append(l.pop())     #by using pop and append
    return reverse

numbers=[1,2,3,4,5,6,7,8,9]    
print(reverse_list(numbers))

#61. Chapter 5 exerccise 3……………………………………………………………………………………

def reverse_elements(l):
    elements=[]
    for i in l:
        elements.append(i[::-1])
    return elements

words=['abc','def','ghi']
print(reverse_elements(words))

#62. Chapter 5 exercise 4………………………………………………………………………………

def filter_odd_even(l):
    odd=[]
    even=[]
    for i in l:
        if i%2==0:
            even.append(i)
        else:
            odd.append(i)
    output=[odd,even]
    return output

num=[1,2,3,4,5,6,7,8,9]
print(filter_odd_even(num))

#63. Chapte 5 exercise 5………………………………………………………………………………

def common(l1,l2):
    output=[]
    for i in l1:
        if i in l2:
            output.append(i)
    return output

print(common([1,2,3,4],[1,2,5,6,7]))

#64. Min and max functions………………………………………………………………………………………………………

numbers=[1,2,3,4,5]
print(min(numbers))
print(max(numbers))
def greatest_diff(l):
    return max(l)-min(l)

print(greatest_diff(numbers))

#65. Chapter 5 exercise 6…………………………………………………………………………………………


def sublist_counter(l):
    count=0
    for i in l:
        if type(i)==list:
            count+=1
    return count
mixed=[[1,2,3],[4,5],[6]]
print(sublist_counter(mixed))

#66. TUPLES……………………………………………………………………………………………………………

#tuples are immutable
#cant be updated once created
#tuples are faster than lists

#methods --> count, index, len func, slicing can be used in tuples 


mixed=(1,2,3,4,5)
for i in mixed:
    print(i)

nums=(1,)           #method to declare tuple with 1 element
print(type(nums))

#tuple without paranthesis
guitars='yamaha','baton roughe','taylor'
print(type(guitars))

#tuple unpacking
guitarists=('maneli jamal','Eddie Van Der Meer','Andrew Foy')
guitarist1, guitarist2, guitarist3=(guitarists)

#list inside tuples
favourites=('southern magnolia',['tokyo ghoul theme','landscape'])
favourites[1].pop()
print(favourites)
favourites[1].append('we made it')
print(favourites)

# min ,max ,sum
print(min(mixed))
print(max(mixed))

#67. Functions returning 2 values…………………………………………………………………


def func(i1,i2):
    add=i1+i2
    multiply=i1*i2
    return add,multiply

print(func(2,3))
add,multiply=func(2,3)      #use of tuple unpacking
print(add)
print(multiply)

#68. More on tuple………………………………………………………………………………………………

nums=tuple(range(1,11))
print(nums)
num=str(nums)
print(type(num))
print(num)

#69. Dictionary …………………………………………………………………………………………………

#dictionaries 
#unordered coolections of data in key : value pair
user={'name' : 'vikas', 'age' : 20}
print(user)
print(type(user))

user1=dict(name = 'vikas', age= 24)
print(user1)

#there is no indexing in dict
print(user['name'])         #we use keys to access values
print(user['age'])

#how to add data in empty dictionary
user_info={}
user_info['name']='vikas'
user_info['age']=20

print(user_info)
#70. In and loops on dictionaries………………………………………………………………………………

user={'name' : 'vikas', 'age' : 20}

#check a key in user
if 'name' in user:
    print('present')
else:
    print('not present')

#check a value in user
if 24 in user.values():
    print('present')
else:
    print('not present')

#loop in dict
for i in user:
    print(i)            #prints keys
for i in user.values():
    print(i)           #prints values

#values method
user_values=user.values()
print(user_values)
print(type(user_values))        #type --->dict_values

for i in user:
    print(user[i])              #also prints values

#items method
user_items=user.items()
print(user_items)               #prints (key,value) pairs as tuples in a lis
t
print(type(user_items))         #--> dict_items

for key,value in user.items():
    print(f"key is {key} and value is {value}")

#71. Add and delete data……………………………………………………………………………


user={'name' : 'vikas', 'age' : 20}

#how to add data
user['surname']=['yadav']
print(user)

#pop method
poped=user.pop('surname')           #deletes key value pair and saves value 
in poped 
print(f"poped item is {poped}")         
print(type(poped))                  #--->list

#popitem method
poped=user.popitem()               #deletes key value pair and saves key val
ue pair as tuple in poped
print(poped)
print(type(poped))                  #--->tuple

#72. Update method……………………………………………………………………………………………

user={'name' : 'vikas', 'age' : 20}
more_info={'name': 'vikas yadav', 'state':'delhi','hobbies':
['coding','reading']}
user.update(more_info)

print(user)

#73. Fromkeys , get ,copy ,clear…………………………………………………………………………………

#fromkeys 
#used to make dictionaries
d={'name': 'unknown', 'age': 'unknown',}
d=dict.fromkeys(('name','age','height'),'unknown')
print(d)

d1=dict.fromkeys(range(1,11),'default')
print(d1)

d2=dict.fromkeys(['name','age'],['unknown','unknown'])
print(d2)

#get method
print(d.get('name'))

if d.get('name'):               #get returns None if not found
    print('present')            #and if None---->False
else:
    print('not present')

#copy
d3=d.copy()
print(d3.popitem())
print(d)

#clear 
d.clear()
print(d)

#74. More about get…………………………………………………………………………………………………

user={'name':'vikas','age':20}
print(user.get('names','not found !'))      #by default it returns None but 
we can change it
print(user)

#if list contains more than 1 same keys then the last value is considered

#75. Chapter 7 exercise 1……………………………………………………………………………………………

#cube finder
def cube_finder(i):
    cubes={}
    for i in range(1,i+1):
        cubes[i]=i**3
    return cubes

print(cube_finder(10))
#76. Word counter using dict…………………………………………………………………………………………

#word counter
def word_counter(s):
    count={}
    for char in s:
        count[char]=s.count(char)
    return count

print(word_counter('vikas yadav'))

#77. Chapter 7 exercise 2…………………………………………………………………………………………

user={}
name=input('what is your name')
age=input('what is your age')
fav_movies=input('enter your fav movies seperated by comma :').split(',')
fav_songs=input('enter your fav songs seperated by , :').split(',')

user['name']=name
user['age']=age
user['fav_movies']=fav_movies
user['fav_songs']=fav_songs

for key,value in user.items():
    print(f'{key} : {value}')

#78. SETS…………………………………………………………………………………………………………………………

#unordered collection of unique items
#cant store list,tuple in sets
s={1,1.0,2,3,2}
print(s)
#no indexing in sets
l=[1,2,3,4,5,6,7,8,9,5,2,6,4,8]
#remove duplicate
s2=list(set(l))
print(s2)
#add method
s.add(4)
print(s)
s.add(5)
s.add(4)
print(s)
#remove method
s.remove(5)
print(s)
#discard method
s.discard(7)        #doesn't throw error if not present
#clear method
s.clear()
print(s)
#copy method
s1=s.copy()
print(s1)

#79. More on sets……………………………………………………………………………………………………………

s={'a','b','c','d'}
if 'a' in s:
    print('present')        #unordered 

for item in s:
    print(item)

#set maths
s1={1,2,3,4}
s2={3,4,5,6}
#union 
s3=s1 | s2
print(s3)

#intersection
s4=s1 & s2
print(s4)

#80. List comprehension………………………………………………………………………………


#list comprehension
squares=[]
for i in range(1,11):
    squares.append(i**2)

print(squares)

squares2=[i**2 for i in range(1,11)]        #can create list in one line
print(squares2)

negative=[-i for i in range(1,11)]
print(negative)

names=['vikas','mohit','rohit']
new=[name[0] for name in names]
print(new)

#81. Chapter 9 exercise 1………………………………………………………………………………………………

def reverse(l):
    return [name[::-1] for name in l]

print(reverse(['abc','def','ghi']))

#82. List comprehension with if …………………………………………………………………………

def reverse(l):
    return [name[::-1] for name in l]

print(reverse(['abc','def','ghi']))

#83. Chapter 9 exercise 2……………………………………………………………………………………

def num_to_string(l):
    return [str(i) for i in l if (type(i)==int or type(i)==float)]

print(num_to_string([True,False,[1,2,3],1,1.0,3]))

#84. List comprehension with if else…………………………………………………………………………

nums=[1,2,3,4,5,6,7,8,9,10]
new=[i*2 if i%2==0 else -i for i in nums]
print(new)

#85. Nested list comprehension………………………………………………………………………………………

l=[[1,2,3],[1,2,3],[1,2,3]]
nested=[[i for i in range(1,4)] for j in range(3) ]
print(l)
print(nested)

#86. Dictionary comprehension………………………………………………………………………

square={1:1,2:4,3:9}
square1={f"square of {num} is" :num**2 for num in range(1,11)}
for k,v in square.items():
    print(f'{k} : {v}')

string="vikas yadav"
word_count={char:string.count(char) for char in string}
print(word_count)

#87. Dictionary comprehension with if else…………………………………………………………………


d={1:'odd',2:'even',3:'odd'}
odd_even={i:('even' if i%2==0 else 'odd') for i in range(1,11)}
print(odd_even)

#88. Sets comprehension……………………………………………………………………………………

s={k**2 for k in range(1,11)}
print(s)

names=['vikas','mohit','rohit']
first={name[0] for name in names}
print(first)

#89. *args………………………………………………………………………………………………………………………………

#make flexible functions
#*operator
#*arg

def total(a,b):
    return a+b
print(total(3,4))

def all_total(*args):
    total=0
    for num in args:
        total+=num
    print(args)
    print(type(args))   #---> tuple

    return total
    

print(all_total(1,2,3,4,5,6,7,8,9))

#90. *args as argument……………………………………………………………………………………………


def multiply(*args):
    multiply=1
    print(args)
    for i in args:
        multiply *=i
    return multiply

nums=[2,3,4]
print(multiply(*nums))      #unpack

#91. *args with normal parameter………………………………………………………………………

def multiply(num,*args):
    multiply=1
    print(num)
    print(args)
    for i in args:
        multiply *=i
    return multiply

print(multiply(2,2,3,4))

#92. Chapter 11 exercise 1………………………………………………………………………..

def power(num,*args):
    if args:
        return [i**num for i in args]
    else:
        return "you didnt passed any args "
nums=[1,2,3,4,5]
print(power(3,*nums))

#93. **kwargs………………………………………………………………………………………………………………

#kwargs (keyword arguments)
#**kwargs
def func(**kwargs):
    print(kwargs)
    for k,v in kwargs.items():
        print(f'{k} : {v}')

d={'name':'vikas','age':24}
func(first_name='vikas',last_name='yadav')
func(**d)

#94. Function with all types of parameters…………………………………………………………

#parameter 
#*args
#default parameters
#**kwargs

def func(name,*args, last_name='unknown',**kwargs):
    print(name)
    print(args)
    print(last_name)
    print(kwargs)

func('vikas',1,2,3,  a=1,b=2)

#95. Chapter 11 exercise 2………………………………………………………………………………………………

def func(l,**kwargs):
    if kwargs.get('reverse_str')==True:
        return [name[::-1].title() for name in l]
    else:
        return [name.title() for name in l]
    
names=['vikas','mohit','rohit']
print(func(names,reverse_str = True))

#96. Lambda expressions………………………………………………………………………………………


#lambda expressions (anonymous function)

def add(a,b):
    return a+b

add1=lambda a,b : a+b
print(add(2,3))

multiply =lambda a,b : a*b
print(multiply(2,3))

#97. Lambda expressions…………………………………………………………………………………

def is_even(a):
    return a%2==0
print(is_even(4))

is_even2= lambda a : a%2==0
print(is_even2(6))

def last(s):
    return s[-1]

last_char =lambda s: s[-1]
print(last_char('vikas'))

def func(s):
    return len(s)>5

func1=lambda s: True if len(s)>5 else False
func2=lambda s: len(s)>5
print(func1('abcdef'))
print(func2('abcdef'))

#98. Enumerate fuction………………………………………………………………………………………………

#we use enumerate func with for loop to track pos of our item in iterable

names=['abc','abcde','vikas']
for pos,name in enumerate(names):
    print(f"{pos} ----> {name}")
def find_pos(l,target):
    for pos,name in enumerate(l):
        if name==target:
            return pos
    return -1

print(find_pos(names,'vikas'))

#99. Map function………………………………………………………………………………………………………

numbers=[1,2,3,4]

#map func
squares=list(map(lambda a: a**2 ,numbers))
print(squares)

squares1=[i**2 for i in numbers]
print(squares1)

names=['a','ab','abc']
length=list(map(len,names))
print(length)

#100. Filter function…………………………………………………………………………………………

#filter func
numbers=[3,2,4,5,7,9,8]

even=tuple(filter(lambda a:a%2==0,numbers))
print(even)

#101. Iterator vs iterables………………………………………………………………………………

numbers=[1,2,3,4]   #list, tuples, strings ---> iterables
squares=map(lambda s:s**2, numbers)    #iterator

num_iter=iter(numbers)      #calls iter func to convert numbers to iterator
print(next(num_iter))
print(next(num_iter))
print(next(num_iter))
print(next(num_iter))

print(next(squares))    #squares is already an iterator
print(next(squares))
print(next(squares))
print(next(squares))

#102. Zip function………………………………………………………………………………………

#zip function
user_id=['user1','user2','user3']
names=['vikas','mohit','rohit','sachin']
last_name=['yadav','sharma','sharma','kumar']

print(list(zip(user_id,names,last_name)))
print(dict(zip(user_id,names)))

#103. Zip …………………………………………………………………………………………………………………………

l1=[1,2,3,4]
l2=[2,4,6,8]
l=[(1,2),(3,4),(5,6)]
l3,l4=list(zip(*l))     #unziping
print(list(l3))
print(list(l4))

new_list=[]
for pair in zip(l1,l2):
    new_list.append(max(pair))

print(new_list)
#104. Chapter 13 exercise 1………………………………………………………………………………

def average_finder(*args):
    average=[]
    for pair in zip(*args):
        average.append(sum(pair)/len(pair))
    return average

average_finder_beta= lambda *args:[sum(pair)/len(pair) for pair in zip(*args)]
print(average_finder([1,2,3],[4,5,6],[7,8,9]))  
print(average_finder_beta([1,2,3],[4,5,6],[7,8,9]))

#105. Any() and all() functions………………………………………………………………………………

#any , all function 
numbers1=[2,4,6,8,10]
numbers2=[1,2,3,4,5,6]
print(any([num%2==0 for num in numbers1]))      #--->True
l=[num%2==0 for num in numbers1]
print(l)
print(all([True,False,True,True]))       #--->False
#all func checks for all True values in the list
# any func checks if even 1 True is present in the list

#106. More about any() an all()………………………………………………………………………………………………

def sum(*args):
    if all([(type(arg)== int or type(arg)== float ) for arg in args]):
        total=0
        for num in args:
            total+=num
        return total
    else:
        return 'wrong input'

print(sum(1,2,3,4,5,6,'vikas',['vikas']))
#107. Advance min() max() function……………………………………………………………………………

numbers=[1,2,3,4,5]
names=['vikas','ab','abc','']
print(max(names,key=lambda item: len(item)))

students=[
    {'name':'vikas','score':90, 'age':20},
    {'name':'mohit','score':85, 'age':21},
]
students1 ={
    'harshit' : {'score':75 , 'age':24},
    'vikas' : {'score':80 ,'age':20},
}
print(max(students, key = lambda item:item.get('score'))['name'])
print(max(students1, key = lambda item:students1[item]['score']))

#108. Sorted() function………………………………………………………………………………………………………………

fruits=['grapes','mango','apple']
fruits1=('grapes','apple','mango')
print(sorted(fruits1))
fruits2={'grapes','mango','apple'}
print(sorted(fruits2))

guitars=[
    {'model':'yamaha f310',"price":8400},
    {'model':'faith neptune',"price":50000},
    {'model':'faith apollo venus',"price":35000},
    {'model':'taylor 814ce',"price":450000}
]

sorted_guitars=sorted(guitars, key = lambda d:d['price'],reverse =True)
print(sorted_guitars)

#109. More about functions…………………………………………………………………………………………

def add(a,b):
    ''' this function takes 2 numbers and return their sum '''  #docstring
    return a+b

print(add.__doc__)
print(sum.__doc__)
print(len.__doc__)
print(help(sum))

#110. Object oriented programming…………………………………………………

#object oriented programming
#class , object(instance) , method
l=[1,2,3,4]
l.append(8)

#list class    <list>
#list object    l
#list method    append()

#111. Class demo……………………………………………………………………………………

class Person:
    def __init__(self, first_name, last_name, age):     #self-->Person instan
ce
        #instance variables
        print('init method // constructor get called')      
        self.first_name=first_name
        self.last_name=last_name
        self.age=age

p1= Person('vikas','yadav',20)      #object created
p2= Person('mohit','sharma',21)     #object created

print(p1.first_name)
print(p2.first_name)

#112. Chapter 16 exercise 1……………………………………………………………………

class Laptop:
    def __init__(self,brand,model_name,price):
        #instance variables
        self.brand=brand
        self.model_name=model_name
        self.price=price
        self.laptop_name = brand+' '+model_name

laptop1= Laptop('hp','au114tx',63000)
print(laptop1.laptop_name)

## built in errors………………………………………………………………………

1.SyntaxError
2.IndentationError
3.NameError --variable not defined
4.TypeError --wrong operation on wrong type
5.IndexError --index out of bounds
6.ValueError --string to int
7.AttributeError --no attribute found
8.KeyError --key not found

## raise errors………………………………………………………………………………………

def add(a,b):
    if (type(a) is int) and (type(b) is int):
        return a+b
    raise TypeError('oops wrong data entered')

print(add('1','2'))

## Custom exceptions……………………………………………………………………

class NmaeTooShortError(ValueError):
    pass

def validate(name):
    if len(name)<8:
        raise NmaeTooShortError('name is too short')

username=input('enter your name : ')
validate(username)
print(f"hello {username}")

## Debugging………………………………………………………………………………

#Debugging is a process of finding and resolving defeects and problems with
in
# a computer program that prevents correct operation of the software
import pdb      #python debugger module

name=input('please type your name : ')
age=input('please enter your age : ')
pdb.set_trace()
print(name)
age=age+5
print(age)

#l  --current contol flow pos line
#n  --run current line
#c  --continue
#q  --quit

## File Handling………………………………………………………………………………

#readfile
#open func
#read method
#seek method 
#tell method
#readline method 
#readlines method
#close method

f=open('file1.txt','r')
print(f'cursor position , {f.tell()}')
print(f.read())
print(f'cursor position , {f.tell()}')

print('before seek method')
f.seek(0)
print('after seek method')
print(f'cursor position , {f.tell()}')

print(f.readline() ,end='')
print(f.readline() ,end='')
f.seek(0)
print('after seek method')

lines = f.readlines()
print(lines)

for line in lines:
    print(line,end='')
#name , closed  -->data discriptors
print(f.name)       #--> gives name of file
print(f.closed)     #--> check if file closed or not

f.seek(0)
for line in f.readlines()[:2]:
    print(line,end='')
f.close()

## With Block……………………………………………………………………………………………………

#with block
#context manager

with open('file1.txt') as f:
    data = f.read()
    print(data)

print(f.closed)

## Write To File……………………………………………………………………………………………………

# 'a' , 'w' , 'r+'
with open('file2.txt','w')as f:         #-->creates new file if not found
    f.write('hello\n')

with open('file2.txt','a')as f:          #-->creates new file if not found
    f.write("content appended\n")

with open('file2.txt','r+')as f:        #-->starts from pos 0 and overwrites
    f.seek(len(f.read())+1)               #this to write at the end
    f.write("file updated by r+ mode")

## read and write ……………………………………………………………………………………………

with open('file1.txt','r')as rf:
    with open('file3.txt','w')as wf:
        wf.write(rf.read())

## exercise 1 file handling……………………………………………………………………………

with open('salary.txt','r')as rf:
    with open('output.txt','a')as wf:
        for line in rf.readlines():
            name,salary=line.split(',')
            wf.write(f"{name}\'s salary is {salary}")

#### Opening, Reading and Writing Binary Files

Binary files refer to any file that contains non-text, such as image or video
files. To work with binary files, we simply use the ‘rb’ or ‘wb’ mode. Copy
a jpeg file onto your desktop and rename it myimage.jpg. Now edit the
program above by changing the first two line lines

inputFile = open (‘myfile.txt’, 'r')


outputFile = open (‘myoutputfile.txt’, 'w')

to

inputFile = open (‘myimage.jpg’, 'rb')


outputFile = open (‘myoutputimage.jpg’, 'wb')

Make sure you also change the statement outputFile.write(msg +


'\n') back to outputFile.write(msg).

Run the new program. You should have an additional image file named
myoutputimage.jpg on your desktop. When you open the image file, it
should look exactly like myimage.jpg

#### Deleting and Renaming Files

Two other useful functions we need to learn when working with files are
the remove() and rename() functions. These functions are available in
the os module and have to be imported before we can use them.

The remove() function deletes a file. The syntax is


remove(filename). For instance, to delete myfile.txt, we write
remove(‘myfile.txt’).

The rename() function renames a file. The syntax is rename (old


name, new name). To rename oldfile.txt to newfile.txt, we
write rename(‘oldfile.txt’, ‘newfile.txt’).

You might also like