You are on page 1of 38

4PPO

PYTHON
PACKAGING

Chapter 1. Python notions recap


Summary

• Python presentation
• Python notions recap
• Variables declarations
• Conditions
• Loops
• Functions
WHAT IS PYTHON ?

3
What is python ? Interpreted language.

Syntax close to English.

First version in 1991.

Open source.

4
PYTHON USAGE

MACHINE DATA SCIENCE AUTOMATION SCRIPTING SIMULATION


LEARNING

FINANCE WEB API

5
Python
Installation
At https://www.python.org/downloads/

6
VSCode installation
https://code.visualstudio.com/Download
7
PyCharm installation
https://www.jetbrains.com/pycharm/download/
8
 BASIC PYTHON SYNTAX

9
Language syntax

Language norm is snake_case.

Code block definition use indentation.

Standard indentation is 4 spaces.


Your first python program

1. Create a file named "hello.py" in your editor.

2. Write this inside :  print("Hello, world !")

3. Execute the file by running "python hello.py"

11
SCALAR VARIABLES TYPES
Type​ What it is​ Examples​

int​ Integer number​ -4 | –1 | 0 | 1 | 2 | 42​

float​ Decimal number​ -3.14 | 1.0 | 4.4242​

str​ String (chain of characters​) "Obi-Wan" | 'kenobi'​

bool​ A value that is True or False​ True / False​

NoneType​ No value​ None​

complex​ A complex number​ 3.4j | -2j | 1 + 4j​

12
ARITHMETIC OPERATORS

Operator​ What it does​ Example​


+​ Addition​ 3 + 2 => 5​
-​ Subtraction​ 3 – 2 => 1​
*​ Multiplication​ 3 * 2 => 6​
/​ Division​ 5 / 2 => 2.5​
//​ Integer division​ 5 // 2 => 2​
%​ Modulo  5 % 2 => 1​
**​ Exponentiation​ 3 ** 2 => 9​

13
Container types
Type Usage
list Stores a sequence of objects
tuple Immutable list
set Stores only one occurrence of an object
dict Stores objects by Associating keys to values

Like most languages, indexes starts at 0.

You can get the length / size of a container by using the len() function on it.

14
Container examples
# list creation, multiple object types inside are allowed
my_list = [0, 1, "hello"]

# replace the first value


my_list[0] = "the new first value"

print(my_list) # print the list

my_tuple = ("this", "is", "immutable")

my_tuple[0] = "This will cause an error"

15
Container examples
# dict are used to associate keys to values
my_dict = {
    "France": "Paris",
    "Germany": "Berlin",
    "Spain": "Madrid"
}

# Get the capital of France


print(my_dict["France"])

# this will cause an error


print(my_dict["Japan"])

16
LIST METHODS

Methods can be used on a list like this : my_list.my_method()


Method Action
.append(item) Adds item at the end of the list.
.pop(index) Removes the item at index.
.index(item) Returns the index of the first occurrence of item.
.count(item) Returns the number of occurrences of item.
.remove(item) Removes the first occurrence of item.

17
DICTIONARIES METHODS
Method​ Action​
.clear() Empties the dictionary.
.keys() Returns all the keys.
.values() Returns all the values().
.items() Returns all the key/values couples in tuples.
.pop(key) Removes and returns the value at key.
.get(key, default) Returns the value linked to key or default if there is none.

18
CONDITION SYNTAX

if condition:
    # Code to execute if condition is True​
    #​
elif other_condition:
    # Code to execute if other_condition is True​
    #​
else:
    # Code to execute if condition if False​
    #​

19
COMPARISION OPERATORS
Operator Name Example
== Equal 1 == 1
!= Not equal 1 != 2
< Less than 1<2
> Greater than 2>1
<= Less than or equal 1<= 2
>= Greater than or equal 2 >= 2

20
LOGICAL OPERATORS
- Allows to create complex boolean logic.

Operator Description Example


and Returns true if both are True. True and False => False
or Returns True if at least one is True. True or False => True
not Reverse the boolean value not True => False

21
Condition example

# ask the user to enter its age and read it


x = int(input("Enter a value for x : ").strip())

if x == 10:
    print("x is 10")
elif x < 10:
    print("x is less than 10")
else:
    print("x is greater than 10")

22
LOOP ITERATIONS

Definite : we know before starting how many loops we will do.

Indefinite : when we stop looping depends on a condition.

