Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

2.basic Data and Operations

This document provides an introduction to basic Python concepts including variables, data types, operations, functions, and conditionals. It begins with an overview of variables and how to assign values to them. It then discusses different data types like integers, floats, strings, and booleans. It covers basic operations that can be performed on numbers and strings. The document introduces functions, how to define them using def, and how to call functions by name and pass parameters. It emphasizes using return to output results from functions. Finally, it discusses conditionals or if/else statements for making decisions based on conditions. It provides examples of checking conditions and executing different code blocks depending on the outcome.

Uploaded by

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

2.basic Data and Operations

This document provides an introduction to basic Python concepts including variables, data types, operations, functions, and conditionals. It begins with an overview of variables and how to assign values to them. It then discusses different data types like integers, floats, strings, and booleans. It covers basic operations that can be performed on numbers and strings. The document introduces functions, how to define them using def, and how to call functions by name and pass parameters. It emphasizes using return to output results from functions. Finally, it discusses conditionals or if/else statements for making decisions based on conditions. It provides examples of checking conditions and executing different code blocks depending on the outcome.

Uploaded by

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

Basic data and

operations.
Variables and conditionals.

Olatz Perez de Viñaspre Garralda


Ander Soraluze Irureta
Help

Python’s documentation:
https://docs.python.org/3/

GOOGLE in general!!!
Talking with the
computer print(“message”)

Print a message
Let’s try it
02-01-Hello_world.py
In short...

● Do not be afraid of trying


● Errors are part of the development:
○ They are useful for learning
● SyntaxError: we wrote something wrong
○ Give a look to parenthesis, quotes,
Tip tabulators,...
Tell the audience about ● NameError: we wrote the name wrong
the problem through a ○ Check documentation for the
story, ideally a person.
correct name of the function
#The following code will print “message”

Secret messages? print(“message”)


#And the following “hello”
You can add comments to your print(“hello”)
code that will not be executed
Strings
They are written between quotes
For example, Python
“Amaia” There is no difference
between simple or
‘Manuel Lardizabal Pasealekua’ double quotes
“Message” == ‘Message’
Be careful! Use the
same for opening and
closing
“Message’ ERROR
There are different data types:

Variables ●

Integer numbers: int
Float numbers: float
● Strings: str
They store the data
● Boolean: True or False
Variable. Previous example
with variables:
message = “Hello world”
print(message)
Variables in Python

● We use the = symbol to assign a value


○ The left side takes the right’s value
○ variable = value
● Name convention, first character lowercase
○ Mandatory, fist character alphabetic (no numeric)
Talking with the
computer name = input(“What’s your name?”)

Read/store a value
Let’s try it
02-02-Hello_name.py
In short...
● Print can print several values
○ print(“Hello”, name)
● Strings can be concatenated
○ message = “Hello” + ” world”

Tip
Tell the audience about Remember...
the problem through a
story, ideally a person.

● print displays the VALUE of a variable


○ print(name)
Operations with numbers

● addition/subtraction: +, -
multiplication/division: *, /
Numbers

● exponent: **
● integer division: //
The value is used/assigned
directly Relational operators

age = 30 ● greater/less: <,<=,>=,>


length = 1.64 ● equal: ==
birth_year = 2020 - age ● not equal: !=
For example, to calculate the
seconds of a leap year
print((365 + 1) * 24 * 60 * 60)
31622400

days = 365
hours = 24
minutes = 60
seconds = 60
leap_year = (days+ 1) * hours * minutes * seconds
print(leap_year)
31622400
Operations with stings

Operands with ● adding strings:


“he” + “llo” → “hello”
strings ● multiplication with strings:
3* “bye” → “byebyebye”
As with numbers, some
Relational operands
operations can be done
(alphabetic order)

● greater/less: <,<=,>=,>
● equal: ==
● not equal: !=
Casting between types
For example, to cast a number into a string
age = 30
age_str = str(age)
And to cast it again to int
age_int = int(age_str)
Different conversions

Casting types ● into string:


str(variable)
To change the type of the ● into int number:
variable int(variable)
● into float number:
float(variable)
Be careful!
You can not concatenate a number to a string

print(name + age) ERROR!


Let’s do some
exercises
First 5 exercises from “Fundamentals exercises”
In short...
● Types can not be mixed when concat
○ print(“Hello” + 30) ERROR

● To make more complex programs, we


need to think step by step: ALGORITHM

Tip
Tell the audience about
the problem through a
story, ideally a person.
Functions
Until now, we used two functions:

