Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Cheat Sheet

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Save Copy to Evernote

Last updated: Jul 14, 2021

Python Cheat Sheet


Save Copy to Evernote

Various Ways to Print:


# printing the list using * operator separated 
# by space 
print(*a)
  
# printing the list using * and sep operator
print("printing lists separated by commas")
  
print(*a, sep = ", ") 
  
# print in new line
print("printing lists in new line")
  
print(*a, sep = "\n")
Output
1 2 3 4 5
printing lists separated by commas
1, 2, 3, 4, 5
printing lists in new line
1
2
3
4
5

Convert a list to a string for display


a =["Geeks", "for", "Geeks"]
  
# print the list using join function()
print(' '.join(a))
  
# print the list by converting a list of  Save Copy to Evernote
# integers to string 
a = [1, 2, 3, 4, 5]
  
print str(a)[1:-1] 
Output
Geeks for Geeks
1, 2, 3, 4, 5

  
a = [1, 2, 3, 4, 5]
print(' '.join(map(str, a))) 
  
print"in new line"
print('\n'.join(map(str, a)))

end= ” ” statement

The end keyword is used to specify the content that is to be printed at the end of the execution of the
print() function. By default, it is set to “\n”, which leads to the change of line after the execution of print()
statement.
print ("GeeksForGeeks is the best platform for DSA content")
 
# This print() function ends with "**" as set in the end argumennt.
print ("GeeksForGeeks is the best platform for DSA content", end= "**")
print 8 blank lines
print (8 * "\n")

Lamda Expression

# Program to show the use of lambda functions


double = lambda x: x * 2
print(double(5))

filter()

# Program to filter out only the even items from a list


my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)

map() in lambda

# Program to double each item in a list using map()


my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list) Save Copy to Evernote

The global Keyword

If we want those changes to be reflected in our global variable, instead of making a new local one, all we
have to do is add the global keyword. This allows us to communicate that the fruit variable is indeed a
global variable:
We could also define a global variable within our function and have it be able to be referenced and
accessed anywhere else.

fruit = ['pineapple', 'grapes']

def shopping_list():
    global fruit
    fruit = ['pineapple', 'grapes', 'apple', 'banana']

shopping_list()
print(fruit)

nonlocal, a keyword which functions very similarly to global, but primarily takes effect when nested in
methods. nonlocal essentially forms an in-between of global and local scope.
Number Data Type in Python
Python supports integers, floating-point numbers and complex numbers. They are defined as int, float,
and complex classes in Python.
Complex numbers are written in the form, x + yj, where  x  is the real part and  y  is the imaginary part.
We can use the type() function to know which class a variable or a value belongs to
and isinstance() function to check if it belongs to a particular class.

a = 5

print(type(a))

print(type(5.0))

c = 5 + 3j
print(c + 3)

print(isinstance(c, complex))

When we run the above program, we get the following output:


<class 'int'>
<class 'float'>
(8+3j)
True

In Python, we can represent these numbers by appropriately placing a prefix before that number. The
following table lists these prefixes.
Number System Prefix Save Copy to Evernote

Binary '0b' or '0B'

Octal '0o' or '0O'

Hexadecimal '0x' or '0X'

How to create a list?


In Python programming, a list is created by placing all the items (elements) inside square brackets [],
separated by commas.

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed data types


my_list = [1, "Hello", 3.4]

A list can also have another list as an item. This is called a nested list.

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

Negative indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second
last item and so on.

How to slice lists in Python?


We can access a range of items in a list by using the slicing operator :(colon).

# List slicing in Python

my_list = ['p','r','o','g','r','a','m','i','z']

# elements 3rd to 5th


print(my_list[2:5])

# elements beginning to 4th


print(my_list[:-5])

# elements 6th to end


print(my_list[5:])

# elements beginning to end Save Copy to Evernote


print(my_list[:])

Output

['o', 'g', 'r']


['p', 'r', 'o', 'g']
['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']

Add/Change List Elements


