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

24-RTSA-01 Introduction to Python

Python for beginners

Uploaded by

ktopu67
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

24-RTSA-01 Introduction to Python

Python for beginners

Uploaded by

ktopu67
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Real-Time Systems and

programming for Automation M


1. Introduction to Python
Notice
The course material includes material taken from Prof. Chesani and
Prof. Martini courses (with their consent) which have been edited to suit
the needs of this course.
The slides are authorized for personal use only.
Any other use, redistribution, and any for profit sale of the slides (in any
form) requires the consent of the copyright owners.

Real-Time Systems and programming for Automation M


1.2 Torroni and Galassi ©2024
Computations, Machines, Languages
• A computation is
• The manipulation of symbols from an alphabet…
• …through an elementary finite set of operations

• A programming language describes the manipulation process


• Symbols that will be manipulated
• Which are the elementary operation
• How to combine elementary operations
• We call machine an agent that performs a computation

Real-Time Systems and programming for Automation M


1.3 Torroni and Galassi ©2024
Python Machines and Interpreter
• Python is a general purpose programming language.
• Manipulation processes described in Python can be executed by a Python
machine

• More in detail:
• First, the Python source code is read by a Python interpreter
o Checks if the code is syntactically correct
o Converts it into ByteCode
• Then, the Python Virtual Machine (PVM) execute the code

Real-Time Systems and programming for Automation M


1.4 Torroni and Galassi ©2024
Peculiarities
• High Level Language
• Flexible and large set of data types
• No direct connection between Python data and machine representation

• Every instruction must be terminated by a newline or, alternatively by a ;


