0% found this document useful (0 votes)
58 views36 pages

Lesson 10 Slides

The document provides an introduction to variables and data types in Python. It discusses key concepts like variables, data types, operators, functions, strings and more. The objectives are to understand typing the first Python instructions, variables, and different data types. It provides examples of using variables, operators, functions like print, format and input, as well as discussing data types like integers, strings and others.

Uploaded by

ka
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)
58 views36 pages

Lesson 10 Slides

The document provides an introduction to variables and data types in Python. It discusses key concepts like variables, data types, operators, functions, strings and more. The objectives are to understand typing the first Python instructions, variables, and different data types. It provides examples of using variables, operators, functions like print, format and input, as well as discussing data types like integers, strings and others.

Uploaded by

ka
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/ 36

COMPUTER SCIENCE

code 30424 a.y. 2018-19

Lesson 10
Variables and data types

SEDIN
IT Education Services Center
2

Objectives of the lesson


• Typing the first instructions in Python
• Understanding variables and the different existing data types
3

Mathematical operators
Symbol Operation Description
+ Addition Adds two numbers
- Subtraction Subtracts two numbers
* Multiplication Multiplies two numbers
Divides two numbers and returns a floating-
/ Division
point number
Floor division (aka Divides two numbers and rounds down to an
//
integer division) integer (*)

% Modulus Divides two integers and returns the


remainder of the division
** Exponentiation Elevates a number to a power

(*) when the result is positive, the decimal part is simply deleted while if the result
is negative it is rounded down to the nearest whole.
4

Mathematical expressions
In mathematical expressions, the operations enclosed in parentheses are
executed first and then the operator with the highest precedence is applied
first:
• Exponentiation
• Multiplication and division
• Addition and subtraction
PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction)

>>> (6 - 3)* (2 + 7) / 3
9.0
Note: numbers in Python are always
>>> 6 - 3 * 2 + 7 / 3
expressed with the Anglo-Saxon notation
2.3333333333333335
5

Order of operations
Operators with the same priority are evaluated from left to right, except
exponentiation, which runs from right to left

Example:
>>>2**3**2
???

The result is 512: first it computes 32=9, then 29=512


6

Formatting numbers
The format function allows number formatting. It has two arguments: the
number to be formatted and the format specifier: format (value, format_spec)
Examples:
>>> print(format(10000/7, '.2f'))
1428.57
>>> print(format(10000/7, ',.2f'))
1,428.57
>>> print(format(10000/7, ',.2%'))
142,857.14%

• .2 indicates that we want to round off the number to the second decimal place
• f specifies that the number that you want to obtain is a floating-point
• the “,” (comma) adds the thousands separator
• the % symbol is used to format in percentage
7

Built-in functions
• These are the “default” functions, existing in Python standard installation
• In this lesson we will see print, format, help, input
• The standard syntax of a function in Python provides the name and
arguments in parentheses, separated by commas when they are more than
one: fname (arg1, arg2, …)
8

print function
Let's start by understanding the syntax of a function and the IDLE color codes
Purple for built-
in functions

Green for
strings

Blue for
output

Red for errors

Use of Function
separators syntax
9

Strings and use of quotation marks


A string in Python can be enclosed in:

• Single quotes: 'goofy' In special cases you can


also use triple single quotes
• Double quotes: "goofy" or triple double quotes

They can be used interchangeably, except where the string contains quotes or
quotation marks, so the other character must be used to delimit it

Examples:
10

Operations on strings
Normally it is not possible to perform operations on strings, even if their
content resembles a number

There are two exceptions:


• the + operator: performs the concatenation
• the * operator: performs the repetition

Example:
>>> print ('Python' * 4)
PythonPythonPythonPython
11

Escape codes
• Escape codes are formed by a backslash (\) and other characters, placed
within a string
• They are not displayed in the output but give specific commands
• E.g.: the code \n is used to wrap text, \t aligns to the next tab, \ alone wraps
the code

>>> print ('One\nTwo\nThree')


One
Two
Three
12

help function
Shows information about a function, a data item, or a form
13

Python standard library


• There are many libraries of functions that allow to expand the potential of
Python
• The standard library is installed together with Python and contains several
useful modules
• To access the functions of a certain module it is necessary to import it. The
import is valid only for the current session
• The functions of the module are called by adding the name of the library

Examples:
14

Variables
This is a fundamental concept in all programming languages:

• A variable is a name that represents a value in the computer's memory


• An assignment statement is used to create a variable and to refer to a
piece of data
• The equal sign (=) is called the assignment operator

Examples:
last_name = 'Snow'
age = 25
15

Variables as argument of functions


• Variables are very useful when used as function arguments
• In this case, the variable name should not be enclosed in quotes, otherwise
it is interpreted as a simple string

Example:
16

Assignment statements
An assignment statement creates a new variable and gives it a value:
>>> surname_professor = 'Wilson'
>>> number_students = 86
>>> g = 9.81

The variable name is always on the left, while on the right there must be the
assigned value

The equal sign (=) is an assignment operator


17

Variable names
Variable names:
• must be short and meaningful
• must start with a letter or the underscore character (_), followed by letters,
numbers or underscores
• cannot contain spaces or special characters, such as @, &, $, €, § etc.
• cannot consist of reserved Python words (keywords), such as True, not, or, return,
while, and, if or function names