● input()
● print()
Function Many “synonyms”:
An independent piece of code ● Procedure or subprogram,
that performs a specific task mainly. Methods are also very
similar
Calls to functions

In Python is very easy to call a


function.

You must know: For example, we want to calculate the


absolute value of a number:
● Name of the function
● Required parameters ● Name: abs
(whatever goes between ● Parameters: original number
parenthesis) ● Result: another number (the
● What it returns absolute value of the original
number)
Functions’ parameters

Too many or very few parameters: Wrong type of parameter:

abs() abs(“a”)
abs(1,-3)
Output:
Output:
TypeError: bad operand type for abs(): 'str'
TypeError: abs() takes exactly one
argument (0 given)
TypeError: abs() takes exactly one
argument (2 given)
Parenthesis are
compulsory!
print(abs)

Output:
<built-in function abs>
def hello(name):

Creating return “Hello” + name

functions
message = hello(“Amaia”)
print(message)

In Python, functions are defined Output:


with the reserved word def
Hello Amaia
Let’s try it
02-03-function_hello.py
Avoid input() and print() inside

● Parameters for input data


● Return for output data

input() and print() to communicate with the user (in general) in


the main program
Return of results (return)

As seen, some functions must return ● We return the result of the


something: function with the reserved
word return.
● factorial, sum_numbers ● Be careful! With the return, the
function ends
But it is not always compulsory: ○ The following code will never
be executed
● hello ● You can use return in any place
○ if, while, for,..
● But the best place uses to be at
the end of the function
Be careful...
● Python is interpreted language
○ It needs to get the function
definitions before it’s call
Let’s try it
02-06-functions_return.py
Let’s do some
more exercises
Repeat the first 5 exercises from “Fundamentals exercises”,
now using functions (exercise 1.6)
Conditionals
Making decisions Get ready to
go out of
home

Till now... Is it
raining
?
We have executed operations in order,
False True
from up to bottom. Everytime the
same will be executed.
Go to work Go to work
But most of the times... walking by bus

We will want to make decisions


depending on something
Arrive at
work
if rain == ‘yes’:
print(“You better go to work by bus”)
if rain == ‘no’:
print(“You better go to work walking”)
Let’s try it
02-07-conditionals-rain.py
They are “almost” equivalent...

if rain == ‘yes’: if rain == ‘yes’:


print(“By bus”) print(“By bus”)
if rain == ‘no’: else:
print(“Walking”) print(“Walking”)
Note
If the two options of the
conditional are
contraries, you can use
the if-else structure.
Let’s try it
02-08-conditionals-rain2.py
Blocks at programming
● When programming, there are if rain == ‘yes’:
blocks that performs a set of
operations
print(“It is raining”)
print(“You better go by bus”)
print(“You will get wet otherwise”))
Blocks in Python else :
print(“It does not rain”)
● The beginning of a block is print(“Walking is a good option”)
represented by “two dots” (:)
● The operations inside the block
must be indented
Be careful!
Indentation must be coherent

Usually, 2 or 4 spaces are used


Assignation vs comparison

Assignation Comparison
● It is used to assign a value to a ● It is used to compare two
variable values (it can be the value of
● A single = is used variables as well)
● For example, ● A double = is used
● For example,
name = “Olatz”
age = 33 if name == “Olatz”:
print(“Kaixo Olatz”)
if name != “Olatz:
print(“What’s your name?”)
Booleans
The result of a comparison will be
a boolean value:
True or False
Let’s try it
02-09-booleans.py
In addition to compare equal (==)
and not equal (!=), it is very common
to compare greater and less than

Comparisons ● Less than: <

with numbers ●
x<0
Less or equal than: <=
x <= 10
As done with strings, we can
● Greater than: >
write conditionals with numbers
x>7
● Greater or equal than: >=
x >= 5
Let’s try it
02-10-booleansNumbers.py
Nested conditionals

A block of ifs can have another block inside

if x > 0:
if x < 10:
print(“It is a number of one digit”)
else:
print(“It has more than one digit”)
else:
print(“It is a negative number”)
Let’s try it
02-11-nestedConditionals.py
Conditionals with many options

You can concatenate many conditions using the elif structure.


The following two pieces of code are identical.

if x > 0: if x > 0:
print("Positive") print("Positive")
else: elif x < 0:
if x < 0: print("Negative")
print("Negative") else:
else: print("Zero")
print("Zero")
Let’s try it
02-12-manyConditionals.py
Want more?
http://www.parentesis.com

You might also like