Vous êtes sur la page 1sur 10

Python

 Exception handling:-
We can use try/except statement. The try block contains the code that might throw a exception, if that
exception occurs, the code will not be executed. If error occurs, the code in except block will be executed.
If there is no error, Code in except block will not executed.
try:

num1=7

num2=0

print(num1/num2)

print('Done Calculation')

except ZeroDivisionError as e:

print('An error occured')

Finally:-
To ensure some code runs no matter what errors occurs, a finally statement can used. The finally
statement is placed at the bottom of a try/except statement.
try:

num1=7

num2=0

print(num1/num2)

print('Done Calculation')

except ZeroDivisionError as e:

print('An error occured')

finally:

print('this will be printed')

Raising Exceptions:-
We can raise exceptions by using the raise statement. Exceptions can be raised with arguments that
give detail about them.
name="123"

raise NameError('invalid name')

In except block, the raise statement can be used without arguments to reraise whatever exception
occured.
try:

num=5/0

except:

print('error occured')
Raise

Assertions:-
An assertion is a sanity check that we can turn on or turn off when you have finished testing the
program. An expression is tested, and if the result comes up false, an exception is raised. Syntax is assert
assert 1+1==4

print(3)

The assert can take a second argument that is passed to the assertion error if the assertion fails.
assert 1+1==4,'Second argument'

print(3)

 File Handling:-
Opening Files:-
File can be opened using open function.
Myfile=open(‘filename.txt’)

It can take second argument as the mode used to open a file.


“r” opens file in read mode.
“w” opens file in write mode, for rewriting the contents of the file.
“a” means append mode, for adding new content to the end of the file.
Once a file has been opened and used, we should close it. This is done with the close method of the file
object. Syntax is file.close()
Reading Files:-
The contents of a file that been opened in text mode can be read using the read method.
file=open('filename.txt','r')

cont=file.read()

print(cont)

file.close()

Argument in file.read() defines number of bytes to read.


To retrieve each line in a file, you can use the readlines method to return a list in which each element is a
line in the file
file=open('filename.txt','r')

print(file.readlines())

file.close()

We can also use a for loop to iterate through the lines in the file.
file=open('filename.txt','r')

for line in file:

print(line)
file.close()

Writing Files:-
To write to files we use write method, which writes a string to a file.
file=open('filename.txt','w')

file.write('this will be written to the file.')

file.close()

file=open('filename.txt','r')

print(file.read())

file.close()

The write method returns the number of bytes written to a file, if successful.
file=open('filename.txt','w')

amount=file.write('this will be written to the file.')

print(amount)

file.close()

 Data Types:-
None:-
the None object is used to represent the absence of a value. The None object is returned by any
function that doesn’t explicitly return anything else.
def func():

print('hi')

var=func()

print(var)

Dictionaries:-
Dictionaries are data structures used to map arbitary keys to values. It can be indexed using square
brackets containing keys.
ages={'dave':25,'mary':89,'joe':56}

print(ages['dave'])

print(ages['joe'])

Dictionary keys can be assigned to different values. A new dictionary key can also be assigned a value, not
just ones that already exist.
dict1={1:'test'}

dict1[2]='new'

dict1[1]='old'

print(dict1)
One of the method in dictionary is get. It does the same thing as indexing, but if key is not found in the
dictionary it returns another specified value instead(‘none’,by default)
dict1={1:'test'}

dict1[2]='new'

dict1[1]='old'

print(dict1.get(3,'this will be shown'))

Tuples:-
Tuples are similar to lists, except that they cannot be changed. These are created using parentheses, rather
than square brackets. Tuples can be created by just separating the values by commas.
tuple1='one','two','three'

print(tuple1[0])

List Slices:-
List slicing involves indexing a with two colons separated integers. This returns a new list containing all the
values in the old list between the indices.
squrares=[0,1,2,3,4,5,6,7]

print(squrares[2:7])

