You are on page 1of 44

Abdelmalek Essaadi University

National School of Applied Sciences of Tangier

Python Programming Language

GCyB-I

Pr. SBAYTRI Youssef


2023-2024
Brief History of Python

 Invented in the Netherlands, early 90s by Guido van


Rossum
 Named after Monty Python
 Open sourced from the beginning
 Considered a scripting language, but is much more
 Scalable, object oriented and functional from the
beginning
 Used by Google from the beginning
 Increasingly popular Guido van Rossum

26/11/2023 2
1- Installation of Python Environement

 Python is pre-installed on most Unix systems, including Linux and MAC OS X

 The pre-installed version may not be the most recent one (2.6.2 and 3.1.1 as of Sept 09)

 Download from http://python.org/download/

 Python comes with a large library of standard modules

 There are several options for an IDE

 Pycharm IDE – https://www.jetbrains.com/pycharm/download/?section=windows.

 Anaconda - https://www.anaconda.com/download.

 Spyder - https://www.spyder-ide.org.

 Jupyter - https://jupyter.org/install.

26/11/2023 3
1- Installation of Python Environement

https://www.python.org/downloads/release/python-
3110/

26/11/2023 4
2- Installation of Pycharm IDE

https://www.jetbrains.com/pycharm/download/?section=wind
ows

26/11/2023 5
2- Installation of Pycharm IDE

Running python script

26/11/2023 6
3- Installation of Anaconda

26/11/2023 7
3- Installation of Anaconda

26/11/2023 8
3-1- First test with Spyder

26/11/2023 9
3-2 First test with Jupyter Notebook

26/11/2023 10

To run python code (Shift + Enter)


4- Variables in Python

In python there’s no program delimiters (start, end, {}, main, ;, …)


No need to declare a variable, it's the first assignment that will take care of it!
The variable takes the type of the assigned value.
Example:
 n=6: creation of a variable which will have the name “n” of type integer.
 x=3.0: creation of a variable which will have the name “x” of type float.
 a=‘s’: creation of a variable which will have the name “a” of type string.
 m=true: creation of a variable which will have the name “m” of type boolean.

26/11/2023 11
4- Operators in Python
Operators Description ^ Bitwise XOR
+, - Addition and Subtraction & Bitwise AND
*, /, % Multiplication, Division and Remainder <<, >> Shifts
** Exponentiation | Bitwise OR
<, <=, >, >=, !=, == Comparisons
~x Bitwise NOT
or Boolean OR

and Boolean AND

not x Boolean NOT

in, not in Membership tests

is, is not Identity tests

lambda Lambda Expression

26/11/2023 12
4- Operators in Python

Operators Description

(expressions, ...) Binding or tuple display

[expressions, ...] List display

{key:datum, ...} Dictionary display

`expressions, ...` String conversion

x.attribute Attribute reference

x[index] Subscription

x[index:index] Slicing

f(arguments, ...) Function call

26/11/2023 13
5- Python Syntaxe

5-1 Decision making statement


 In Python, there are three forms of the if...else statement:
• if statement

• if...else statement

• if...elif...else statement

In python, input values


are string by default

26/11/2023 14
5-2 Loops
 Loops makes an execution of a program chunk iterative.
 Two types of loops in Python:
 for loop
 while loop
 When our iterations are countable , we often use for loop.
 When our iterations are uncountable, we often use while loop.

26/11/2023 15
5-2 Loops

A- while loop demonstration

26/11/2023 16
5-2 Loops

B- for loop demonstration

26/11/2023 17
5-2 Loops

The break statement is used to break out of a loop statement (stop the execution of a
looping statement).

 Even if the loop condition has not become false

 if you break out of a for or while loop, any loop else block is not executed.
Example:

26/11/2023 18
5-2 Loops

The continue statement is used to:

 Skip the rest of the statements in the current loop cycle.

 Continue to the next iteration of the loop.

26/11/2023 19
6- Data structures
 Data structures are used to store a collection of related data.

 There are three main data structures in Python:

 Lists, Tuples, Sets and Dictionaries

Built-In Data
Structure

Lists Tuples Sets Dictionaries

