























































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!
























































print("hello")
"""multi line comment """ print("hello avi") print("hello avi2")
end="(character with which you want to end like comma,space,fullstop)" print("hello avi",end=", ") print("hello avi2") print("hello avi",end="*****") print("hello avi2") print("hello avi","hello avi2",) #it will automatically give space. #Escape Sequence - "\n,\t" to print escpae sequence write \ like "\n ,\t "
var1="hello world" var2 = 4 var3 =36. var4 = "Avi" print(type(var1)) print(type(var2)) print(type(var3)) #print(var1 + var2) error #print(var1 + var3) error print(var2+ var3) print(var1+var4) print(type(var2+ var3)) #Type casting int(variable_name) int(),float(),str() var5 = "4" var6 = "12" print(var5+var6) print(int(var5)+int(var6)) print(str(var2)+str(var3)) #utilities 10(any_string) print it 10 times, n(any string) print it n times
#how to take input in python input is taken by default as string print("Enter no.") a = input() print("You entered ",a) #alternate method a = input("enter again") print("You entered ",a)
Strings in Python are immutable meaning you cannot replace parts of them. string fun – findall, search, split, sub, finditer mystr ="Avi is good boy" print(mystr) #print complete string print(mystr[ 2 ]) #print of that index. print(len(mystr)) #print the length print(mystr[ 0 : 10 ]) #print from including starting index and upto last index(ex cluding) print(mystr[ 0 : 10 : 2 ]) #print with escaping one characters if instead of 2 we wr ite n it will skip n- 1 character print(mystr[::- 1 ]) #first reverse the string then print from starting to last print(mystr[::- 2 ]) #first reverse the string then print from starting to last skiping 1 chara cter print(mystr[ 0 :]) #print from starting index to last print(mystr[::]) #print from starting to last print(mystr.isalnum()); #check whether it is alpha numeric or not print(mystr.isalpha()); #check whether it is alpha or not here false b/c conta ins space print(mystr.endswith("boy")) #check whether it ends with given word/letter or not print(mystr.count("o")) #counts no of repetition print(mystr.capitalize()) #capitalise first letter print(mystr.find("is")) #gives the starting index print(mystr.lower()) #convert in lowercase print(mystr.upper()) #convert in uppercase print(mystr.replace("good","very good")) # replace
grocery =["harpic","vim bar","dio","bhindi","lollly pop", 45 ] print(grocery) #print complete list print(grocery[ 3 ]) #print at that index assume as array numbers =[ 5 , 5 , 5 , 8 , 3 , 7 , 4 ]
#Dictionary is key value pair it is written in {} d1 ={"Avi":"Avishek","Abh":"Abhay","Rau":"Raushan"} print(type(d1)) print(d1["Avi"]) #it will print the value of corresponding to that key
d2 ={"Avi":{"Name":"Avishek","MOB": 7479734685 },"Abh":"Abhay","Rau":"Raushan"} print(d2["Avi"]["Name"]) d2["Ankit"] = "Junk Food" # add items in dict print([d2["Ankit"]]) d2["Ankit"] = "New Junk Food" print([d2["Ankit"]]) del d2["Ankit"] # it will delete this key and its pair d3 = d2 # it means now d3 will point d2 , on changing in d3 it will change on d d3 = d2.copy() #it will return copy of d2, now d2 and d3 will be independent print(d2.keys()) #print keys print(d2.items()) #print items
s = set() print(type(s)) s_fron_list = set([ 1 , 2 , 3 , 4 ]) # same set can be created using list instead of passing list you can also pass the name of list declared before print((s_fron_list)) s.add( 1 ) # it will add it in set but set contains unique values only s.add( 1 ) # adding it again will not change any thing in set but in list you c an add repeatitively print(s) s1 = s.union({ 4 , 2 , 3 }) #return union of s and given set print( s,s1) s1 = s.intersection(( 1 , 3 )) # return union of s and given set print( s,s1) print(s.isdisjoint(s1)) #it will tell whether s ar s1 is disjoint or not s_fron_list.remove( 4 ) # removes the passed element #similarly len(s),max(s),min(s) will gives length and maximum, minimum value
a = 6 b= 56 c = int(input("Enter no\n")) if c>b:
print("Greater") elif c==b: print("Equal") else: print("Lesser") list1 = [ 5 , 7 , 3 ] if 5 in list1: print("Yes") if 15 not in list1: # here "in" and "not in" is keyword print("NO") #short hand for if else c = int(input("Enter no\n")) if c>b : print("Greater") c = int(input("Enter no again\n")) print("Greater") if c>b else print("Smaller")
list1 = ["avi","kvi","ashi","aksd","klajdkf","sdfkld"] list2 = [["akldj", 1 ],["klaj", 2 ],["klaj", 3 ]] dict1 = dict(list2) for item in list1: print(item) for item,numb in list2: print(item,"has scored rank",numb,"\n",end="*") print("printing dictionary ",dict1) #to iterate in dictionary for item,numb in dict1.items(): print(item,"has scored rank",numb) #practise prac = ["avi", 4 , 12 ,"akd",6.5] for item in prac: if(str(item).isnumeric() and item> 6 ): print(item) else: print("It is not allowed") """range function it will take three argument max, first is starting, second is terminating and third is increment value if you pass one value then by default starting value =0, increment value = 1,t erminating value = passed value if you pass 2 value (a,b) a= starting value ,b= terminating value,increment va lue=1(bydefault) """
"and" and "or" or #Identity operator "is" (a is b) check whether a is b "is not" (a is not b) check whether a is not b #Membership Operator list = [3,3,2,45,24,8,6,7,15,76] "in" print(45 in list) it will print whether 45 is in list or not "not in" #Bitwise Operator & binary and | binary or """
#first line inside a function as a multi line comment is called docstring whic h should contain some details related to that function #to check the docstring of function f1() write "print(f1.doc)" def function(a, b): """this is a function to add two number""" print("Hello inside function", a + b) def function2(a,b): """this to find average""" average = (a+b)/ 2 print(average) return average print(function( 7 , 10 )) print(function2( 4 , 8 )) # first execute the function then print the return value print(function2.doc) #print the docstring print(function2.code) print(function.doc)
a = input("enter a\n") b = input("enter b\n") try: print("sum",int(a)+int(b)) except Exception as e:
print("something is wrong",e) #Exception is the error msg
"r" - open file for reading "w" - open file for writing , erase the previous content and write ,create new file if not exist "x" - creates file if not exist (exclusive creation) "b" - open for binary mode "t" - text mode (it is default mode) "a" - add more content (append) write in last of file "+" - both read and write """ #f = open("avi.txt") #syntax of file opening f = open("avi.txt","r") #second argument is file opening mode by default it "r" mode
e read() it will read whole file
#content = f.read(3) #here it will read first 3 character and then cal ling it again it will read after that character
ot that much character then it will read upto last only #print(content) #content = f.read(3) #here it will read 3 character after that which was already read #print(content) """ to read file line by line or letter by letter we have to iterate the file" ""
ave to use content
b/c if we use it will read file upto end and nothing will left to read
print(f.readlines()) #it will store the line in list
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file f writing. 6 wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates new file for writing. 7 w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exis creates a new file for reading and writing. 8 wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file doe not exist, creates a new file for reading and writing. 9 a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the appen mode. If the file does not exist, it creates a new file for writing. 10 ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the fi is in the append mode. If the file does not exist, it creates a new file for writing. 11 a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file open in the append mode. If the file does not exist, it creates a new file for reading and writing. 12 ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exist The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
f = open("avi.txt") f.seek( 11 ) print(f.tell())
print(f.readline())
print(f.readline())
f.close()
with open("avi.txt") as f: #inside open you can also pass opening mode a = f.readlines() print(a)
#first part l = 10 #Globlal def function1(n): #l = 5 #it is local scope
"""here it will first search for local variable and if it will not in loca l scope it will search in global we can not change global variable directly it will give error""" global l # need to write this statement to change the the value of global variable l = l + 10 print(n,l,"I have printed") function1("This is me") print(l) #second part x= 89 def avi(): x = 20 def avi2(): global x # on writing this it will go directly to global scope to find
import random import datetime import playsound import platform import math import builtins import calendar print(datetime.datetime.now()) print("Here is the calendar",calendar.month( 2020 , 2 )) print(platform.system()) print(math.sqrt( 25 )) print(builtins.bin( 8 )) playsound.playsound('Tera zikr.mp3') random_num = random.randint( 0 , 5 ) print(random_num) print(random.random()) # 0 to 1 lst = ["channel1","channel2","channel3","channel4","channel5","channel6","chan nel7"] print(random.choice(lst))
F string is similar to template literal of ES6 of javascript me = "Avi" a1 = 3
a = f"this is {me} {a1} {math.cos(65)}" # this is f string
print(a) a = input("Enter you name\n") b = "18" str = "Hello {0} you have to wait {1} minutes to meet with Mr. Abhishek Pratap Singh" print("Hello %s you have to wait %s minutes to meet with Mr. Abhishek Pratap S ingh"%(a,b)) print(str.format(a,b)) print(f"Hello {a} you have to wait {b} minutes to meet with Mr. Abhishek Prata p Singh")
args means arguments kwargs means keyworded (named or like key, pair) arguments keyworded arguments doesn’t matter order in which they passed in function, in python it knows the name of variable name defined( search keyworded arguments in python on google for more info) The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list. The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is because the double star allows us to pass through keyword arguments (and any number of them).
def funargs(normal, *argsrohan, **kwargsbala): print(normal) for item in argsrohan: print(item) print("\nNow I would Like to introduce some of our heroes") for key, value in kwargsbala.items(): print(f"{key} is a {value}")
har = ["Harry", "Rohan", "Skillf", "Hammad", "Shivam", "The programmer"] normal = "I am a normal Argument and the students are:" kw = {"Rohan":"Monitor", "Harry":"Fitness Instructor", "The Programmer": "Coordinator", "Shivam":"Cook"} funargs(normal, *har, **kw) #in function *args and ** kwargs are optional even
situations virtual environment can be really useful to maintain dependencies of both the projects.
Enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method. l1 =[ "item1" , "item2" , "item3" , "item4" , "item5" , "item6" , "item7" , "item8" ] for index,item in enumerate(l1): print( f"{ item } is on index number { index+ 1 }" )
When we write import means we are putting the codes of that file in our file we can also import our own file. name is a built-in variable which evaluates to the name of the current module. Thus it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement. If the script is executed in its file then name is main but when imported in some file and executed then its name is its file name. Sometimes we define some very useful function and do some work in a file and if we import that file then it is again executed there, which is not required we need only those defined function for some other operations. In such case we use if name ==’main’ because when it is imported in some other file then it’s name will be different and the condition becomes false and if it is executed in same file then only condition will be true and it’s code will be executed File import file2 # we can also import files written by us import file
Map – it applies a function over all the elements of a list. To apply same function over all elements of list we can use for loop or map function Syntax- map(function_name, list_name) First argument is function name without braces and other is list name. Or instead of that we can also pass lambda function. It returns a object then we have to type cast in list. def square(x): return xx def cube(x): return xxx numbers = ["3", "34", "64", "420"] numbers = list(map(int, numbers)) numbers[ 2 ] = numbers[ 2 ] + 1 print(numbers[ 2 ]) num = [ 2 , 3 , 5 , 6 , 76 , 3 ] sq = list(map(lambda x: xx, num)) # here map will give each element of num list to fn which will return its square print(sq) func = [square, cube] # list of function for i in range( 6 ): val = list(map(lambda x: x(i), func)) # here map will give each function from func list to lambda function and here lambda fn is also recieving a fn and returning f(i) print(val) Filter – It filters a list means it return a object of sublist with elements such that for which that function returns true def is_greater_5(num): return num> 5 lst = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] print(list(filter(is_greater_5, lst))) Reduce - The reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along.This function is defined in “functools” module. Working :
print("The sum of the list elements is : ", end="") print(reduce(lambda a,b : a+b,lis))
print("The maximum element of the list is : ", end="") print(reduce(lambda a, b : a if a > b else b, lis))
The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity. Unzipping means converting the zipped values back to the individual self as they were. This is done with the help of “ ***** ” operator.
name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ] roll_no = [ 4 , 1 , 3 , 2 ] marks = [ 40 , 50 , 60 , 70 ]
mapped = zip(name, roll_no, marks) print (mapped) for item in mapped: print(item[ 1 ])
mapped = set(mapped)
print ("The zipped result is : ",end="") print (mapped) name = ["Manjeet", "Nikhil", "Shambhavi", "Astha"] roll_no = [ 4 , 1 , 3 , 2 ] marks = [ 40 , 50 , 60 , 70 ]
mapped = zip(name, roll_no, marks)
mapped = list(mapped)