if the first number is missing ,it is taken from start of the list. If the second number is missing, it is taken to
last of the list.
List slices can also have a third number, representing the step, to include only alternate values in the slice.
squrares=[0,1,2,3,4,5,6,7]

print(squrares[2:7:2])

Negative values can be used in list slicing. When negative values are used for the first and second values in
a slice, they count from the end of the list.
squrares=[0,1,2,3,4,5,6,7]

print(squrares[7:2:-2])

String Formatting:-
It provides a more powerful way to embed non-strings within strings. String formatting uses a string’s
format method to substitute a number of arguments in the string.
squrares=[0,1,2,3,4,5,6,7]

msg='numbers: {0} {1} {2}'.format(squrares[2],squrares[1],squrares[5])

print(msg)

String formatting can also be done with named arguments.


String Functions:-
Join- joins a list of strings with another string as a separator.
Replace- replaces one substring in a string with another.
Startswith and Endswith- determine if there is a substring at the start and end of a string, respectively.
To change the case of a string, you can use lower and upper.
The method split is the opposite of join, turning a string with a certain separator into a list.
print(", ".join(["spam", "eggs", "ham"]))
#prints "spam, eggs, ham"

print("Hello ME".replace("ME", "world"))


#prints "Hello world"

print("This is a sentence.".startswith("This"))
# prints "True"

print("This is a sentence.".endswith("sentence."))
# prints "True"

print("This is a sentence.".upper())
# prints "THIS IS A SENTENCE."

print("AN ALL CAPS SENTENCE".lower())


#prints "an all caps sentence"

print("spam, eggs, ham".split(", "))


#prints "['spam', 'eggs', 'ham']"

Text analyzer:-
This shows a program shows a function that counts how many times a character occurs in a string.
def count1(text,char):

count=0

for c in text:

if c==char:

count+=1

return count

filename=input('enter filename')

with open(filename) as f:

text=f.read()

print(count1(text,'t'))

 Functional programming:-
Map:-
The function Map takes a function and an iterable as arguments, and returns a new iterable with the
function applied to each arguments.
def addfive(x):

return x+5

nums=[0,1,2,3]
result=list(map(addfive,nums))

print(result)

Filter:-
The function filter filters an iterate by removing items that don’t match a predicate.
def hi(x):

if x%2==0:

return x

nums=[0,1,4,6,8,7,4]

result=list(filter(hi,nums))

print(result)

Generators:-
def countdown():

i=5

while i>0:

yield i

i-=1

for i in countdown():

print(i)

 Object-Oriented Programming
Classes:-
A class can be described as an object’s blueprint, description, or definition. You can use the same class
as a blueprint for creating multiple different objects. Classes are created using the keyword class and an
indented block, which contains class methods.(which are functions).
The __init__ is called when an instance (object) of the class is created, using the class name as a function.
All methods must have self as their first parameter. In an __init__ method, self.attribute can therefore be
used to set the initial value of the instance’s attributes.
class cat:

def __init__(self,color,legs):

self.color=color

self.legs=legs

felix=cat('ginger',4)

rover=cat('dog-colored',4)

stumpy=cat('brown',3)

print(felix.color)

Inheritance:-
Inheritance provide a way to share functionality between classes. To inherit a class from another class,
put the superclass name in parenthess after the class name. A class that inherits from another class is
called a subclass. A class that is inherited from is called a superclass. One class can inherit from another,
and that class can inherit from a third class.
The function super is a useful inheritance-related function that refers to the parent class. It can be
used to find the method with a certain name in an object’s superclass.
class a:

def spam(self):

print(1)

class b(a):

def spam(self):

super().spam()

print(2)

b().spam()

Magic Methods:-
Magic methods are special methods which have double underscores at the beginning and end of
their name. One common use of them is operator overloading. This means that defining operators for
the custom classes that allow operators such as + and * to be used on them.
An example magic function is __add__ for +.
class vector():