26/11/2023 20
6-1 Lists
 An ordered group of items
 Does not need to be the same type
 Could put numbers, strings, Boolean or any other type of data in the same list.
 The list of items should be enclosed in square brackets separated by commas.
 Lists are mutable; We can add, remove items in a list.
 Example: fruit_list = ['apple', 'mango', 'banana’]
 We can access members of the list by using their position (fruit_list[0]).
 Two-dimensional list: a list that contains other lists as its elements
 Example:
 Matrix=[[1,2,3],[8,7,9],[4,6,5]]

26/11/2023 21
6-1 Lists
 List Methods and Useful Built-in Functions

Method Description
Append(item) used to add items to a list – item is appended to the end of the existing list
Index(item) used to determine where an item is located in a list, Returns the index of the first
element in the list containing item

insert(index, item) used to insert item at position index in the list


Sort() used to sort the elements of the list in ascending order
Remove(item) removes the first occurrence of item in the list
Reverse() reverses the order of the elements in the list

Del removes an element from a specific index in a list

Min/max(list) built-in functions that returns the item that has the lowest /highest value in a list

26/11/2023 22
6-1 Lists
A- Uni-dimension list

26/11/2023 23
6-1 Lists

26/11/2023 24
6-1 Lists
A- Lists indexing

B- Lists Slicing

26/11/2023 25
6-1 Lists
A- Multi-dimension list

26/11/2023 26
6-2 Tuples

 Tuples are defined by specifying items separated by commas within a pair of parentheses.
 Tuples are similar to lists except that they are immutable (Once it is created it cannot be
changed).
 Tuples support operations as lists
• Subscript indexing for retrieving elements
• Methods such as index
• Built in functions such as len, min, max
• Slicing expressions
 Tuples do not support the methods: Append,Remove, Insert, Reverse, sort.

26/11/2023 27
6-2 Tuples

Example: fruit_tuple = ('apple', 'mango', 'banana’)

26/11/2023 28
6-4 Sets

 A set is an unordered collection of elements where each element must be unique ((no
duplicates allowed)
).
 Attempts to add duplicate elements are ignored.
 Creating a set:
mySet = set(['a', 'b', 'c', 'd’])
 Or:
myList = [1, 2, 3, 1, 2, 3]
mySet2 = set(myList)
 Note that in the second example, the set would consist of the elements {1, 2, 3}

26/11/2023 29
6-4 Sets
 List of set methods
 s=set([7,9,10,'A',4]) ; t=set([1,2,3]) ; c=set([9,10])

Method Description Example


s.add(item) add items to the set s.Add(100)  {4, 100, 7, 9, 10, 'A'}
s.update(t) return set s with elements added from set t s.Update(t) {1, 2, 3, 4, 100, 7, 9, 10, 'A'}
s.remove(item)/s.discard(item) Remove the given item from the set s.remove(100) {1, 2, 3, 4, 7, 9, 10, 'A'}

s.pop() remove and return an arbitrary element from s s.Pop() A

s.clear() Remove all elements of the set


len(s) number of elements in set s (cardinality) len(s)  5
s.issubset(t) c.issubset(s)  True
test whether every element in s is in t
s.issuperset(t) test whether every element in t is in s s.issuperset(c)  True

s.union(t) new set with elements from both s and t s.union(c)  {'A', 4, 7, 9, 10}

s.intersection(t) new set with elements common to s and t s. difference(c)  {9, 10}

s.difference(t) new set with elements in s but not in t s.difference(c)  {'A', 4, 7}

s.copy() new set with a shallow copy of s K=s.copy() k={'A', 4, 7, 9, 10}

26/11/2023 30
6-4 Dictionaries

 Keys are associated with values;


 The key and value pairs are separated by a colon
 Pairs are separated themselves by commas
 all this is enclosed in a pair of curly brackets or braces
 The key must be unique.
 Pairs of keys and values are specified in a dictionary by using the notation:
dict = {key1 : value1, key2 : value2 }.
Example: fruit_dict = {0:'apple’, 1:'mango’, 2:'banana’}

26/11/2023 31
6-4 Dictionaries

26/11/2023 32
6-4 Dictionaries

26/11/2023 33
7- String

 A string is a sequence of characters.


 Strings are amongst the most popular types in Python. We can create them simply by
enclosing characters in quotes. Python treats single quotes the same as double quotes.
 Creating strings is as simple as assigning a value to a variable. For example:
var1 = 'Hello World!'
var2 = "Python Programming"

26/11/2023 34
7-1 Some features of strings

Backward Indexing
Python String indexing

Forward Indexing

26/11/2023 35
7-1 Some features of strings
A- String Slicing
 To slice a string we use indexes
 String[i:j] is the substring that begins with index i and ends with index j ( but j not include)
greeting = ‘hello, world’
greeting[1:3]  'el’
greeting[-3:-1]  ‘rl’
 Omit begin or end to mean 'as far as you can go’
greeting[:4]  ‘hell’
greeting[7:]  ‘world’

26/11/2023 36
7-1 Some features of strings

B- String Special Operators

Assume string variable a = 'Hello' and variable b = 'Python' then:

Operator Description Example


+ Concatenation - Adds values on either side of the operator a + b will give HelloPython

* Repetition - Creates new strings, concatenating multiple copies of the a*2 will give -HelloHello
same string
[] Slice - Gives the character from the given index a[1] will give e

[:] Range Slice - Gives the characters from the given range a[1:4] will give ell

in Membership - Returns true if a character exists in the given string H in a will give 1

not in Membership - Returns true if a character does not exist in the given M not in a will give 1
string

26/11/2023 37
7-2 Strings Methods
Method Description Example
capitalize Capitalizes first letter of string "hello".capitalize()  Hello
strip/lstrip/ rstrip used to remove left and right (left/right) padded spaces in a given string “ hello”.lstrip()  “hello”

Lower / islower convert given string in to lower case. “HELLo”.lower()  hello


Upper / isupper Convert a string to upper case “hello”.upper()  HELLO
title Every first chatacter of word of a given string is converted to title case. “hello world”.title()  Hello World
ljust/rjust add spaces to the left/right side of the given string “hello”.ljust(3)+”*” hello *

zfill fill the zero to a given string “hello”.zfill(8)  000hello

find find a perticular character or string in a given string. "hello".find("l")  2; "hello".find(« e")  1

count number of times character or string appears in a given string. “helllo”.count(“l”)  3

Stratswith/endswith check string start/end with particular string or not "hello".startswith("h")  True; "hello".startswith("h") ==> False

Isdigit/isnumeric/isd check string is digit (number) or not "1A234".isdigit()  False ; "1234".isdigit()  True
ecimal
len get a length of string. len("hello")  5

split Split a string "hel,l,o".split(‘,’)  ['hel', 'l', 'o’] ; "hel l o".split())  ['hel', 'l', 'o’]

index Find the index of a character "hel lo".index("l",3,5)  4 ; "hel lo".index("l")  2


26/11/2023 38
8-Functions

 Functions are reusable pieces of programs.


 They allow us to give a name to a block of statements.
 We can execute then that block of statements by just using that name anywhere in our program
and any number of times.
 In python, functions are defined using the def keyword, followed by an identifier name for the
function, followed by a pair of parentheses which may enclose some names of variables.
Example:
def sayHello():
print('Hello World!’) # A new block
# End of the function
sayHello() # call the function

26/11/2023 39
8-1 Functions parameters
 Parameters are values we supply to the function to perform any task.
 Specified within the pair of parentheses in the function definition, separated by commas.
 When we call the function, we keep the values in the same way and order.
 The names given in the function definition are called parameters.
 The given values in the function call are called arguments.

26/11/2023 40
8-1 Functions parameters
# Demonstrating Function Parameters
def printMax(a, b):
if a > b:
print(a, ‘is maximum’ )
else:
print(b, ‘is maximum’)

printMax(3, 4) # Directly give literal values


x = -5
y = -7
printMax(x, y) # Give variables as arguments

26/11/2023 41
8-2 Local and global variables

 Variable declared inside a function are not related in any way to other variables with the same
names used outside the function
 Variable declarations are local to the function.
Example:

26/11/2023 42
8-2 Local and global variables
Global variables are used for assigning to a variable defined outside the function.
The keyword “global” is used to declare that the variable is global.
It is impossible to assign to a variable defined outside a function without the “global” statement.
We can specify more than one global variables using the same global statement (global x, y, z).
Example:

26/11/2023 43
8-2 The return statement
 The return statement is used to return from a function, i.e. break out of the function.
 Return a value from a function is optional.
 Return statement without a value is equivalent to return None.
 Every function implicitly contains a return None statement (if return doesn’t exist).
Example:

26/11/2023 44

You might also like