0% found this document useful (0 votes)
14 views

Part 2

The document describes functions in Python. It defines functions as blocks of code that perform a specific task and may take parameters as input. Functions allow for code reusability and modular programming. The key points covered are: 1) The syntax for defining a function includes the def keyword followed by the function name and parameters in parentheses. The function body is indented and may return a value. 2) Functions can take parameters and default values can be set for parameters. 3) Variables inside functions are local, while global variables declared outside can be accessed if declared global inside the function. 4) Recursion is when a function calls itself, with the base case stopping further recursion. Recursion is used
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Part 2

The document describes functions in Python. It defines functions as blocks of code that perform a specific task and may take parameters as input. Functions allow for code reusability and modular programming. The key points covered are: 1) The syntax for defining a function includes the def keyword followed by the function name and parameters in parentheses. The function body is indented and may return a value. 2) Functions can take parameters and default values can be set for parameters. 3) Variables inside functions are local, while global variables declared outside can be accessed if declared global inside the function. 4) Recursion is when a function calls itself, with the base case stopping further recursion. Recursion is used
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

FUNCTIONS

54
Functions
■ The Python syntax for the definition of a function is as follows:
def name_function(list of params):
bloc k of statments
return (result)
■ Function without parameters:
def counter3():
i=0
while i < 3:
print(i)
i=i+1
counter3()

55
Functions

■ Function with a paramter ■ Function with many paramters


def counter(stop): def full_ counter(start, stop, step):
i=0 i = start
while i < stop: while i < stop:
print(i) print(i)
i=i+1 i = i + step
counter(4)
full_ counter(1, 7, 2)

56
Functions
■ Default values for parameters
– In the definition of a function, it is possible to define a default
argument for each of the parameters.
– We thus obtain a function which can be called with only part of the
expected arguments
■ Example :
def politeness(Name, title ="Sir"):
print(" Please accept, ", title, name, ", my best regards. ")
>>> politeness("Dupont")
Please accept, Sir Dupont, my best regards.
>>> politeness('Durand’, Miss')
Please accept, Miss Durand , my best regards.

57
Functions
■ Scope of variables(Global variable and Local variable)
– In the definition of a function, it is possible to define a default
argument for each of the parameters.
■ Example (local variable): ■ Example (global variable):
a=2 a=2
b=7 b=7
def test(): def test():
b=5 global b
print(a, b) b=5
test() print(a, b)
print(a, b) test() The value of b has
25 print(a, b) changed
27 25
25 58
Recursion
■ Recursion is the process of defining something in terms of itself.
■ In Programming, we know that a function can call other functions. It is even possible
for the function to call itself.
These types of construct are termed as recursive functions.

59
Recursion
■ The most typical example to understand recursion is to find the factorial of an integer.
■ Factorial of a number is the product of all the integers from 1 to that number.
■ For example, the factorial of 5 (denoted as 5!)

60
Recursion

Every recursive function must have a base condition that stops the recursion
or else the function calls itself infinitely.

■ The Python interpreter limits the depths of recursion to help avoid infinite
recursions, resulting in stack overflows.
■ By default, the maximum depth of recursion is 1000. If the limit is
crossed, it results in RecursionError. Let's look at one such condition.

def recursor(): Traceback (most recent call last):


File "<string>", line 3, in <module>
recursor() File "<string>", line 2, in a
recursor() File "<string>", line 2, in a
File "<string>", line 2, in a
[Previous line repeated 996 more times] RecursionError: maximum recursion depth exceeded
61
FILES

62
Files: reading and writing

■ To open o file we use the function open and specifying


the accessmode
myFile = open(fileName, accessMode)

Access mode Action


r Read the file
w Write to the file
a Append to the existing file content
b Open a binary file
Writing files

■ Tu put text in files we use the function write

fileName = "GuestList.txt"
accessMode = "w"
myFile = open(fileName, accessMode)
myFile.write("Hi there!")
myFile.write("How are you?")
Reading files

■ The function read is used to read from a file

fileContent= myFile.read()

■ The read function returns the entire contents of the file in the
form of a single character string.
■ Lines are separated by the character '\ n'
Reading files

■ We use the readline function to read from file line by line.

fileContent= myFile.readline()

■ The readline function return a line from file as string.


■ When attending the end of the file readline return an empty string.

 You should always close files