def __init__(self,x,y):

self.x=x

self.y=y

def __add__(self,other):

return vector(self.x+ other.x,self.y+other.y)

first=vector(2,5)

second=vector(6,9)

result=first+second

print(result.x)

print(result.y)

More magic methods:__sub__ for -, __mul__ for *, __truediv__ for /, __floordiv__ for //, __mod__
for %, __pow__ for **, __and__ for &, __xor__ for ^, __or__ for |
class specialstring:

def __init__(self,cont):

self.cont=cont

def __truediv__(self,other):
line='='*len(other.cont)

return '\n'.join([self.cont,line,other.cont])

spam=specialstring("spam")

hello=specialstring('hello world')

print(spam/hello)

Data Hiding:-
Weakly private methods and attributes have a single underscore at the beginning. This signals that
they are private, and shouldn’t be used by external code. However, it is mostly only a convention, and does
not stop external code from accessing them. Its only actual effect is that form module_name import*
won’t import variables that start with a single underscore.
class queue:

def __init__(self,contents):

self._hiddenlist=list(contents)

def push(self,value):

self._hiddenlist.insert(0,value)

def pop(self):

return self._hiddenlist.pop(-1)

def __repr__(self):

return 'queue({})'.format(self._hiddenlist)

queue=queue([1,2,3])

print(queue)

queue.push(0)

print(queue)

queue.pop()

print(queue)

print(queue._hiddenlist)

Strongly private methods and attributes have a double underscore at the beginning of their names.
This causes their names to be mangled, which means that they can’t be assessed from outside the class.
Name mangled methods can still be accessed externally, but by a different name. The method
__privatemethod of class spam can be accessed externally with _spam__privatemethod.
class spam:

__egg=7

def print_egg(self):

print(self.__egg)

s=spam()

s.print_egg()

print(s._spam__egg)
print(s._egg)

Class methods:-
Class methods are called by a class, which is passed to the cls parameter of the method. Class methods
are marked with a classmethod decorator.
class rectangle:

def __init__(self,width,height):

self.width=width

self.height=height

def calculate(self):

return self.width*self.height

@classmethod

def newsquare(cls,newlength,newbreadth):

return cls(newlength,newbreadth)

square=rectangle.newsquare(5,6)

print(square.calculate())

Newsquare is a class method and is called on the class, rather than on an instance of the class. It
returns a new object of the class cls.
Static methods:-
Static functions don’t receive any additional arguments; they are identical to normal functions that
belong to a class. They are marked with the staticmethod decorator.
class pizza:

def __init__(self,topping):

self.topping=topping

@staticmethod

def validate_topping(topping):

if topping=="pineapple":

print('no pineapple')

else:

return True

ingredients=['cheese','onions','spam',]

if all(pizza.validate_topping(i) for i in ingredients):

pizza=pizza(ingredients)

print(pizza.validate_topping([1]))

A simple game:-
Example 1:-
def get_input():

command=input(':').split()

verb_word=command[0]

if verb_word in verb_dict:

verb=verb_dict[verb_word]

else:

print('unknown verb {}'.format(verb_word))

return

if len(command)>=2:

noun_word=command[1]

print (verb(noun_word))

else:

print(verb('nothing'))

def say(noun1):

return 'you said "{}"'.format(noun1)

verb_dict={'says':say}

while True:

get_input()

 Regular expressions:-
Regular expressions are domain specific language(DSL) that is present as a library in python. They are
useful for two main tasks:-
-verifying that strings match a pattern
-performing substitutions in a string
Regular expressions can be accessed using the re module, which is a part of the standard library. The
re.match function can be used to determine whether it matches at the beginning of a string. If it does,
match returns an object representing the match, if not, it returns none. Raw strings will be used as
r“expression”. Raw strings don’t escape anything, which makes use of regular expression easier.

Vous aimerez peut-être aussi