Lists are mutable, meaning their elements can be changed unlike string or tuple.
odd = [2, 4, 6, 8]

# change the 1st item   


odd[0] = 1           

print(odd)

# change 2nd to 4th items


odd[1:4] = [3, 5, 7] 

print(odd)                 

Output
[1, 4, 6, 8]
[1, 3, 5, 7]

We can add one item to a list using the append() method or add several items using extend() method.

# Appending and Extending lists in Python


odd = [1, 3, 5]

odd.append(7)

print(odd)

odd.extend([9, 11, 13])

We can also use + operator to combine two lists. This is also called concatenation.

The * operator repeats a list for the given number of times.

# Concatenating and repeating lists


odd = [1, 3, 5]

print(odd + [9, 7, 5])

print(["re"] * 3)
Output

Save Copy to Evernote


[1, 3, 5, 9, 7, 5]
['re', 're', 're']

we can insert one item at a desired location by using the method insert() or insert multiple items by
squeezing it into an empty slice of a list.

# Demonstration of list insert() method


odd = [1, 9]
odd.insert(1,3)

print(odd)

odd[2:2] = [5, 7]

print(odd)

Output

[1, 3, 9]
[1, 3, 5, 7, 9]

Delete/Remove List Elements


We can delete one or more items from a list using the keyword del. It can even delete the list entirely.

# Deleting list items


my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

# delete one item


del my_list[2]

print(my_list)

# delete multiple items


del my_list[1:5]

print(my_list)

# delete entire list


del my_list

# Error: List not defined


print(my_list)

Python List Methods

append() - Add an element to the end of the list

extend() Add all elements of a list to the another list Also add Multiple items to a list
extend() - Add all elements of a list to the another list. Also add Multiple items to a list

insert() - Insert an item at the defined index Save Copy to Evernote

remove() - Removes an item from the list. but shows error if not found

pop() - Removes and returns an element at the given index

clear() - Removes all items from the list

index() - Returns the index of the first matched item

count() - Returns the count of the number of items passed as an argument

sort() - Sort items in a list in ascending order

reverse() - Reverse the order of items in the list

copy() - Returns a shallow copy of the list

List Comprehension:

pow2 = [2 ** x for x in range(10)]

List Membership Test

We can test if an item exists in a list or not, using the keyword in.

my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

# Output: True
print('p' in my_list)

# Output: True
print('c' not in my_list)

Tuples
A tuple in Python is similar to a list. The difference between the two is that we cannot change the
elements of a tuple once it is assigned whereas we can change the elements of a list.
A tuple is created by placing all the items (elements) inside parentheses (), separated by commas. 
# Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers


my_tuple = (1, 2, 3)
y p
print(my_tuple)

Save Copy to Evernote


# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

Having one element within parentheses is not enough. We will need a trailing comma to indicate that it is,
in fact, a tuple.
# Creating a tuple having one element
my_tuple = ("hello",)
print(type(my_tuple))  # <class 'tuple'>

Indexing of Tuple

We can use the index operator [] to access an item in a tuple, where the index starts from 0.

# Accessing tuple elements using indexing


my_tuple = ('p','e','r','m','i','t')

print(my_tuple[0])  # 'p'
print(my_tuple[5])  # 't'

Slicing

We can access a range of items in a tuple by using the slicing operator colon :.

# Accessing tuple elements using slicing


my_tuple = ('p','r','o','g','r','a','m','i','z')

# elements 2nd to 4th


# Output: ('r', 'o', 'g')
print(my_tuple[1:4])

# elements beginning to 2nd


# Output: ('p', 'r')
print(my_tuple[:-7])

# elements 8th to end


# Output: ('i', 'z')
print(my_tuple[7:])

# elements beginning to end


# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])

Changing a Tuple
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed once they have been assigned. But, if the element
is itself a mutable data type like a list, its nested items can be changed. Save Copy to Evernote
We can also assign a tuple to different values (reassignment).

# Changing tuple values


