0% found this document useful (0 votes)
13 views21 pages

Tema 1 - Introduction Python

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views21 pages

Tema 1 - Introduction Python

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

UNIT 1:

INTRODUCTION TO
PYTHON
Máster Universitario en Mecánica de Fluidos Computacional
LEARNING OUTCOMES
• Describe the syntax of Python
• Employ conditional structures in Python to branch the
behavior of a software
• Employ looping structures in Python to repeat sequences or
blocks of actions
• Define functions in Python to encapsulate and organize code
• Describe the behavior of different types of data structures
• Employ appropriate data structures to create effective software

OPT 2
UPV
ASSUMPTIONS

• You have some working knowledge of any programming


language used in Engineering: MATLAB, C/C++, R, Python,
etc.

• You feel comfortable with some basic programming structures


• Conditionals (If)
• Looping (While, For, etc.)
• Functions
• Object-oriented programming?

• You have some patience and resilience to deal with bugs and
unexpected errors ☺ OPT 3
UPV
VARIABLES, DATA
TYPES AND Basic foundations

OPERATORS
OPT 4
UPV
BASIC DATA TYPES AND VARIABLES

• Variables don't need to be previously x = 3


declared
y = 2.23
• The type of the variable is dynamic
z = "Hello world"
• Basic data types
w = 'Again, hello word'
• Integer numbers (int)
print("This message will be printed on the screen")
• Floating point numbers (float)
print(x)
• Text (str)
• Boolean (bool, True/False) print("The value of y is " + str(y) + " and the
string w contains " + w )
• Some common operators nombre = input("Please, type your name: ")
• We use + to concatenate strings or add
edad = int( input("Please, type your age: " ) )
numbers
• We use the print function to print
messages in the standard output
(console)
• We use input to read information from OPT
the keyboard (str) 5
UPV
ARITHMETIC OPERATORS

Operator Description Example


+ Adds two values a = 1 + 23.4
b = a + 33
- Substracts two values a=5–7
b = a – 11.2
* Multiplies two values a=3*4
b = a * 1.2
/ Floating point division between two values. a = 4/2
Always returns a floating point value b = a/1.3
// Integer division. Always returns an integer a = 9//3
b = a//2
% Division modulus. a=3%2
** Power a value to some given value a = 4 ** 2
b = a**2

OPT 6
UPV
COMPARISONS AND BOOLEAN OPERATORS

Comp Description Examples


ar.
<, > True if the first value is lower/greater than the 3<2 Oper. Description Examples
second, False otherwise 3>2
1<2 and True if both values or expressions are evaluated to 3<2 and 3>5
1>2 True, False otherwise 3<2 and (3%2 ==
a<b 1)
2<3 and 5>3
<=, >= True if the first value is lower/greater than or 3<=2
a and b
equal to the second value, False otherwise 3>=2
2<=2 or True if both values or expressions are evaluated to 3<2 or 3>5
2>=2 True, False otherwise 3<2 or (3%2 == 1)
a<=b 2<3 or 5>3
a or b
== True if both values are equal, False otherwise 3 == 3
4 == 5.2 not True if the expression or value is evaluated to False, not 3>2
a == b False otherwise not 1>2
not a>b
!= True if both values are different, False 3!=3
otherwise 4 != 5.2
a != b

OPT 7
UPV
CONDITIONAL Branching the logic of
your code

STRUCTURES
OPT 8
UPV
CONDITIONAL STRUCTURES
if ... elif ... else

• We use conditional structures when we x = int( input("Introduce a number") )


want to branch the logic of our program
if x > 20 :
• When do I need a conditional structure?
if x % 2 == 1:
• You want to carry out some actions in a
specific condition (If) print("I'm odd")
• You want to carry out different actions print("I am greater than 20")
according to specific conditions (If ... Elif
... Else) elif x > 10 :

• In Python, we can use the if ... elif ... Else print("I am a number between 11 and 20")
structure else :
• We don't use { } for delimiting code x = x**2
blocks. Indentation defines code blocks. print("Before, I was less than or equal to 10,
• We can have nested conditional structures but now I am " + str(x))

OPT 9
UPV
CONDITIONAL STRUCTURES
Match - Case

• From Python 3.1 onwards, they lang = input("What's the programming language you want to
introduced match and case learn? ")

structure match lang:


• Similar to switch case in other case "JavaScript":
programming languages print("You can become a web developer.")
case "Python":
• There is no need for break
print("You can become a Data Scientist")
statement after each case. case "PHP":
• _ represents the default action (no print("You can become a backend developer")
case "Java":
previous matches)
print("You can become a mobile app developer")
case _:
print("The language doesn't matter, what matters is
solving problems.")

OPT 10
UPV
LOOPING Repeating code blocks

STRUCTURES
OPT 11
UPV
LOOPING STRUCTURES
for

• We use looping structures when we want for i in range(0, 10, 2):


to repeat multiple times the same block of
instructions print(i)

• Types of looping:
• Known number of times
• Unknown number of times
• for loops are typically used when we
know beforehand how many times we
want to repeat a block of instructions
• A given number of times (i.e., n)
• For each element in a given data structure
• We can use range to iterate using a
typical for structure found in other
programming languages
• No {} and indentation is a must
OPT 12
UPV
LOOPING STRUCTURES
for

• We can use for to iterate over ítems in a mylist=[1,5,"Hello",3.2]


collection or data structure
for x in mylist:
• It is safer than using índices
print(x)
• Python lists:
mylist.append(3) #Adds 3 to the end of the list
• They are ordered collections (not sorted)
that may have multiple data types mylist[0]="Pepe" #Overrides first element
• They are dynamic print(mylist[0]) #Access first element
• We can access elements form the start (0, print(mylist[1])
1, ..., n-1) and the end (-1, -2, -3, ..., -n).
print(mylist[4])
print(mylist[-1]) #Access last element
del mylist[0] #Delete element
print(mylist)

OPT 13
UPV
LOOPING STRUCTURES
while

• We typically use a while loop when we hidden_password = "1234"


don't know beforehand how many times
we want to repeat a code block password = ""

• It is general, and it can loop similarly to a


while password != hidden_password:
for loop. It subsumes for loops
password=input("Please input a correct password")
• While loops iterate while a certain
condition is met
print("You passed the security control!")

OPT 14
UPV
LOOPING STRUCTURES
while

• We typically use a while loop when we mylist=[1,5,"Hello",3.2]


don't know beforehand how many times
we want to repeat a code block i = 0
while i < len(mylist):
• It is general, and it can loop similarly to a print(mylist[i])
for loop. It subsumes for loops i=i+1
j=0
• While loops iterate while a certain
condition is met
while j < 20:
print(j)
• There is no native do-while
j=j+2

OPT 15
UPV
Create code recipes

FUNCTIONS
OPT 16
UPV
FUNCTIONS
Creating code recipes

• Functions allow us to define code blocks def normalize(value, mu, sigma): #This defines the
that will be used in several parts of the function or code recipe
code. They are code recipes.
#value, mu, and sigma represent the inputs. The
• Functions are: recipe depends on this inputs
• Declared when first defined. It defines and den = value - mu
stores the code récipe
return den/sigma #It returns a value
• Called when needed in action
• Their result typically depends on an input #Up to this point we have just stored normalized, but
• They typically provide one or several never executed it!
outputs as a result of applying the recipe
• Why functions? normalize(3, 1.4, 2) #Now we execute the code recipe
with some specific inputs
• Avoids code repetition → More
maintainable normalize(a,b,c) #I can also call the function using
• Makes the code more readable variables as inputs, or even expressions!
• Allows you to share your code
• Generalizes your code OPT 17
UPV
OTHER DATA Learn more...

STRUCTURES
OPT 18
UPV
TUPLES
Static data structure

• They work like lists, however they are my_tuple = (1,5,"Hello",3.2)


immutable.
for elem in my_tuple :
print(elem)
• Once created, they don't change
print(my_tuple[0])
print(my_tuple[1])
• How do I modify an existing tuple? print(my_tuple[3])
Impossible. Create a new one
print(my_tuple[-1])

• More memory efficient and faster

OPT 19
UPV
DICTIONARIES
Indexed key-value

• For lists, you access elements by user_ages = { '45883251E': 23, '21885251F': 18, '11895
providing an index position, as they are 231A' : 42 }
an ordered collection
user_ages['11111111B'] = 49
• Dictionaries are not ordered (i.e., there is
print(user_ages['21885251F'])
no numerical position).
print('11895231A' in user_ages)
• The information in a dictionary is
accessed by providing a key, that for key in user_ages.keys():
uniquely identifies the value stored value = user_ages[key]
• They are known as key-value structures, print(key, value)
as you need keys to access and store
values
• When do we use dictionaries?
• Fast access to unordered information
• Less memory efficient
• Counting items
• Defining complex data structures (e.g. OPT 20
JSON) UPV
OPT
UPV

THANK YOU!
[email protected]
Andrea Conchado Peiró
Víctor Sánchez Anguix [email protected]

You might also like