L02P
L02P
Salem Belgurzi
Topics
Variables
Data Conversions
Variables
Variable: name that represents a value stored in the computer
memory
Used to access and manipulate data stored in memory
A variable references the value it represents
A variable is similar to a
parking space in a parking
garage.
This means that variable is assigned value. i.e., after the assignment,
variable "contains" value.
# C code
x = 5.3; // i l l e g a l
# Python code
x = 17 # x gets int value 17
x = 5.3 # x gets float value 5.3
Variables
You can create a new variable in Python by assigning it a value. You
don’t have to declare variables' types, as in many other programming
languages.
>>> x= 3 # creates x, assigns int
>>> print( x)
3
>>> x = " abc" # re - assigns x a string
>>> print( x)
abc
>>> x = 3.14 # re - assigns x a float
>>> print( x)
3.14
>>> y= 6 # creates y, assigns int
>>> x* y # uses x and y
18.84
Variables
In assignment statement, variable receiving value must be on left
side
and, as, assert, break, class, continue, def ,eslaF ,tpecxe ,esle ,file ,led ,
,ro ,ton ,enoN ,lacolnon ,adbmal ,si ,ni ,tropmi ,fi ,labolg ,morf ,rof ,yllanif
dleiy ,htiw ,elihw ,yrt ,eurT ,nruter ,esiar ,ssap
>>> x = 17
>>> t ype ( x)
<cl ass ’ i nt ’ > • Class is another name for data type.
>>> y = -20.9 • Data type is a classification
>>> t ype ( y) • "What kind of thing is the value this
<cl ass ’ f l oat ’ > variable refers to?"
>>> t ype ( 20)
<cl ass ’ i nt ’ >
>>> t ype ( ’ abc ’ )
<cl ass ’ st r ’ >
Data Types
Three data types we will use in many of our Python programs are:
int: signed integers (whole numbers)
Computations are exact and of unlimited size
Examples: 4, -17, 0
float: signed real numbers (numbers with decimal points) Large
range, but fixed precision
Computations are approximate, not exact Examples: 3.2, -9.0,
3.5e7
str: represents text (a string)
We use it for input and output We’ll see more uses later
Examples: "Hello, World!", ’abc’
These are all immutable. The value cannot be changed.
Reading Input from the Keyboard
Most programs need to read input from the user
Three primary built-in functions that allow you to convert data from
one type to another :
int(item) converts item to an integer
float(item) converts item to a float
str(item) converts item to a string
Conversion Functions– int()
int(): This function is used to convert a value to an integer data type.
num_str = “9”
num_int = int(num_str)
print(num_int) # Output: 9
print(type(num_int)) # Output: <class 'int’>
num_str = “4.15"
num_float = float(num_str)
num_int = 40
num_str = str(num_int)