my_tuple = (4, 2, 3, [6, 5])

# TypeError: 'tuple' object does not support item assignment


# my_tuple[1] = 9

# However, item of mutable element can be changed


my_tuple[3][0] = 9    # Output: (4, 2, 3, [9, 5])
print(my_tuple)

# Tuples can be reassigned


my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)

 + and * operations result in a new tuple.

# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))

# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)

Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. It means that we cannot delete or remove
items from a tuple.
Deleting a tuple entirely, however, is possible using the keyword del.

Tuple Membership Test

# Membership test in tuple


my_tuple = ('a', 'p', 'p', 'l', 'e',)

# In operation
print('a' in my_tuple)
print('b' in my_tuple)

# Not in operation
print('g' not in my_tuple)

Iterating Through a Tuple

We can use a for loop to iterate through each item in a tuple.


# Using a for loop to iterate through a tuple
g p g p
for name in ('John', 'Kate'):
    print("Hello", name)
Save Copy to Evernote

Advantages of Tuple over List

We generally use tuples for heterogeneous (different) data types and lists for homogeneous
(similar) data types.
Since tuples are immutable, iterating through a tuple is faster than with list. So there is a slight
performance boost.
Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not
possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-
protected.

String in Python

# triple quotes string can extend multiple lines


my_string = """Hello, welcome to
          the world of Python""

Access characters in a string

#Accessing string characters in Python


str = 'programiz'
print('str = ', str)

#first character
print('str[0] = ', str[0])

#last character
print('str[-1] = ', str[-1])

#slicing 2nd to 5th character


print('str[1:5] = ', str[1:5])

#slicing 6th to 2nd last character


print('str[5:-2] = ', str[5:-2])

Strings are immutable. This means that elements of a string cannot be changed once they have been
assigned. We can simply reassign different strings to the same name.
We cannot delete or remove characters from a string. But deleting the string entirely is possible using
the del keyword.
# Python String Operations
str1 = 'Hello'
str2 ='World!'

# using +
print('str1 + str2 = ', str1 + str2)

# using *
print('str1 * 3 =', str1 * 3)
# Iterating through a string
count = 0 Save Copy to Evernote
for letter in 'Hello World':
    if(letter == 'l'):
        count += 1
print(count,'letters found')

String Membership Test

We can test if a substring exists within a string or not, using the keyword in.
>>> 'a' in 'program'
True
>>> 'at' not in 'battle'
False

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position of where it was
found

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where it was
found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier


islower() Returns True if all characters in the string are lower case
Save Copy to Evernote
isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a specified value

rfind() Searches the string for a specified value and returns the last position of where it
was found

rindex() Searches the string for a specified value and returns the last position of where it
was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string


translate() Returns a translated string

upper() Converts a string into upper case Save Copy to Evernote

zfill() Fills the string with a specified number of 0 values at the beginning

Sets in Python
A set is an unordered collection of items. Every set element is unique (no duplicates) and must be
immutable (cannot be changed).
Creating Python Sets
A set is created by placing all the items (elements) inside curly braces {}, separated by comma, or by using
the built-in set() function.It can have any number of items and they may be of different types (integer, float,
tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements.

my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes


my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

# set cannot have duplicates


# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)

# we can make set from a list


# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)

# set cannot have mutable items


# here [3, 4] is a mutable list
# this will cause an error.

my_set = {1, 2, [3, 4]}

Creating an empty set is a bit tricky.

Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements, we
use the set() function .without any argument.

Modifying a set in Python


Sets are mutable. However, since they are unordered, indexing has no meaning.
We cannot access or change an element of a set using indexing or slicing. Set data type does not support
it.
We can add a single element using the add() method and multiple elements using the update() method
We can add a single element using the add() method, and multiple elements using the update() method.
The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates
are avoided. Save Copy to Evernote

# initialize my_set
my_set = {1, 3}
print(my_set)

# my_set[0]
# if you uncomment the above line
# you will get an error
# TypeError: 'set' object does not support indexing

# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)

# add multiple elements


# Output: {1, 2, 3, 4}
my_set.update([2, 3, 4])
print(my_set)

# add list and set


# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4, 5], {1, 6, 8})
print(my_set)

A particular item can be removed from a set using the methods discard() and remove().


The only difference between the two is that the discard() function leaves a set unchanged if the element is
not present in the set. On the other hand, the remove() function will raise an error in such a condition (if
element is not present in the set).

# Difference between discard() and remove()

# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)

# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)

# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)

# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)

# remove an element
i
# not present in my_set
# you will get an error.
# Output: KeyError Save Copy to Evernote

my_set.remove(2)

we can remove and return an item using the pop() method.


Since set is an unordered data type, there is no way of determining which item will be popped. It is
completely arbitrary.

Python has a set of built-in methods that you can use on sets.

Method Description

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between two or more sets

difference_upda Removes the items in this set that are also included in another, specified set
te()

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two or more sets

intersection_up Removes the items in this set that are not present in other, specified set(s)
date()

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_diffe Returns a set with the symmetric differences of two sets


rence()

symmetric_diffe inserts the symmetric differences from this set and another
rence_update()

union() Return a set containing the union of sets

update() Update the set with another set, or any other iterable
Set Membership Test
Save Copy to Evernote
We can test if an item exists in a set or not, using the in keyword.

my_set = set("apple")

# check if 'a' is present


# Output: True
print('a' in my_set)

Iterating Through a Set

We can iterate through each item in a set using a for loop.

>>> for letter in set("apple"):


...    print(letter)
...   
a
p
e
l

Built-in Functions with Set

Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used


with sets to perform different tasks.

Function Description

all() Returns True if all elements of the set are true (or if the set is empty).

any() Returns True if any element of the set is true. If the set is empty, returns False.

enumerate() Returns an enumerate object. It contains the index and value for all the items of the
set as a pair.

len() Returns the length (the number of items) in the set.

max() Returns the largest item in the set.

min() Returns the smallest item in the set.

sorted() Returns a new sorted list from elements in the set(does not sort the set itself).

sum() Returns the sum of all elements in the set.

 Python Dictionary
Python dictionary is an unordered collection of items. Each item of a dictionary has a key/value pair.
# empty dictionary Save Copy to Evernote
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])

Accessing Elements from Dictionary


 Keys can be used either inside square brackets [] or with the get() method.
# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error


# Output None
print(my_dict.get('address'))

# KeyError
print(my_dict['address'])

Changing and Adding Dictionary elements


Dictionaries are mutable. We can add new items or change the value of existing items using an
assignment operator.

# Changing and adding Dictionary Elements


my_dict = {'name': 'Jack', 'age': 26}

# update value
my_dict['age'] = 27

#Output: {'age': 27, 'name': 'Jack'}


print(my_dict)

# add item
my_dict['address'] = 'Downtown'

# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}

Removing elements from Dictionary


Removing elements from Dictionary
Save removes
We can remove a particular item in a dictionary by using the pop() method. This method Copy to Evernote
an item
with the provided key and returns the value.
The popitem() method can be used to remove and return an arbitrary (key, value) item pair from the
dictionary. All the items can be removed at once, using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.

Python Dictionary Comprehension

# Dictionary Comprehension
squares = {x: x*x for x in range(6)}

print(squares)

# Dictionary Comprehension with if conditional


odd_squares = {x: x*x for x in range(11) if x % 2 == 1}

print(odd_squares)

Dictionary Membership Test

We can test if a key is in a dictionary or not using the keyword in only for the keys and not for the values.
# Membership Test for Dictionary Keys
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

# Output: True
print(1 in squares)

# Output: True
print(2 not in squares)

# membership tests for key only not value


# Output: False
print(49 in squares)

Opening Files in Python

>>> f = open("test.txt")    # open file in current directory


>>> f = open("C:/Python38/README.txt")  # specifying full path
f.close()

This method is not entirely safe. If an exception occurs when we are performing some operation with the
file, the code exits without closing the file.

try:
  f = open("test.txt", encoding = 'utf-8')
  # perform file operations
finally:
  f.close()
with open("test.txt", encoding = 'utf-8') as f:
  # perform file operations
Save Copy to Evernote

Writing to Files in Python


In order to write into a file in Python, we need to open it in write w, append a or exclusive creation x mode.
with open("test.txt",'w',encoding = 'utf-8') as f:
  f.write("my first file\n")
  f.write("This file\n\n")
  f.write("contains three lines\n")

Reading Files in Python


To read a file in Python, we must open the file in reading r mode.
>>> f = open("test.txt",'r',encoding = 'utf-8')
>>> f.read(4)    # read the first 4 data
'This'

>>> f.read(4)    # read the next 4 data


' is '

>>> f.read()    # read in the rest till end of file


'my first file\nThis file\ncontains three lines\n'

>>> f.read()  # further reading returns empty sting


''

We can change our current file cursor (position) using the seek() method. Similarly, the tell() method
returns our current position (in number of bytes).

>>> f.tell()    # get the current file position


56

>>> f.seek(0)  # bring file cursor to initial position


0

>>> print(f.read())  # read the entire file


This is my first file
This file
contains three lines

we can use the readline() method to read individual lines of a file. This method reads a file till the newline,
including the newline character.
>>> f.readlines()
['This is my first file\n', 'This file\n', 'contains three lines\n']
#use strip() to remove \n

Python Directory

Get Current Directory


We can get the present working directory using the getcwd() method of the os module.
>>> import os Save Copy to Evernote

>>> os.getcwd()
'C:\\Program Files\\PyScripter'

>>> os.getcwdb()
b'C:\\Program Files\\PyScripter'

Changing Directory

>>> os.chdir('C:\\Python33')

>>> print(os.getcwd())
C:\Python33

List Directories and Files


All files and sub-directories inside a directory can be retrieved using the listdir() method.

>>> print(os.getcwd())
C:\Python33

>>> os.listdir()
['DLLs',
'Doc',
'include',
'Lib',
'libs',
'LICENSE.txt',
'NEWS.txt',
'python.exe',
'pythonw.exe',
'README.txt',
'Scripts',
'tcl',
'Tools']

Making a New Directory

>>> os.mkdir('test')

>>> os.listdir()
['test']

Renaming a Directory or a File

>>> os.listdir()
['test']

>>> os.rename('test','new_one')

Removing Directory or File


>>> os.rmdir('new_one') Save Copy to Evernote
Note: The rmdir() method can only remove empty directories.
In order to remove a non-empty directory, we can use the rmtree() method inside the shutil module.
>>> import shutil

>>> shutil.rmtree('test')
>>> os.listdir()
[]

Catching Exceptions in Python

# import module sys to get the type of exception


# The critical operation which can raise an exception is placed inside the try clause.
The code that handles the exceptions is written in the except clause.
import sys

randomList = ['a', 0, 2]

for entry in randomList:


    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except:
        print("Oops!", sys.exc_info()[0], "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)

If no exception occurs, the except block is skipped and normal flow continues(for last value). But if any
exception occurs, it is caught by the except block (first and second values).
Here, we print the name of the exception using the exc_info() function inside sys module. We can see
that a causes ValueError and 0 causes ZeroDivisionError.

# program to print the reciprocal of even numbers

try:
    num = int(input("Enter a number: "))
    assert num % 2 == 0
except:
    print("Not an even number!")
else:
    reciprocal = 1/num
    print(reciprocal)

Python try...finally
The try statement in Python can have an optional finally clause. This clause is executed no matter what,
and is generally used to release external resources.

try:
f = open("test.txt",encoding = 'utf-8')
  f open( test.txt ,encoding utf 8 )
  # perform file operations
finally: Save Copy to Evernote
  f.close()

Object Oriented Programming

class Parrot:

    # class attribute
    species = "bird"

    # instance attribute
    def __init__(self, name, age):
        self.name = name
        self.age = age

# instantiate the Parrot class


blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)

# access the class attributes


print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))

# access the instance attributes


print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))

Methods

class Parrot:
   
    # instance attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age
   
    # instance method
    def sing(self, song):
        return "{} sings {}".format(self.name, song)

    def dance(self):
        return "{} is now dancing".format(self.name)

# instantiate the object


blu = Parrot("Blu", 10)

# call our instance methods


print(blu.sing("'Happy'"))
print(blu.dance())

Inheritance
we use the super() function inside the __init__() method. This allows us to run the __init__() method of the
parent class inside the child class.
# parent class
class Bird: Save Copy to Evernote
   
    def __init__(self):
        print("Bird is ready")

    def whoisThis(self):
        print("Bird")

    def swim(self):
        print("Swim faster")

# child class
class Penguin(Bird):

    def __init__(self):
        # call super() function
        super().__init__()
        print("Penguin is ready")

    def whoisThis(self):
        print("Penguin")

    def run(self):
        print("Run faster")

peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()

Encapsulation
In Python, we denote private attributes using underscore as the prefix i.e single _ or double __.
lass Computer:

    def __init__(self):
        self.__maxprice = 900

    def sell(self):
        print("Selling Price: {}".format(self.__maxprice))

    def setMaxPrice(self, price):


        self.__maxprice = price

c = Computer()
c.sell()

# change the price


c.__maxprice = 1000
c.sell()

# using setter function


c.setMaxPrice(1000)
c.sell()

P l hi
Polymorphism
Save Copy to Evernote
class Parrot:

    def fly(self):
        print("Parrot can fly")
   
    def swim(self):
        print("Parrot can't swim")

class Penguin:

    def fly(self):
        print("Penguin can't fly")
   
    def swim(self):
        print("Penguin can swim")

# common interface
def flying_test(bird):
    bird.fly()

#instantiate objects
blu = Parrot()
peggy = Penguin()

# passing the object


flying_test(blu)
flying_test(peggy)

In the above program, we defined two classes  Parrot  and  Penguin . Each of them have a
common fly() method. However, their functions are different.
To use polymorphism, we created a common interface i.e flying_test() function that takes any object and
calls the object's fly() method. Thus, when we passed the  blu  and  peggy  objects in
the flying_test() function, it ran effectively.

Constructors in Python
use  __init__(self, variable)
class ComplexNumber:
    def __init__(self, r=0, i=0):
        self.real = r
        self.imag = i

    def get_data(self):
        print(f'{self.real}+{self.imag}j')

# Create a new ComplexNumber object


num1 = ComplexNumber(2, 3)

# Call get_data() method


# Output: 2+3j
num1.get_data()
# Create another ComplexNumber object
# and create a new attribute 'attr' Save Copy to Evernote
num2 = ComplexNumber(5)
num2.attr = 10

# Output: (5, 0, 10)


print((num2.real, num2.imag, num2.attr))

# but c1 object doesn't have attribute 'attr'


# AttributeError: 'ComplexNumber' object has no attribute 'attr'
print(num1.attr)

Deleting Attributes and Objects


Any attribute of an object can be deleted anytime, using the del statement. 

>>> num1 = ComplexNumber(2,3)


>>> del num1.imag

Automatic destruction of unreferenced objects in Python is also called garbage collection.


Python Multiple Inheritance

class Base1:
    pass

class Base2:
    pass

class MultiDerived(Base1, Base2):


    pass

Python Multilevel Inheritance

class Base:
    pass

class Derived1(Base):
    pass

class Derived2(Derived1):
    pass

sorted() function:
sorted(iterable, key, reverse)
Note: No matter what iterable is passed in to the sorted() function, it always returns a list.
Save Copy to Evernote
Save Copy to Evernote
Save Copy to Evernote
Save Copy to Evernote

Terms of Service Privacy Policy Report Spam

You might also like