interpreted, object-oriented, high-level programming language with dynamic typed
Python
does not refer to the snake, but comes from the BBC comedy series Monty Python’s Flying Circus
.x = input("Enter something: ")
print("Hello, World!")
Important Note: Python is indentation-sensitive, meaning indentation is mandatory to define blocks of code.
#shell comment
"""This is a multi-line comment"""
or '''multi-line comment'''
Backslashes \ are used to insert special characters in a string.
35 keywords in python
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
name given to a memory location
a=7
print(a)
a=10
a=10.0
a=10+1j
d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
true/false
set1 = {'James', 2, 3,'Python'}
A sequence of characters, defined using single or double quotes.
a='rajesh'
lst = ["hi", "Python", 2]
tup = ("hi", "Python", 2)
len(tuple)
allows you to convert data from one type to another:
int('22')
float(2)
str(3.1)
Note: Use type(object) to find the type of an object. type(object)
Arithmetic Operators | Example |
---|---|
Exponent | 2 ** 3 = 8 |
Modulus/Remainder | 22 % 8 = 6 |
Integer division | 22 // 8 = 2 |
Division | 22 / 8 = 2.75 |
Multiplication | 3 * 3 = 9 |
Subtraction | 5 - 2 = 3 |
Addition | 2 fzaq``+ 2 = 4 |
Other Operators | Symbols |
---|---|
Arithmetic Operator | + - * / % ** // |
Relational Operator | <, <=, >, >=, ==, != |
Logical Operator | and, or, not |
Assignment Operator | a += 4 |
Inc and Dec Operator | Not supported |
Tenary Operator | ‘kid’ if age < 18 else ‘adult’ |
Identity Operator | is, is not |
Bitwise Operator | &, «, », »> |
Membership operators | in, not in |
Walrus Operator | print(my_var:=”Hello”) |
if 5 > 2:
print("True")
if 5 > 2:
print("True")
else:
print("False")
if 5 > 2:
print("True")
elif 5 < 2:
print("False")
match response_code:
case 200:
print("OK")
case 201:
print("Created")
case _:
print("invalid")
for n in lists:
print(n)
while counter < 10:
counter = counter + 3
for i in range(5):
print('printed {i}')
Functions in Python are defined using the def keyword:
def functionName(arg1,arg2=defaultVal):
#function body
return something
functionName('val1','val2')
functionName(arg2='val1',arg1='val2')
def add(*num) #can be called add(1),add(1,2), add(1,2,3)
func = lambda x: x + 1
global variableName=5
#to make changes in global variable inside functionclasses define the blueprint for creating objects.
class ClassName:
num = 4
def __init__(self):
print('this is constructor')
def add(self,x):
self.num = self.num + x
obj = ClassName() #creating object
obj.num #accessing variable
obj.add(3) #accessing function
acquires properties from parent to child class
Note: Python supports single and multiple inheritance.
class Parent():
class Child(Parent): #child inherited parent if overriding occurs, current class func overrides parent class function
class StepParent:
class Child(Parent,StepParent): #multiple inheritance, if overriding occurs, 1st arg override 2nd arg
allow you to organize code into separate files.
import my_module
my_module.function_name()
my_module.variable_name
from my_module import function_name
Types of import:
file = open('file.txt', 'rt')
content = file.read()
file.close()
file = open('file.txt', 'w')
file.write("New text")
file.close()
import os
os.remove('file.txt')
try:
number = int(input("What is your fav number?"))
print(18/number)
except ValueError:
print('Make sure you are entering a number')
except ZeroDivisionError:
print('Dont enter Zero')
except:
print('something error, but i dunno what')
finally:
print('it will print finnaly, whatever happended')
import threading
class MyThread(threading.Thread):
def run(self):
print(threading.currentThread().getName())
thread1 = MyThread(name="Thread 1")
thread2 = MyThread(name="Thread 2")
thread1.start()
thread2.start()
import multiprocessing
def my_function():
print("Hello from process")
process1 = multiprocessing.Process(target=my_function)
process1.start()
process1.join()
import logging
logging.debug('program starts')
logging.debug('program ends')
json_dumps(dictVariable)
json_loads(string)
itr = iter(obj) #we can call next value by using next(itr)
simple way to create an iterator
def gen():
yield "one"
yeild "two"
Now we can gen as iterator
parser = argparse.ArgumentParser()
parser.add_arguement("firstargName")
args =parser.parse_args()
print(arg.firstargName)
The enumerate()
function allows you to loop through a list while keeping track of the index position:
presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe", "Adams", "Jackson"]
for num, name in enumerate(presidents, start=1):
print(presidents[num])
colors = ["red", "green", "blue", "purple"]
ratios = [0.2, 0.3, 0.1, 0.4]
for color, ratio in zip(colors, ratios):
print("{}% {}".format(ratio * 100, color))