• In some cases, due to buffering, changes made to a file may not
show until you close the file.
Reading files

■ Examples
■ Read the first tow lines:

f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
f.close()
■ Read the whole file:

f = open("demofile.txt", "r")
for x in f:
print(x)
f.close()
SEQUENCES ET &
DICTIONARIES

68
Sequences
 Sequence is the most basic data structure in Python.
 Each element of a sequence is assigned a number, its position or index.
– The first index is zero, the second index is one, and so forth.

 Types of sequences :
– lists : [‘z’, 1, 2]
– Strings: "azerty«
– tuples : (1,2,3,8)
 The operators on sequences are the same:

69
Sequences
 S is a squence :
 S[i] : return (i+1)th element of S.
 S[ :a] : sub-sequence of elements from the beginning to the element a, a excepted.
 S[a: ] : sub-sequence of elements from the a included to the end.
 S[ : ] : the whole sequence.
 S[a:b] : sub-sequence of elements from a included to b excepted.
 S[a:b:c] : sub-sequence of elements from a included to b excepted with a step equal
c.
 len(S) number of elements.
 With negatives indices allow to access to the elements from the end (last element
S[-1] or L[len(L)-1], … )

70
Lists
 Sequential mutable container
 The type of elements can be heterogenous
 Example:
– >>> l = [1,42] # list of 2 elements
– >>> len(l) # length of l
– 2
– >>> l.append(4) # add an element at the end of the list
– >>> l
– [1, 42, 4]

71
Lists
Example :
>>> l.pop() # pull and return the last element of the list
>>> l[0:2] # return a sub-list
[1, 42]
>>> l[-1] the last element( l[len(l)-1])
4
>>> liste = [1, 2, 3, 4, 5, 6]
>>> liste[-3] #display the third element beginning from the end:
4
>>> liste[-3:] #display the last three element:
[4, 5, 6]

72
Lists
Example :
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> x + y #addition of two lists
[1, 2, 3, 4, 5, 6]

>>>x = [1, 2]
>>> x*5 #multiplication of list
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]

73
Lists
Exercise 1 :
Write a script that initializes a list of integers
Ask the user to enter an integer and test if it exists in the list. If so, multiply the
elements by 2.
Exercise 2 :
We want to simulate the dice game. The player rolls a die made up of 6 facets from
1 to 6. Each time he rolls, he randomly reorders the facets and he will get a
random facet. The player will win if he obtains the same facets of two
successive throws.
Implement this game using a list to represent the dice. Use the appropriate
functions for the arrangement and the random choice of the facet

74
Tuples
 Tuple is a sequential non-mutable container
 Ordered set of elements
 Not necessarily constant
 Examples :
a = (1,2,3) # create a new tuple
a[1] # return 2
a[0] = 4 # forbidden
a.append(42) # false
b = a + (4,) # full copy of a into b

75
Dictionaries

 Associative container, a kind of list but instead of using indexes, we use


alphanumeric keys.
 It allows you to store key : value pairs, with very fast access to the value
from the key
  the key can be present only once in the dictionary.
 To create a dictionary, we use the dictionary syntax:
 d = {1: ‘one ', 2:‘ two', 3: ‘three '}
 You can add or replace an element in a dictionary:
 dictionary [key] = value.
 >>> d [4] = ‘four’

76
Dictionaries

Examples :
>>> del d[2] # delete an element based on its key
>>> d
{1: ‘one', 3: ‘three', 4: ‘four'}
>>> d.keys() # return the list of keys (can be very expensive)
[1, 3, 4]
>>> d.values() # return the list of values
[‘ one ‘, ‘three’, ‘four']
>>> d.items() # return the list of pairs(key, value)
[(1, ‘one'), (3, ‘three'), (4, ‘four')]

77
case study:
We aim to develop an application dedicated to textual data analysis. The application has more
functionalities for textual files parsing and extraction of statistics. In this context, you are
required to implement some functionalities.
1. Write a function readTextfile (f) allowing to read a file f and return a list containing all the
lines of this file.
2. Write a function Wordfrequency () that allows to compute the frequency of words in the
whole text and return a dictionary, the keys are words and values are the frequencies .
3. White the function phrases () that allows to compute the number of phrases in each line
and return a dictionary which the keys are lines numbers and values are phrases count
Note : we assume that a phase ends with one of the following elements [“.”,”?”,”!”,”…”]

78

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy