WWW Codewithharry Com
WWW Codewithharry Com
Python CheatSheet
Haris Ali Khan · August 21, 2023 · 10 min read
Basics
Basic syntax from the python programming language
print(
print ("Content that you wanna print on screen")
screen")
we can display the content present in object using prit function as follows:-
var1 = "Shruti"
print(
print ("Hi my name is: ",
",var1
var1)
)
input(
var1 = input ("Enter your name: ")
")
print(
print ("My name is: ",
", var1
var1))
var1=
var1=int
int(
(input
input(
("enter the integer value")
value"))
print(
print (var1
var1))
var1=
var1=float
float(
(input
input(
("enter the float value")
value"))
print(
print (var1
var1)
)
range Function
range function returns a sequence of numbers, eg, numbers starting from 0 to n-1 for range(0, n)
range(
range (int_start_value
int_start_value,,int_stop_value
int_stop_value,
,int_step_value
int_step_value)
)
Here the start value and step value are by default 1 if not mentioned by the programmer. but int_stop_value is the
compulsory parameter in range function
example-
Display all even numbers between 1 to 100
for i in range
range((0,101
101,,2):
print(
print (i)
Comments
Comments are used to make the code more understandable for programmers, and they are not executed by
compiler or interpreter.
Multi-line comment
'''This is a
multi-line
comment'''
Escape Sequence
An escape sequence is a sequence of characters; it doesn't represent itself (but is translated into another
character) when used inside string literal or character. Some of the escape sequence characters are as follows:
Newline
Newline Character
print(
print ("\n"
"\n")
)
Backslash
It adds a backslash
print(
print ("\\"
"\\")
)
Single Quote
It adds a single quotation mark
print(
print ("\'"
"\'")
)
Tab
It gives a tab space
print(
print ("\t"
"\t")
)
Backspace
It adds a backspace
print(
print ("\b"
"\b")
)
Octal value
It represents the value of an octal number
print(
print ("\ooo"
"\ooo"))
Hex value
It represents the value of a hex number
print(
print ("\xhh"
"\xhh"))
Carriage Return
Carriage return or \r will just work as you have shifted your cursor to the beginning of the string or line.
pint(
pint("\r"
"\r")
)
Strings
Python string is a sequence of characters, and each character can be individually accessed using its index.
String
You can create Strings by enclosing text in both forms of quotes - single quotes or double quotes.
example
str=
str ="Shruti"
print(
print ("string is ",
",str
str)
)
Indexing
The position of every character placed in the string starts from 0th position ans step by step it ends at length-1
position
Slicing
Slicing refers to obtaining a sub-string from the given string. The following code will include index 1, 2, 3, and 4 for the
variable named var_name
Slicing of the string can be obtained by the following syntax-
string_var[
string_var[int_start_value:
int_start_value:int_stop_value:
int_stop_value:int_step_value]
int_step_value]
var_name[
var_name[1 : 5]
here start and step value are considered 0 and 1 respectively if not mentioned by the programmmer
isalnum() method
Returns True if all the characters in the string are alphanumeric, else False
string_variable.
string_variable .isalnum
isalnum(()
isalpha() method
Returns True if all the characters in the string are alphabets
string_variable.
string_variable .isalpha
isalpha(()
isdecimal() method
Returns True if all the characters in the string are decimals
string_variable.
string_variable .isdecimal
isdecimal(()
isdigit() method
Returns True if all the characters in the string are digits
string_variable.
string_variable .isdigit
isdigit(()
islower() method
Returns True if all characters in the string are lower case
string_variable.
string_variable .islower
islower(()
isspace() method
Returns True if all characters in the string are whitespaces
string_variable.
string_variable .isspace
isspace(()
isupper() method
Returns True if all characters in the string are upper case
string_variable.
string_variable .isupper
isupper(()
lower() method
Converts a string into lower case equivalent
string_variable.
string_variable.lower(
lower()
upper() method
Converts a string into upper case equivalent
string_variable.
string_variable .upper
upper(()
strip() method
It removes leading and trailing spaces in the string
string_variable.
string_variable .strip
strip(()
List
A List in Python represents a list of comma-separated values of any data type between square brackets.
element1,
var_name = [element1, element2
element2,, ...]
Indexing
The position of every elements placed in the string starts from 0th position ans step by step it ends at length-1
position
List is ordered,indexed,mutable and most flexible and dynamic collection of elements in python.
Empty List
This method allows you to create an empty list
my_list = []
index method
Returns the index of the first element with the specified value
list.
list.index
index(
(element
element)
)
append method
Adds an element at the end of the list
list.
list.append
append(
(element
element)
)
extend method
Add the elements of a given list (or any iterable) to the end of the current list
list.
list.extend
extend(
(iterable
iterable)
)
insert method
Adds an element at the specified position
list.
list.insert
insert(
(position
position,
, element
element)
)
pop method
Removes the element at the specified position and returns it
list.
list.pop
pop(
(position
position)
)
remove method
The remove() method removes the first occurrence of a given item from the list
list.
list.remove
remove(
(element
element)
)
clear method
Removes all the elements from the list
list.
list.clear
clear(
()
count method
Returns the number of elements with the specified value
list.
list.count
count(
(value
value)
)
reverse method
Reverses the order of the list
list.
list.reverse
reverse(
()
sort method
Sorts the list
list.
list.sort(
sort(reverse=
reverse=True|
True|False)
False)
Tuples
Tuples are represented as comma-separated values of any data type within parentheses.
Tuple Creation
variable_name = (element1,
element1, element2,
element2, ...)
Indexing
The position of every elements placed in the string starts from 0th position ans step by step it ends at length-1
position
Tuples are ordered,indexing,immutable and most secured collection of elements
Lets talk about some of the tuple methods:
count method
It returns the number of times a specified value occurs in a tuple
tuple.
tuple.count(
count(value)
value)
index method
It searches the tuple for a specified value and returns the position.
tuple.
tuple .index
index((value
value))
Sets
A set is a collection of multiple values which is both unordered and unindexed. It is written in curly brackets.
element1,
var_name = {element1, element2
element2,, ...}
var_name = set(
set([element1,
element1, element2,
element2, ...])
Set Methods
Lets talk about some of the methods of sets:
add() method
Adds an element to a set
set.
set .add
add((element
element))
clear() method
Remove all elements from a set
set.
set .clear
clear(()
discard() method
Removes the specified item from the set
set.
set .discard
discard((value
value))
intersection() method
Returns intersection of two or more sets
set.
set .intersection
intersection(
(set1
set1,
, set2 ... etc
etc)
)
issubset() method
Checks if a set is a subset of another set
set.
set .issubset
issubset(
(set
set)
)
pop() method
Removes an element from the set
set.
set .pop
pop(()
remove() method
Removes the specified element from the set
set.
set .remove
remove(
(item
item)
)
union() method
Returns the union of two or more sets
set.
set .union
union((set1
set1,
, set2
set2....)
Dictionaries
The dictionary is an unordered set of comma-separated key:value pairs, within {}, with the requirement that within a
dictionary, no two keys can be the same.
Dictionary
dictionary-
<dictionary-name
name>
> = {<key
key>>: value
value,
, <key
key>>: value ...}
Dictionary is ordered and mutable collection of elements.Dictionary allows duplicate values but not duplicate keys.
Empty Dictionary
By putting two curly braces, you can create a blank dictionary
mydict=
mydict ={}
dictionary>
<dictionary>[<key
key>>] = <value
value>>
dictionary>
del <dictionary >[<key
key>>]
len() method
It returns the length of the dictionary, i.e., the count of elements (key: value pairs) in the dictionary
len(
len (dictionary
dictionary)
)
clear() method
Removes all the elements from the dictionary
dictionary.
dictionary .clear
clear(()
get() method
Returns the value of the specified key
dictionary.
dictionary .get
get((keyname
keyname))
items() method
Returns a list containing a tuple for each key-value pair
dictionary.
dictionary .items
items(()
keys() method
Returns a list containing the dictionary's keys
dictionary.
dictionary .keys
keys(
()
values() method
Returns a list of all the values in the dictionary
dictionary.
dictionary .values
values(()
update() method
Updates the dictionary with the specified key-value pairs
dictionary.
dictionary .update
update((iterable
iterable)
)
Indentation
In Python, indentation means the code is written with some spaces or tabs into many different blocks of code to
indent it so that the interpreter can easily execute the Python code.
Indentation is applied on conditional statements and loop control statements. Indent specifies the block of code
that is to be executed depending on the conditions.
Conditional Statements
The if, elif and else statements are the conditional statements in Python, and these implement selection constructs
(decision constructs).
if Statement
if(
if(conditional expression)
expression):
statements
if-else Statement
if(
if (conditional expression)
expression):
statements
else:
else :
statements
if-elif Statement
if (conditional expression)
expression):
statements
elif (conditional expression)
expression):
statements
else:
else:
statements
if (conditional expression)
expression):
if (conditional expression)
expression):
statements
else:
else:
statements
else:
else:
statements
example-
a=15
b=20
c=12
if(
if (a>b and aa>
>c):
print(
print (a,"is greatest")
greatest")
elif(
elif (b>c and b b>
>a):
print(
print (b," is greatest")
greatest")
else:
else:
print(
print (c,"is greatest")
greatest")
Loops in Python
A loop or iteration statement repeatedly executes a statement, known as the loop body, until the controlling
expression is false (0).
For Loop
The for loop of Python is designed to process the items of any sequence, such as a list or a string, one by one.
for <variable
variable>
> in <sequence
sequence>
>:
statements_to_repeat
example-
for i in range(
range(1,101
101,
,1):
print(
print (i)
While Loop
A while loop is a conditional loop that will repeat the instructions within itself as long as a conditional remains true.
logical-
while <logical -expression
expression>>:
loop-
loop-body
example-
i=1
while(
while (i<=
<=100
100)
):
print(
print (i)
i=
i =i+1
Break Statement
The break statement enables a program to skip over a part of the code. A break statement terminates the very loop
it lies within.
for <var
var>> in <sequence
sequence>
>:
statement1
condition>
if <condition >:
break
statement2
statement_after_loop
example-
for i in range
range((1,101
101,
,1):
print(
print (i ,end
end=
=" ")
")
if(
if (i==
==50
50)
):
break
else:
else :
print(
print ("Mississippi"
"Mississippi")
)
print(
print ("Thank you"
you"))
Continue Statement
The continue statement skips the rest of the loop statements and causes the next iteration to occur.
for <var
var>> in <sequence
sequence>
>:
statement1
if <condition>
condition > :
continue
statement2
statement3
statement4
example-
for i in [2,3,4,6,8,0]:
!=0
if (i%2!= 0):
continue
print(
print (i)
Functions
A function is a block of code that performs a specific task. You can pass parameters into a function. It helps us to
make our code more organized and manageable.
Function Definition
def my_function(
my_function():
#statements
Function Call
my_function(
my_function ()
Whenever we need that block of code in our program simply call that function name whenever neeeded. If
parameters are passed during defing the function we have to pass the parameters while calling that function
example-
add(
def add (): #function defination
a=
a =10
b=
b =20
print(
print (a+b)
add(
add () #function call
value/
return [value /expression
expression]
]
def my_function(
my_function(arg1
arg1,
,arg2
arg2,
,arg3
arg3.
....argn
argn)
):
#statements
my_function(
my_function (arg1
arg1,
,arg2
arg2,
,arg3
arg3.
....argn
argn)
)
example-
def add(
add(a,b):
a+
return a +b
add(
x=add (7,8)
print(
print (x)
File Handling
File handling refers to reading or writing data from files. Python provides some functions that allow us to manipulate
data in the files.
open() function
open(
var_name = open("file name",
name", " mode")
mode")
modes-
1. r - to read the content from file
2. w - to write the content into file
3. a - to append the existing content into file
4. r+: To read and write data into the file. The previous data in the file will be overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.
close() function
var_name.
var_name.close
close(
()
read () function
The read functions contains different methods, read(),readline() and readlines()
read(
read() #return one big string
readlines(
readlines () #returns a list
write function
This function writes a sequence of strings to the file.
write(
write () #Used to write a fixed sequence of characters to a file
writelines(
writelines ()
Exception Handling
An exception is an unusual condition that results in an interruption in the flow of a program.
try:
try :
[Statement body block]
block]
Exception(
raise Exception()
Exceptionname:
except Exceptionname :
[Error processing block]
block]
else
The else block is executed if the try block have not raise any exception and code had been running successfully
try:
try :
#statements
except:
except :
#statements
else:
else:
#statements
finally
Finally block will be executed even if try block of code has been running successsfully or except block of code is
been executed. finally block of code will be executed compulsory
class
The syntax for writing a class in python
class_name:
class class_name :
pass #statements
Creating an object
Instantiating an object can be done as follows:
object-
<object-name
name>
> = <class
class--name
name>
>(<arguments
arguments>>)
self parameter
The self parameter is the first parameter of any function present in the class. It can be of different name but this
parameter is must while defining any function into class as it is used to access other data members of the class
CodeWithHarry:
class CodeWithHarry :
# Default constructor
__init__(
def __init__(self
self)
):
self.
self.name = "CodeWithHarry"
Inheritance in python
By using inheritance, we can create a class which uses all the properties and behavior of another class. The new
class is known as a derived class or child class, and the one whose properties are acquired is known as a base class
or parent class.
It provides the re-usability of the code.
class Base_class:
Base_class:
pass
derived_class(
class derived_class (Base_class
Base_class)):
pass
Types of inheritance-
Single inheritance
Multiple inheritance
Multilevel inheritance
Hierarchical inheritance
filter function
The filter function allows you to process an iterable and extract those items that satisfy a given condition
filter(
filter (function
function,
, iterable
iterable))
issubclass function
Used to find whether a class is a subclass of a given class or not as follows
issubclass(
issubclass (obj
obj,, classinfo
classinfo)
) # returns true if obj is a subclass of classinfo
Iterator
Used to create an iterator over an iterable
iter(
iter_list = iter (['Harry'
'Harry',, 'Aakash'
'Aakash',
, 'Rohan'
'Rohan']])
print(
print (next
next(
(iter_list
iter_list)
))
print(
print (next
next(
(iter_list
iter_list)
))
print(
print (next
next(
(iter_list
iter_list)
))
Generator
Used to generate values on the fly
Decorators
Decorators are used to modifying the behavior of a function or a class. They are usually called before the definition
of a function you want to decorate.
setter Decorator
It is used to set the property 'name'
@name.
@name .setter
name(
def name (self
self,
, value
value)
):
self.
self .__name
__name=
=value
deleter Decorator
It is used to delete the property 'name'
@name.
@name .deleter #property-name.deleter decorator
name(
def name (self
self,, value
value)
):
print(
print ('Deleting..'
'Deleting..'))
self.
del self .__name
Post Comment
Comments (61)
ceras34320 2024-05-06
REPLY
harshchauhan17725_gm 2024-05-05
REPLY
vikasmali9265_gm 2024-04-30
REPLY
ysandrewng737_gm 2024-04-29
REPLY
ankur93045 2024-04-28
REPLY