• Don't put spaces in front of an instruction: they have a specific meaning!!!
• The language is case-sensitive: print is different from Print
• Comments on a single line: starts with #
• Comments on multiple lines: start and ends with triple single apex ''', or
triple double apex """
• a useful function: print(…) takes in input an expression and prints it out

• Everything is an object

Real-Time Systems and programming for Automation M


1.5 Torroni and Galassi ©2024
Types
• What is a Data Type?
• a set of effectively presented values
• a set of effective, elementary operations on those values

• For every new type we will create/define/introduce, we will have:


• the set of values
• how those values are represented
• the set of operations related to the type
• the name of the type

Real-Time Systems and programming for Automation M


1.6 Torroni and Galassi ©2024
Primitive Types
• integers: 3, 5, -12 …
• they have arbitrary dimension (limited by your available memory)
• floats: 3.14 , 5. , 2.76e3
• complex numbers: 3+4j , 2-6j
• booleans: True, False, but also values 1 and 0
• strings: 'mickey' , "minnie"
• No char…!!! A char is a string of one character.

Real-Time Systems and programming for Automation M


1.7 Torroni and Galassi ©2024
Variables and Values
• Variables have a name
• It must start with any letter or the _ (no digits!)
• Can contain digit, letters and _

• Values have a type


• The type decides which are the allowed operations for the value

• Variables are assigned to values through the assignment operator =


a = 3.0
b = 4.0
c = a * b

Real-Time Systems and programming for Automation M


1.8 Torroni and Galassi ©2024
Dynamic Binding
• A variable name is simply an identifier of an object.
• Variables do not have a type

• Dynamic binding: methods and attributes are solved at execution time

• A variable can refer to a value of type x, and later can refer to an value of
type y

• Each type has a different set of permitted operations


• the allowed operations are checked only at execution time
• no checks at compile time
• If the operation is not permitted on that type => error!

Real-Time Systems and programming for Automation M


1.9 Torroni and Galassi ©2024
Dynamic Binding - Examples
# Ex. 1: # Ex. 3:
a = 3 a = 3
a = a – 2 a = 'goofey’
print(a) print(a)

# Ex. 2:
a = 'goofey'
a = a – 2
print(a)

Real-Time Systems and programming for Automation M


1.10 Torroni and Galassi ©2024
Constants
• There are no constants in Python

• If the developer wants to specify that some variables contains a constant,


the convention is to name the variable using only capital letters

MAX = 10 # constant
min = 0 # variable

Real-Time Systems and programming for Automation M


1.11 Torroni and Galassi ©2024
Assignment
• The operator = bears the usual assignment meaning
• The semantics, however, is slightly different:
<name> = <expression>

1) Evaluate <expression>, determining a value


2) Check if name is already present
3) If not present, create it
4) Bind value to name

Real-Time Systems and programming for Automation M


1.12 Torroni and Galassi ©2024
Associations and Internal State
• The assignment operator creates a link between a name and a value.
• Such link is referred with the term association.

• The list of associations is referred as the internal state of the Python


machine
• the internal state evolves as an ordered list: new names are simply
added at the end of the list
• any assignment of an existing name will affect the association related to
that name

name1 value1

name2 value2

name3 value3

Real-Time Systems and programming for Automation M


1.13 Torroni and Galassi ©2024
Expressions and Commands
• An expression is a phrase in the language of which we are interested in its
value
42
56//8

• A command is a phrase in the language which we use to modify the internal


state

A=10

Real-Time Systems and programming for Automation M


1.14 Torroni and Galassi ©2024
Input and Output
• print() is a command
• It transfers the value of its argument(s) to the external state
a=10
b=a+20
print(a+b)

• input() is an expression
• It is used to transfer values from the external to the internal state
• input() always gives values of type str
c=input() # assignment: d is the name, input() is the expression

Real-Time Systems and programming for Automation M


1.15 Torroni and Galassi ©2024
Expressions
• We may group several operations in an expression

• Expressions are
• completely evaluated
• from left to right
• respecting the precedence rules of math
• parentheses may be used to force grouping

• However, boolean expressions have a lazy evaluation: as soon as it is


possible to determine the final result, the evaluation is stopped
• (true) and (false) and (int(input())
(true) or (int(input())
the input() method will not be executed

Real-Time Systems and programming for Automation M


1.16 Torroni and Galassi ©2024
Data Types: int
• The type of integer values:
• values : the signed integers from math
• presented : like in math
• elementary operations : addition (+), subtraction (–), multiplication (*),
integer division (//), integer modulo (%), exponentiation (**)
• the name of the type : int

Real-Time Systems and programming for Automation M


1.17 Torroni and Galassi ©2024
Data Types: str
• The type of the strings:
• values : non-modifiable finite sequences of ordered alpha-numeric
characters (from a fixed alphabet)
• presented : enclosed in quotes ('), or (") or even (‘‘’)
'Hello', "World" , '''professor'''
• elementary operations : concatenation (+), repetition (*), length
(len(…)), subscription and slicing ( […] )
• name : str

• Strings are immutable!


• We can not change a specific character of a string!

Real-Time Systems and programming for Automation M


1.18 Torroni and Galassi ©2024
str Operations
• Length: number of its characters
print(len('pine')) # answer: 4

• Subscription/Slicing: select a substring based on indexes [start:end]


• starting character is included, ending character is not included
• indexes start at zero (hence, e.g. the third element is at index 2)
• negative indexes are counted from the end
print('pine'[1]) print('pine'[1:3])
print('pine'[-1]) print('pine'[:2])
print('pine'[len('pine')-1]) print('pine'[2:])
print('pine'[len('pine')]) print('pine'[1:-1])

• Concatenation: aggregate multiple strings


print('pine'+'apple') # answer: 'pineapple'

• Repetition: aggregate multiple strings


print('pine'*3) # answer: 'pinepinepine'

Real-Time Systems and programming for Automation M


1.19 Torroni and Galassi ©2024
Overloading
• We can use the same symbol for different operations
• The symbol + means addition with int and concatenation with str

• The machine disambiguates depending on the context


• Depending on the types involved in the operation

• We say that the symbol is overloaded

Real-Time Systems and programming for Automation M


1.20 Torroni and Galassi ©2024
Data Types: float
• The type of rational values:
• values : a subset of the rational number
• presented : like in math; also exponentional notation
3.1415, -1.2, 3.4567e3, 3456.7
• elementary operations : addition (+), subtraction (-), multiplication (*),
division (/), exponentiation (**)
• name: float

Real-Time Systems and programming for Automation M


1.21 Torroni and Galassi ©2024
Predefined Functions
• Some functions are predefined
within the language
• https://docs.python.org/3/librar
y/functions.html

• type() provides the type of a


value

Real-Time Systems and programming for Automation M


1.22 Torroni and Galassi ©2024
Data Conversion
• We can use predefined functions to convert values in different types

• The name of the functions is the name of the types


float(3) # result: 3.0
int(3.5) # result: 3
str(3.14) # result: '3.14’
int('3.14') # result: 3.14
int('bologna') # result: ERROR!

• Important to convert numbers given as input


• The result of input() is always a str

Real-Time Systems and programming for Automation M


1.23 Torroni and Galassi ©2024
Mixed Expressions
• In some cases, it is possible to mix different types
• The Python machine will apply the necessary transformations of types so
that the expression makes sense

• For example, mixing int and float is ok


• The following expressions are all equivalent
7/3
7.0/3
7.0/3.0
float(7)/float(3)

Real-Time Systems and programming for Automation M


1.24 Torroni and Galassi ©2024
Data Types: bool
• The type of the truth values:
• values : only two, true and false
• presented : True, False
• elementary operations : and (logical conjunction), or (logical
disjunction), not (negation)
o They are defined by the usual truth tables
• name : bool

Real-Time Systems and programming for Automation M


1.25 Torroni and Galassi ©2024
Data Types: NoneType
• The type of None:
• values : a single element
• presented : None
• elementary operations : no operations
• name : NoneType (it cannot be used as a converter)

• Used when functions do not have a return type


• (we will talk more about this)

Real-Time Systems and programming for Automation M


1.26 Torroni and Galassi ©2024
Arithmetic Operators

Real-Time Systems and programming for Automation M


1.27 Torroni and Galassi ©2024
Bitwise Operators

Real-Time Systems and programming for Automation M


1.28 Torroni and Galassi ©2024
Assignments Operators

Real-Time Systems and programming for Automation M


1.29 Torroni and Galassi ©2024
Comparison and Logical Operators

Real-Time Systems and programming for Automation M


1.30 Torroni and Galassi ©2024
Identity and Membership Operators

Real-Time Systems and programming for Automation M


1.31 Torroni and Galassi ©2024
Priority between Operators
Note: computation is always
performed left to right, when
possible

Real-Time Systems and programming for Automation M


1.32 Torroni and Galassi ©2024
Priority between Operators
Note: computation is always
performed left to right, when
possible

Real-Time Systems and programming for Automation M


1.33 Torroni and Galassi ©2024
Objects and Identity
• An object is a specific value enveloped in an identity
• This identity is unique during a run of the Python machine
• In Python, any value is an object (even int values)
• We may have distinct objects (with different identities) and same value

• Even if two cars are completely identical, they remain two separate cars
• They have the same Data Type (car)
• They have the same value (the brand and model of the car)
• But they are two different objects, and therefore have two different
identities (the plates are different)
• The comparison operator is can be used to test if two objects have the
same identity (and therefore are the same object)
• For now, identity doesn’t seem very important, we will see it actually is

Real-Time Systems and programming for Automation M


1.34 Torroni and Galassi ©2024
Methods
• Methods are functions that can be invoked on (from) an object
• They simulate the object to do something (e.g., to return a value)
• Can be invoked with the . notation: object.method()
• Examples with strings:
• str.capitalize(): return a copy of the string with its first character
capitalized and the rest lowercased.
print("anDREa".capitalize()) # prints "Andrea"

• str.isalpha(): return True if all characters in the string are


alphabetic and there is at least one character, False otherwise.
• str.isdigit(): return True if all characters in the string are digits
and there is at least one character, False otherwise.
• Example with floats:
• fl.is_integer(): return True if the float instance is finite with
integral value, and False otherwise:

Real-Time Systems and programming for Automation M


1.35 Torroni and Galassi ©2024
Instruction Sequence
• Two ways:
• Each instruction is on a different line, the line can end with ;
• Multiple instructions are on the same line, separated by ;

print('Hello') # instr1 print('Hello'); print('World')


print('World') # instr2 a = input('Type: ') # instr3
a = input('Type: ') # instr3
print('Hello'); # instr4
print('World'); # instr5
a = a**a # instr6

Real-Time Systems and programming for Automation M


1.36 Torroni and Galassi ©2024
Selection: if-elif-else
• Different ways are available: • Where expression is a Boolean
• if expression1: (bool) expression, that can/can
instruction_block1 not be enclosed in round brackets

• if expression1: • Note the use of :


instruction_block1 • Note the use of indentation in the
else: nested instruction blocks
instruction_block2

• If the instruction block can contain


• if expression1: a single line of expressions, they
instruction_block1 can be on the same line of
elif expression2: if/elif/else
instruction_block2
else:
instruction_block3 • if exp: instruction1
else: instruction2

Real-Time Systems and programming for Automation M


1.37 Torroni and Galassi ©2024
Instruction Block
• Used to «structure» the execution with compound commands (e.g., if)

• Blocks in Python:
• a sequence of lines
• each line with a single command
• all of them at the same indentation
o same distance from the left margin
o other programming languages use parenthesis {,}.

• No local scopes, unless for functions or classes

Real-Time Systems and programming for Automation M


1.38 Torroni and Galassi ©2024
Selection: if-elif-else - Example
a = int(input('Number: '))

if a>10: print('Greater than 10!')

if a>5: print('Greater than 5!')


else: print('Less than 5!')

if a>100:
print('this is block aaa')
print('second instruction of block aaa')
print('third instruction of block aaa')
else:
print('this is block bbb')
print('second instruction of block bbb')
print('third instruction of block bbb')
print('fourth instruction of block bbb')

Real-Time Systems and programming for Automation M


1.39 Torroni and Galassi ©2024
Iteration: for
• The construct for iterate over a sequence of any object type
• for value in sequence: single_instruction
• for value in sequence:
instruction_block
• value is a variable that can be referenced into the instructions
• sequence is a sequence of objects of any type
• Objects are typically separated by commas and enclosed between
round brackets
• Can be a str: it is a sequence of characters!
for i in (1,2,3): print('Value: ', i)

for i in 4,5,6: print('Value: ', i)

for i in 'a', 'b', 'ciao', 3+4j, 5.6e-12:


print('Value: ', i)

for c in "ciao": print(c)

Real-Time Systems and programming for Automation M


1.40 Torroni and Galassi ©2024
range()
• The range() function allows to easily create numerical sequences
• range(start, stop, step=1)
returns the sequence of integers starting from start to stop-1, with a
step; if not specified, the step is by default equal to 1
• range(stop)
returns the sequence of integers starting from 0 to stop-1

for i in range(3):
print('Value: ', i)

for i in range(0,10,2):
print('Value: ', i)

• Remember: stop-1, not stop !

Real-Time Systems and programming for Automation M


1.41 Torroni and Galassi ©2024
Use of _
for value in sequence:
instruction_block

• Sometimes the value is not used inside the instruction_block


sum = 0
for i in range(5):
value = int(input('Insert value: '))
sum = sum + value
print(sum)
• In this cases, there is the convention of using the name _
• _ is a valid variable name, it is used to signal that its value doesn’t matter
• The use of _ as a standard variable name is strongly discouraged
sum = 0
for _ in range(5):
value = int(input('Insert value: '))
sum = sum + value
print(sum)

Real-Time Systems and programming for Automation M


1.42 Torroni and Galassi ©2024
Iteration: while
• Iterate until a logical expression is evaluated as true.
• while expression: single_instruction
• while expression:
instruction_block

• expression is logical expression, i.e. something that can be


evaluated to True/False

• Possible to combine with an else branch, executed when the


expression is evaluated to False
while expression:
instruction_block1
else:
instruction_block2
• It is used to execute a piece of code at the end of the iteration
Real-Time Systems and programming for Automation M
1.43 Torroni and Galassi ©2024
Modification to iterations

• pass
• its execution does nothing;
• it is used to place a placeholder for something that will be added
later

• break
• it is used to interrupt abruptly the iteration
• it will be executed the first instruction following the iteration

• They make code more difficult to understand and follow


• If possible, avoid their use!

Real-Time Systems and programming for Automation M


1.44 Torroni and Galassi ©2024

You might also like