You are on page 1of 54

Cours Python

Prof:Mouna HALIMA
2

CHAPTER 1:
INTRODUCTION TO
PYTHON

Prof:Mouna HALIMA
3

Chapter outcomes
• The learning objectives of this course are:

• To understand why Python is a useful scripting language for

developers.

• To learn how to design and program Python applications.

• To learn how to write loops and decision statements in Python.

• To learn how to use lists, tuples, and dictionaries in Python

Prof:Mouna HALIMA
programs.
4

PART 1 – BASIC
CONCEPTS

Prof:Mouna HALIMA
5

what is python?

• A modern interpreted programing


language, created in 1991 by
Guido van Rossum.
• Known for requiring less code to
accomplish tasks than other
languages
Principles:
• Allows programmer to be Simple
• Allows programmer Complexity,
without being complicated

Prof:Mouna HALIMA
• Readable
6

Basic Concepts:
Comment display output to the
user
#This is my first program "Hello World!" You can use single
print ("Teacher says: Hello World!") quotes or double
""" This would be a multi line comment quotes
in Python that spans several lines and Multi line
describes your code, your day, or Comment
anything you want it to"""
print ('I said to the class "sometimes
you need to shutdown and restart a
notebook when cells refuse to run"')
print("It's time to save your code")

Prof:Mouna HALIMA
Output:
Teacher says: Hello World!
I said to the class "sometimes you need to shutdown and restart a notebook when
cells refuse to run"
7

Variables
• In Python variables are used to store values.
• The type of data stored is called the data type of the
variable.
• Three common data types:

String (str) Integer (int) Float (float)


A series of letters, A whole number- no A decimal number.
numbers, and spaces. decimals.
Always enclosed in
quotes

Prof:Mouna HALIMA
Variable assignment
• To give a variable a value we use an assignment statement.
• Do not give the variable a type. The interpreter will decide
type based on the value entered.

varName = value
Message = "This is a string of data"

Prof:Mouna HALIMA
Variables are case sensitive! Num1
same variable!
and num1 are NOT the
9

Exercise 1

Why does this error What is the output ?


occur? message1 = "This is some dat
num1 = "2"
message2 = " that we must di
num2 = 1
message3 = message1+ message
num3 = num1 + num2
print(message3)
Output:
Traceback (most recent call last):
File "C:/Users/PycharmProjects/CS120/Example1.py",
line 3, in <module>
Output:
num3 = num1 + num2 This is some data that we must discuss
TypeError: Can't convert 'int' object to str implicitly

Process finished with exit code 1

Prof:Mouna HALIMA
The quotes make all the difference!
Num1 is a string. Strings cannot be
Strings can be added together. This is
called concatenation.
added to integers.
10

Exercise 2

What is the output ?

message = "This is a python course"


message1 = "What is your name?"
print(message)
print(message1+ " =Justin")

Output:
This is a python course
What is your name?

Prof:Mouna HALIMA
=Justin
11

Variable reassignment

• To give a variable a new value simple write a new


assignment statement. New value will overwrite the
old value.
num1 = 6
print (num1) Output:
6
num1 = 8
8
print(num1)

Prof:Mouna HALIMA
12

type() Function
• Returns the data type of the given data or variable

a = 5
print (type(a)) Output:
<class 'int'>
ch = 'this is a message'
<class 'str'>
print (type(ch))

Prof:Mouna HALIMA
13

INPUT Function
• In Python use the input() function to gather input from the user

name1 = input("enter your name: ")


print (name1)

Input always returns a data type of string

The in keyword allows a simple search to be preformed.


in returns a Boolean result on if the searched text is
contained in a string.

Prof:Mouna HALIMA Output:


message = input("What is your name?")
print("Eric" in message) What is your name? Eric
True
14

INPUT Function – Exercise 3


print("Please enter five grades. One at a time")
grade1=input("Grade 1:")
grade2=input("Grade 2:")
grade3=input("Grade 3:")
grade4=input("Grade 4:")
grade5=input("Grade 5:")
sum_grades=int(grade1)+int(grade2)+int(grade3)+int(grad
print(sum_grades)

Output:
Please enter five grades. One at a time
Grade 1:10 To cast a data type – use
Grade 2:12 the specific Type keyword (
Prof:Mouna HALIMA
Grade 3:11
Grade 4:10
Grade 5:7
like int or str) in front of
the variable or data
50
15

Print formatting

print(object(s), separator=separator, end=end,


file=file, flush=flush)
Parameter Description
object(s) Any object, and as many as you like. Will be converted to string
before printed
sep='separat Optional. Specify how to separate the objects, if there is more
or' than one. Default is ''
end='end' Optional. Specify what to print at the end. Default is '\n' (line feed)
file Optional. An object with a write method. Default is sys.stdout

Prof:Mouna HALIMA
flush Optional. A Boolean, specifying if the output is flushed (True) or
buffered (False). Default is False
16

Print formatting – Example 1


print("Please enter five grades. One at a time")
grade1=input("Grade 1:")
grade2=input("Grade 2:")
grade3=input("Grade 3:")
grade4=input("Grade 4:")
grade5=input("Grade 5:")
sum_grades=int(grade1)+int(grade2)+int(grade3)+int(grade4)+
average=sum_grades/5
print("The average is:", str(average) + ".")

Output:
Please enter five grades. One at a time
Grade 1:10
Grade 2:12 comma (,) method combines printable
Prof:Mouna HALIMA
Grade 3:11
Grade 4:10
Grade 5:7
items with a space

The average is: 10.0.


17

PRINT FORMATTING – Example 2

print("Hello", "how are you?", sep=" --- ") Output:


Hello --- how are you

Output:
print("Hello" , "how are you?", sep=" --- ", Hello
end ---
="***")
how are you

print("Hello" , "how are you?", sep="\t", endOutput:


="\n")
Hello how are
print("Stop") you?

Prof:Mouna HALIMA Stop


18

String – Example 1
Ch= P y t h o n
index 0 1 2 3 4 5
1
index -6 -5 -4 -3 -2 -1
2
ch="python" Output:
print(ch[0]) p
print(ch[-1]) n
print(ch[-6]) p
print(ch[1:3]) yt
print(ch[:4]) pyth
print(ch[2:]) thon
print(ch[::2]) pto

Prof:Mouna HALIMA
print(ch[::-1])
print(ch[::-2])
print(ch*2)
nohtyp
nhy
pythonpython
ch[1]='b' TypeError: 'str' object does not support item
19

STRING – TESTS

.isalpha() Returns True if a string is an alphabetical character a-z, A-Z


.isalnum() Returns True if there is at least 1 character and all are
alphabetical or digits
.istitle() Tests to see if the string is title (all words capitalized)
.isdigit() Tests to see if the string is made entire of digits.
.islower()
These check for all uppercase or lowercase characters
.isupper()
.startswith() This method returns True if a string starts with the specified
prefix(string). If not, it returns False.
Prof:Mouna HALIMA
20

String – Example 2
ch ="python"
ch1="343"
ch2="A Cold Stromy Night"
ch3= "WELCOME TO THE JUNGLE" Output:
print (ch.isalpha()) True
print (ch1.isalpha()) False
print (ch.isalnum()) True
print (ch1.isalnum()) True
print (ch2.istitle()) True
print (ch3.istitle()) False
print (ch1.isdigit()) True
print ("3rd".isdigit()) False
print (ch3.isupper()) True

Prof:Mouna HALIMA
print (ch.islower()) True
print ("THIS IS A MESSAGE WITH 214565".isupper())
print (ch.startswith("p"))
True
True
print (ch2.startswith("a")) False
21

STRING – FUNCTIONS
.capitalize(
capitalizes the first character of a string
)
.lower() all characters of a string are made lowercase
.upper() all characters of a string are made uppercase
.swapcase() all characters of a string are made to switch case upper
becomes lower and vice versa
.title() each 'word' separated by a space is capitalized
.find() The find() method returns the index of first occurrence of the
substring (if found). If not found, it returns -1.
.count() The string count() method returns the number of occurrences

Prof:Mouna HALIMA
.replace()
of a substring in the given string.
The replace() method returns a copy of the string where all
occurrences of a substring is replaced with another substring.
22

String – Example 3
Output:
message=input("Please type your name: ").upper()
Please type your name:
print(message)
Alton
print(message.lower()) ALTON
alton
message="introduction to python" Output:
print(message.capitalize()) Introduction to python
print(message.title()) Introduction To Python

message = 'Hello world' Output:


print(message.find('world')) 6
print(message.count('o')) 2
print(message.replace('Hello','Hi'))
Prof:Mouna HALIMA
print (message.swapcase())
Hi world
hELLO WORLD
23

STORING NUMBER

addition +
subtraction -
Multiplication *
Division /
Exponent **
Modulo %

Order: (), **, * or /, + or -


Multiple line

Prof:Mouna HALIMA
total=5+6**2+8\
+6+2
print(total)
total=5+6**2+8+6+2
print(total)
Output:
57
24

Number format

Output:
print('I have %d cats' %6) I have 6 cats
print('I have %3d cats' %6) I have 6 cats
print('I have %03d cats' %6) I have 006 cats
print('I have %f cats' %6) I have 6.000000 cats
print('I have %.2f cats' %6) I have 6.00 cats
print('I have %s cats' %6) I have 6 cats
print('I have {0:d} cats'.format(6))
I have 6 cats
print('I have {0:3d} cats'.format(6))
I have 6 cats
print('I have {0:03d} cats'.format(6))
I have 006 cats
print('I have {0:f} cats'.format(6))
I have 6.000000 cats

Prof:Mouna HALIMA
print('I have {0:.2f} cats'.format(6))
I have 6.00 cats
25

PART 2 – CONDITIONALS
STATEMENTS

Prof:Mouna HALIMA
26

BASIC FORM
<expr> is an expression evaluated in Boolean context

<statement> is a valid Python statement, which must


if <expr>:
be indented.
<statement(s)>
<following_statement(s)>
The colon ( : ) at the end of the if statement is
required.

a=3
b=2
if a > b:print("a is greater than

Prof:Mouna HALIMA If you have only one statement to


execute, you can put it on the same
line as the if statement.
27

BASIC FORM
If <expr> is true, the first suite is executed, and the
if <expr>:
second is skipped.
<statement(s)_1>
else:
If <expr> is false, the first suite is skipped and the
<statement(s)_2>
second is executed.

<expr1> if <conditional_expr> else <expr2>

<conditional_expr> is evaluated first.

If it is true, the expression evaluates


to <expr1>.
Prof:Mouna HALIMA If it is false, the expression evaluates
to <expr2>.
28

BASIC FORM – Example 1

if age <21:
s='minor' age = 12
else: s = 'minor' if age < 21 else 'a
s='adult' print(s)
print(s)

Output:
minor

Prof:Mouna HALIMA
29

BASIC FORM – Example 2


a, b=2, 4
if a > b:
a, b=2, 4
m = a
m=a if a > b else b
else:
print(m)
m = b
print(m)

Output:
4

Prof:Mouna HALIMA
30

Compound if statements
It is possible to use two conditions at the same time using
an and/or
name=input("what is you name? \n")
if name.isalnum() and not (name.isdigit()):
print("The name you entered is", name)
else:
print("Please enter a valid name")

Output:
what is you name?

Prof:Mouna HALIMA
Alton
The name you entered is Alton
31

Comparison Operators
Comparison operators in Python

operator function
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal
!= not equal

Prof:Mouna HALIMA
Note: A single equals sign (=) is the assignment operator.
Attempting to check for equality is a syntax error in Python
32

ELIF – Chained conditionals

if <expr1>:
<statement(s)_1>
elif <expr2>:
<statement(s)_2>
else:
<statement(s)_3>

if x < y:
STATEMENTS_A
elif x > y:

Prof:Mouna HALIMA
STATEMENTS_B
else:
STATEMENTS_C
33

ELIF – Example 1

x=2
y=3
if x<y:
print("The maximum value is", y)Output:
elif x>y: The maximum value is 3
print("The maximum value is", x)
else:
print(y,"is equal to", x)

Prof:Mouna HALIMA
34

ELIF – Example 2

x=2
if 0<x<10:
print(x, "is a positive digit")
Output:
elif x<-1:
2 is a positive digit
print(x, "is a negative digit")
else:
print(x, " is null")

Prof:Mouna HALIMA
35

Nested Conditionals
Sometimes a program might need to test a condition and a
sub condition based on the answer the first decision.

num1=float(input("Pick a number:"))
num2=float(input("Pick another number:"))
if num1<=num2:
if num1 == num2:
print("equal") Output:
Pick a number:12
else:
Pick another number:20
print("not equal") not equal
elif num1>num2:
print("greater")
Prof:Mouna HALIMA
else:
print("less")
36

exercise
Write a program that begins by reading a letter grade from the user
Then your
program should compute and display the equivalent number of grad
points. Ensure that your program
A
generates
4
an appropriate error
message if the user enters anA-invalid letter
3.7 grade.
B+ 3.3
B 3
B- 2.7
C+ 2.3
C 2

Prof:Mouna HALIMA C-
D+
D
1.7
1.3
1
F 0
37

Exercise - Solution
x=input('Enter a letter grade')
if x in ['A','A+','A-','B+','B-','C','C+','C-','D+','D-
','F']:
if x=='A':
g=4
elif x=='A-':
g=3.7
elif x=='B+':
g=3.3
elif x=='B':
g = 3
elif x=='B-':
g = 2.7
elif x=='C+':
g = 2.3
elif x=='C':
g = 2
elif x=='C-':
g = 1.7
elif x=='D+':
g = 1.3
elif x=='D':

Prof:Mouna HALIMA
g = 1
else:
g = 0
print(g)
else:
print("Enter a correct letter")
38

PART 3 – LOOP
STATEMENTS

Prof:Mouna HALIMA
39

FOR LOOP – Basic form

For loops are traditionally used when you have a block of code which
you want to repeat a fixed number of times.

for iterating_var in sequence:


statements(s)

Prof:Mouna HALIMA
40

FOR LOOP – Examples


Output:
Current Letter : P
for letter in 'Python': Current Letter : y
print ('Current Letter :', letter)
Current Letter : t
Current Letter : h
Current Letter : o
sta end Current Letter : n
rt sta
for x in range(1, 3): Output rt
print ("We're on time", x) We're on time 1
We're on time 2 end-1
If you need to start counting from 1
you can specify numbers to count
to and from
for steps in range(4): Output:

Prof:Mouna HALIMA
print(steps) 0
1
2
Counting starts at zero in for loops
3
41

FOR LOOP - Examples

sta end Step(>


rt 0) Output:
1
for steps in range(1,10,2): 3
print(steps) 5
7
9

You can also tell the loop to skip values by

Prof:Mouna HALIMA
specifying a step
42

FOR LOOP - Examples


Output:
1
for steps in [1,2,3,4,5]: 2
print(steps) 3
4
5

This requires using [ ] brackets instead of ( ) and you don’t use the
“range” keyword
Output:
red
for steps in ['red','blue','green','black',8]:
blue
print (steps) green

Prof:Mouna HALIMA black


8
43

Else in For loop

The else keyword in a for loop specifies a block of code to be executed


when the loop is finished.

Output:
0
for x in range(6):
1
print(x) 2
else: 3
print("Finally finished!") 4
5
Finally finished!

Prof:Mouna HALIMA
44

Nested For loop


A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer
loop"

Output:
0
for x in range(2): 1
2
for y in range(3):
0
print(y) 1
2

Prof:Mouna HALIMA
45

The break/continue Statements

• With the break statement we can stop the loop before it has looped
through all the items
• With the continue statement we can stop the current iteration of the loop,
and continue with the next
for x in range(5):
for x in range(5):
if x==3:
if x==3:
continue
break
print(x)
print(x)

Output:
Output:
Prof:Mouna HALIMA
0
1
2
0
1
2
4
46

The PASS Statement

• the pass statement allows you to handle the condition without the loop
being impacted in any way; all of the code will continue to be read unless a
break or other statement occurs.
• the pass statement will be within the block of code under the loop
statement, typically after a conditional if statement.
Output:
for x in range(5): 0
if x==3: 1
pass 2
print(x) 3
4

Prof:Mouna HALIMA
47

FOR LOOP – Exercise

Write a Python program to construct the following pattern, using a nested


for loop.

*
**
***
****
*****
****
***
**
* Prof:Mouna HALIMA
48

FOR LOOP – Exercise -


solution

n=5 Output:
for i in range (n): *
for j in range (i): **
print('* ',end="") ***
****
print("")
*****
for i in range(n,0,-1): ****
for j in range(i): ***
print('* ', end="") **
print("") *

Prof:Mouna HALIMA
while Loop – Basic form
A while loop statement in Python programming language repeatedly
executes a target statement as long as a given condition is true.

while
expression:

statement(s)

Prof:Mouna HALIMA
Incrementing/ decrementing
Variables
• A While loop can be controlled by a variable called a counter variable.

• A variable can be increment or decremented as a loops run to set a


condition to stop a loop.

• For example using: while x < 10:


x is the counter variable we can increment by one each loop until it reaches 10
andIncrease
the whilethe
condition
value of becomes
a variable false decrease the value of a variable
# initialize # initialize
x=0 x=0
# increment # decrement
x=x+1 x=x-1

Prof:Mouna HALIMA
There is also a shorthand way which is
normally used
x += 1
There is also a shorthand way which is
normally used
x -= 1
while Loop – Examples
Output:
count = 0
The count is: 0
while (count < 5): The count is: 1
print ('The count is:', count)
The count is: 2
count = count + 1 The count is: 3
The count is: 4

name=""
while True:
name=input("Enter a one-word name") Output:
if name.isalpha(): Enter a one-word
print("Good to see you", name.title())
nameAhmed
break Good to see you Ahmed
else:
Prof:Mouna HALIMA
print("sorry, enter a one-word letters only")
while True: is known as the infinity loop
The break statement is critical. Otherwise this is an endless loop- a common logic error when
The break/continue/pass
statements
i = 0 i = 0 i = 0
while i < 6: while i < 6: while i < 6:
i = i+1 i=i+1 i=i+1
if i == 3: if i == 3: if i == 3:
break continue pass
print(i) print(i) print(i)

Output:
Output: 1
Output: 1 2
1 2 3

Prof:Mouna HALIMA
2 4
5
6
4
5
6
Using else Statement with While Loops

If the else statement is used with a while loop, the else statement is
executed when the condition becomes false.

count = 0 Output:
while count < 5: 0 is less than 5
print (count, " is less than 5")1 is less than 5
count+=1 2 is less than 5
3 is less than 5
else:
4 is less than 5
print (count, " is not less than 55")
is not less than 5

Prof:Mouna HALIMA
Exercise

Write a python program to check given number is prime or not

number=int(input("Enter a number"))
counter=2
nb=0
while int(counter<number/2):
if (number%counter==0):
nb+=1
break
counter+=1
if (nb==0):

Prof:Mouna HALIMA
else:
print("it is a prime number")

print("it is not a prime number")

You might also like