It is preferable not to use accented characters

Note: Python is a case-sensitive language, which distinguishes between variable


names made up of lower and upper case characters
18

Reassignment of variables
• Variables can refer to different values during the execution of a program
• When you assign a value to a variable, this refers to the value until a
different value is assigned
• Reassignment is the operation of replacing one value with another

Example:
>>> a = 1
>>> print(a) Assignment
1
>>> a = 2
>>> print(a) Reassignment
2
19

Updating variables
One of the most common forms of reassignment is an update, where the new
value of the variable depends on the previous one

Example:
>>> a = 1
>>> a = a + 1
>>> print(a)
2

Before updating a variable, it is essential to initialize it (that is assign it), as


updating a non-existent variable generates an error
20

Multiple assignment
Python allows multiple assignment of variables (also called unpacking),
which allows acting on multiple variables directly on the same line of code:

>>> a, b, z = 1, 2, 3
>>> print(a)
1
>>> print(b)
2
>>> print(z)
3
21

Data types
• When a given value is assigned to a variable, it is typed, that is, it assumes a
certain type of data depending on the assigned value
• The data type determines the behavior of some operations, while others can
only be performed on values of a specific data type
• To know which type of data a value belongs to, you can use the type
function

Examples: >>> type(1)


<class 'int'>
>>> type('a')
<class 'str'>
22

Basic Python data types

Data type Name Description Examples

Integer int Integer of arbitrary size 112, 0, -158

Real number float Floating-point number 2.14, -159.1234

Boolean bool For true or false values True, False

'SEDIN', 'Python',
String str Used to represent text
'Python3', 'Web 2.0',
23

Reassignment to a different type


After a data of a certain type is assigned to a variable, a data of another type
can be reassigned. Python has dynamic typing

>>> price = 100


>>> type (price)
>>> <class 'int'>
>>> price = 'Depends on the applied discount percentage'
>>> type (price)
>>> <class 'str'>
24

Conversion between data types


It is possible, using some specific functions, to convert the data type:
• int function: converts to an integer
• float function: converts to a floating-point number
• str function: converts to a string

Note that:
• if the conversion is impossible, an error message appears. E.g.: int ('Python')
• int function does not round the fraction part, but chops it off

Example: >>> int(9.9999)


9
25

input function
• The input function asks the user to enter some data (i.e. an input)
• Once the user has typed a value and pressed the Enter key, he reads the
data entered from the keyboard and returns this data to the program as
a string
• It can be used to assign a value to a variable

Example:
26

Conversion from input


If we want the input function to return a data of a different type, we must use a
conversion function

Example:
>>> value = input('Enter the desired value: ')
Enter the desired value: 127
>>> value >>> value = int(input('Enter the desired value: '))
'127' Enter the desired value: 127
>>> value = value + 1 >>> value
Traceback (most recent call last): 127
File "<pyshell#16>", line 1, in <module> >>> value = value + 1
value = value + 1 >>> value
TypeError: must be str, not int 128
27

Shell vs. editor


So far we have worked in the shell, to become familiar with Python. To create
a real program, however, we need to use the editor:

• The shell is useful to start working with Python and to immediately check
the operation of a command

• The editor allows writing a program in Python, that must be saved as a file
to be run
28

Opening the Python editor


From the shell:
• File/New file (to work on a new file) or
• File/Open… (to open an existing file - not to run it)

From Windows Computer:


• Right click/Edit with IDLE/Edit with IDLE 3.7
(to open an existing file - not to run it)
• It does not work with double-click: double-click executes the file in the
Windows shell
29

Writing a program
To write a new program choose
File/New File from the shell menu:

which opens a new editor windows:


30

Saving the program


Once the code is written…

Save the program with the File/Save As command

Extension .py, icon


31

Running the program


If the program is open in the editor, use F5 or the Run/Run Module command
to run it

If it is closed, to reopen it, right click


and choose Edit with IDLE

The output
is shown
in the shell
32

Commenting on the code


Comments are essential for documenting a program, especially when it is
long and complex. They allow you to read it better, to modify it later or for
debugging
At the beginning
(documentation string) or
Two types of comment: between the lines of code

Alongside individual
lines of code
33

Error reporting and debugging


When we work in the shell, Python immediately reports errors in the single
line of code we are executing:

When we write a more complex program in the editor, the error could only
occur when we run the program, preventing it from
running. At that point it is necessary to look for the
bug inside the code: therefore we talk about
debugging
34

Tools to learn with today’s lecture


• Using IDLE (shell and editor)
• Using mathematical operators and performing simple calculations
• Using the print, format, help, input, type functions
• Using the escape code \n
• Understanding and using variables
• Managing quotes and simple operations on strings
• Creating, saving and running a simple program
• Commenting a program
• Understand the concept of bugs and debugging
• Understanding different data types available
• Using conversion functions (str, int, float)
35

Files of the lesson


In the zip file 30424 ENG - 19 - Lesson 10.zip you will find these files:
• 30424 lesson 10 slides.pdf: these slides
• Exercises 30424 lesson 10: exercises on the content of the lesson
36

Book references
Learning Python:
Chapters 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3, 4

Assignment:
Exercises of lesson 10

You might also like