You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
print(a+b) # arithmetic operationprint(a-b) # subtraction operationprint(a*b) # multiplication operationprint(a/b) # division operation - gives the quotient(float)print(a//b) # floor division - gives the quotient(whole)printa(a%b) # Modulas division - gives the remainderprint(a**b) # exponential - power of a^bprint(-a) # negative value of the stored integerprint(abs(-a)) # like modulo |a| - always positive valueprint(int(2.5)) # prints only the decimal value not the float valueprint(float(a)) # prints the decimal value of the int
Boolean Operations
and# performs and operationor# performs or opertaionnot# performs not operation
String Operations
a=' This is a string 'print(a.strip()) # removes whitespaces before and after the string Thisisastring# output of strip()print("Cyberwr3nch".lower()) # prints everything in the lowercasecyberwr3nch# ouput of lower()print("cyberwr3nch".upper()) # prints everything in the uppercaseCYBERWR3NCH# output of upper()print("i am a geek".title()) # prints everything in title formatImAGeek# output of title()iam="cyberwr3nch"# variable with the name "iam" and value 'cyberwr3nch'print(f" I am {iam}") # subsituting the value with f"" formatprint("I am {}".format(iam)) # subsituting the values with format()Iamcyberwr3nch# output of formating, string operations such as title()/upper()/lower() can be performed print("github".startswith("git")) # print boolean if the mentioned string starts with gitprint("github".endswith("hub")) # print boolean if the mentioned string ends with gitprint("github".find('it')) # finds the specifed string and provides its index numberprint("github was awesome".replace('was', 'is') # changes was with isprint('-'.join(['F', 'B', 'I']) # joins the items in the list with the seperator '-'# >>> lis = ["F", "B", "I"]# >>> print('-'.join(lis))# >>> F-B-Iprint(len('github')) # prints the length of the stringprint("git"in"github") # returns boolean if the string is founda="This is a line"print(a.split()) # splits the words on space; ['This', 'is', 'a', 'line']
List Operations
a= [] # empty lista= [1,2,3,4] # list declarationprint(a[2]) # prints the elemet 3, index of lists starts with 0a.append(5) # adds 5 at the ends of the list a; a = [1,2,3,4,5]a= [1,2,4,5]
a.insert(2, 3) # adds 3 in the index 2; a = [1,2,3,4,5]print([1,2,3,4] + [5]) # concats two listsa= [7,2,8,4,5]
a.remove(8) # removes 8 from the list; a = [7,2,4,5]a= [7,4,8,1]
sorted(a) |a.sort() # sorts in ascencding ordersorted(a, reverse=True) |a.sort(reverse=True) # sorts in descending ordersorted(a, key=<value>) |a.sort(key=<value>) # performs sorting based on the specified key value; works for nested listsforiina: # iterate throught the list and print the lists contentsprint(i)
a= [1,2,3,4,5]
print(a[0:2]) # print items with index range 0-2 from the list; index 2 is discarded in the output; Output: 1,2print(a[:3]) # print items from 0 - 2; Output: 1,2,3print(a[2:4]) # print items from index range 2 - 4; Output: 3,4print(a[3:]) # print items from index 3 to end of the list; Output: 4,5a= [1,2,3,4]
b=a[:] # copies the contents of the list a to list b
Range ()
print(list(range(1,6))) # sudden list of numbers from 1 - 6print(list(range(1,10,2))) # print from numbers 1 - 10 with a hop of 2, = 1, 3, 5, 7, 9
if (condition): # IF Loop declaration#code-suitepassif (condition): # IF-Else Loop declaration#code-suitepasselse:
#code-suitepassif (condition): # IF-Elif-Else Loop declaration; Nested IF ELSE CONDITION#code-suitepasselif (condition):
#code-suitepasselse:
#code-suitepass
Python Operators
=# equal to<# less than># greater than!=# not equal to<=# less than or equal to>=# greater than or equal to<and>=# multiple condition checks with the booelan operators
Dictionary Operations
a= {} # empty dictioniarydic= {'language': 'python', 'difficulty': 'easy'}# dictionary declaration; syntax: dict_name = {"key1": "value1", "key2": "value2"}print(dic['language']) # accessing dictionary with keydic['author'] ="Guido van Rossum"# adding new key and value to the dictonary dictdic['difficulty'] ='Medium'# Key's value can be changed with the assignement operator(=)deldic['difficulty'] # removes the key vale pair 'difficulty' from the dictionaryforkey, valueindic.items(): # the dictonary values can be iterated with items()print(f"Key: {key}\n")
print(f"Values: {value}")
forkeyNameindic.keys(): # prints just the key name print(keyName)
forkeyNameinsorted(dic.keys()): # prints key names in sorted orderprint(keyName)
forvalue_itemsindic.value(): # prints the values of the keyprint(value_items)
nl= [] # initializing an empty listnew_dict= {'key': 'val1', 'key2': 'val2'} # assigning the dictionary with the valuesnl.append(new_dict) # appending the dictionary to the listnew_dict= {'name': 'cyberwr3nch', 'prog-lang': ['c', 'python']} # adding lists in the dictionaryprint(new_dict['name']) # accessing value with keyforproginnew_dict['prog-lang']: # iterating through tht list and accessing the valuesprint(f"{prog}\n")
students= { # nested dictionary"dhanesh": { # dic = {"key":"Value", "key", "value"}"f_name": "dhanesh", # nested_Dic = {"key":{"akey1":"avalue1", "akey2":"avalue2"}, "key2": {"bkey1": "bvalue1" }}"l_name": "sivasamy",
"role": "average student"
},
"cyberwr3nch": {
"f_name": "cyberwr3nch",
"l_name": "cyber",
"role": "moderate student"
},
"damnedsec": {
"f_name": "dsec",
"l_name": "security",
"role": "average student"
}
}
forstud_name, stud_detailsinstudents.items():
print(f"{stud_name}\n")
print(f"{stud_details['role']}") # accessing the value's, Value
User Input and While loop
variable=input("Provide input: ") # string input method with the message "Provide input: "variable=int(inpur("Enter num: ")) # integer input method with the messageg "Enter num: "while (condition): # while loop declaration#code-suitepasswhileTrue: # infinite loop#code-suitepasswhileTrue: # stop an infinite loop based on the conditionsif (condition):
#code-suitebreakelse:
pass
Functions
deffunc_name(): # function declaration#code-suitepassfunc_name() # calling a function, which triggers the code suite inside the functiondeffunc_name(arg1): # function declaration with an input to the function#code-suiteprint("Hello {arg1}")
func_name("cyberwr3nch") # passing argument to the function with the function calldeffunc_name(*args): # accepts any numbers of arguments being passed to the function#code-suitepassdeffunc_name(first, last, **user_info): # **user_info, accepts the key valued pair as an input#code-suitepassuser_profile=func_name("Dhanesh","Sivasamy", location="cbe", role="student") # Dhanesh being firstname, Sivasamy being second name, the keyed values locationa and role are accepted by the **user_info argument
Classes
classclass_name: # class initialization#code-suiteclassclass_name:
def__init__(self): # constructor declaration, the __init__() always takes "self" as its first arguemnt# we can assign variables for the inistantiated classes#code-suitepassclassclass_name:
def__init__(self): # we can initialize values for the object with self.<varname>=valueself.name="cyberwrn3ch"self.role="student"defout(self):
print(f"Hi {self.name}, I recon you are a {self.role}")
eggs=class_name() # when calling the function without providing an argumet it automaticalls assigns the variables from the __init__()eggs.out() # calling the function to output the result; class_obj.method(): OUTPUT: Hi cyberwrn3ch, I recon you are a student# when a variable/ value is mentioned in the __init__(self, value1), an variable is required when initializing an instance of the class# when another method in the class inherits the created object with "self" keyword, [HERE: The created object is passed to the out() inside the class], It passes the total no. of created / assigned values to the method, which makes us able to mention the values of self.name and self.roleeggs.role="master"# The values assigned by the __init__() can be modified by addressing themeggs.out()
classcls_child(class_name): # implementing inheritance, the cls_child becomes the child class of the class class_name. Meaning cls_child have all the methods in the class_namedef__init__(self): # super() calls the method specified in the parent classsuper().__init__(name, role)
File And Exceptions
withopen('filename') asfile_object: # open a file and read its contentsfile_object.read()
withopen('filename') asfile_object:
file_object.readlines() # reads the file line by linewithopen('filename', 'w') asfile_object: # opening a file in write modefile_object.write('cyberwr3nch') # writing the desired stuff to the filefile_object.close() # closing the file
# EXCEPTIONSprint(2/0) # ZeroDivisionError: division by zero, program stops# handling the exceptions with try/excepttry:
print(2/0)
exceptZeroDivisionError:
print("You cannot divide by 0")
withopen("iammaster.txt") #FileNotFoundError: [Errno 2] No such file or directory: 'iammaster.txt' try:
withopen(filename, encoding='utf-8') asf:
contents=f.read()
exceptFileNotFoundError:
print(f"Sorry, the file {filename} does not exist.")