Professional Documents
Culture Documents
Prof:Mouna HALIMA
2
CHAPTER 1:
INTRODUCTION TO
PYTHON
Prof:Mouna HALIMA
3
Chapter outcomes
• The learning objectives of this course are:
developers.
Prof:Mouna HALIMA
programs.
4
PART 1 – BASIC
CONCEPTS
Prof:Mouna HALIMA
5
what is python?
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:
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
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
Output:
This is a python course
What is your name?
Prof:Mouna HALIMA
=Justin
11
Variable reassignment
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
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
Prof:Mouna HALIMA
flush Optional. A Boolean, specifying if the output is flushed (True) or
buffered (False). Default is False
16
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
Output:
print("Hello" , "how are you?", sep=" --- ", Hello
end ---
="***")
how are you
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
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
STORING NUMBER
addition +
subtraction -
Multiplication *
Division /
Exponent **
Modulo %
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
a=3
b=2
if a > b:print("a is greater than
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.
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
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
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 loops are traditionally used when you have a block of code which
you want to repeat a fixed number of times.
Prof:Mouna HALIMA
40
Prof:Mouna HALIMA
print(steps) 0
1
2
Counting starts at zero in for loops
3
41
Prof:Mouna HALIMA
specifying a step
42
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
Output:
0
for x in range(6):
1
print(x) 2
else: 3
print("Finally finished!") 4
5
Finally finished!
Prof:Mouna HALIMA
44
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
• 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 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
*
**
***
****
*****
****
***
**
* Prof:Mouna HALIMA
48
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.
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
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")