23
FOR … IN ...
numbers = [1, 2, 4, 8, 16]
Used to iterate over an iterator. for i in numbers:
    print(i)

Here is the iterator is a list. >>> "1"


>>> "2"
>>> "4"
The i variable will take all the values in the list. >>> "8"
>>> "16"

24
FOR … IN RANGE(…)

Returns a generator creating a sequence of integers.


range(start, stop, step)

Parameter Description Default


start Starting integer of the sequence. 0
stop Integer at which the sequence stops (not included). mandatory
step Value to increment. 1

25
FOR … IN RANGE(…)
# Show the squared values of the integers between 0 & 5
for i in range(0, 6):
    squared = i  **  2
    print(f"{i} * {i} = {squared}")

>>> "0 * 0 = 0"


>>> "1 * 1 = 1"
>>> "2 * 2 = 4"
>>> "3 * 3 = 9"
>>> "4 * 4 = 16"
>>> "5 * 5 = 25"

26
WHILE ...
i = 0
while i < 5:
Very useful for indefinite iteration     print(f"{i=}")
    i += 1

Takes a boolean expression as the stop condition. >>> "i=0"


>>> "i=1"
>>> "i=2"
>>> "i=3"
Executes as long as the condition is True.
>>> "i=4"

27
NESTED LOOPS
prefixes = ["I like", "I love"]
suffixes = ["apples", "chocolates"]

for prefix in prefixes:


First loop body.     for suffix in suffixes:
       print(f"{prefix} {suffix}.") Second loop body.

>>> "I like apples."


>>> "I like chocolates."
>>> "I love apples."
>>> "I love chocolates."

28
THE BREAK INSTRUCTION
The break instruction stops the execution of the parent loop.

stop_chars = "hk47-c3po"
phrase = "Hello there, general Kenobi !" >>> "H"
for char in phrase: >>> "e"
    if char in stop_chars: >>> "l"
      break >>> "l"
    print(char)

29
THE CONTINUE INSTRUCTION
Skip the remaining instructions and go to the next iteration.

users = ["Alice", "Bob", "Bill", "Karim"]


for (index, user) in enumerate(users):
    if index % 2 == 0:
        # skips the users with an id
        # that is a multiple of 2
        continue
    print(f"User with {index=} is {user}")

>>> "User with index=1 is Bob"


>>> "User with index=3 is Karim"

30
FUNCTION CREATION

• Start of a function is defined using the def keyword.

• Functions can optionally return values using the return keyword.

def function_name(arg1, arg2, ..., argn):


    # function code
    # optionally return one or more values.
    return value1, value2, ...

31
FUNCTION CALL
• Functions are called using their name and a series of given
parameters :

return_value = function_name(param1, param2, ..., param3=value3)

• Difference with methods is that methods are called directly on an


object :
return_value = object.method_name(param1, param2, ..., param3=value3)

32
FUNCTIONS EXAMPLES

def display_player_infos(name, username, player_class, level):


    print(f"{name} plays a {player_class} level {level} called {username}.")

display_player_infos("Henri", "Obi-Wan", "Jedi", 24)


display_player_infos("Patrick", "Vador", "Jedi", 44)
display_player_infos("Bob", "Palpatine", "Sith", 48)

>>> "Henri plays a Jedi level 24 called Obi-Wan."


>>> "Patrick plays a Jedi level 44 called Vador."
>>> "Bob plays a Sith level 48 called Palpatine."

33
DEFAULT PARAMETERS
• Parameters can have default values.
• You can mix parameters with a default value and no default value.
• Parameters with default values must be defined at the end.

def say_hello(name="world"):
    print(f"Hello, {name} !")

say_hello() >>> "Hello, world !"


say_hello("ecole-it") >>> "Hello, ecole-it !"
say_hello(name="ecole-it") >>> "Hello, ecole-it !"

34
Variables can have types
hints.

PEP 484: Type Highly advised to use.


hints

Duck typing still possible.

35
FUNCTION WITH TYPE HINT

BANNED_USERS = ["Alick", "Patrick"]

def is_user_banned(user: str) -> bool:


    return user in BANNED_USERS

user = "Bob"
banned: bool = is_user_banned(user)

36
Conclusion
• Python is an interpreted language.
• Variable can have dynamic types.
• Python uses indentation instead of brackets.
• The language has many common features of
programming languages.
• Functions are defined with the def keyword.

37
Let’s practice !

38

You might also like