=
symbol assigns the value on the right to the variable on the left.In the code cell below, Python assigns a value to a variable called, HDI
and a country in quotes to a variable country_name
.
Note: HDI is an acronym for Human Development Index
HDI = 0.87
country_name = 'Ghana'
REMEMBER: Variable names can only contain letters, number and digits and are case sensitive.
Do you know why the word Ghana is in quotes in the cell above?
print
function to display values:¶print
.print(country_name, 'reported an average annual growth of',HDI, 'in the Human Development Indicator.')
Ghana reported an average annual growth of 0.87 in the Human Development Indicator.
print
automatically puts a single space between items to separate them.Python reports an error if the variable doesn't exist yet
# print(a variable that doesn't exist yet)
print(city_name)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-1-e2c9967b3460> in <module> 1 # print(a variable that doesn't exist yet) ----> 2 print(city_name) NameError: name 'city_name' is not defined
# calculate age with previous variables
months = 12
HDI_monthly = HDI/months
print('Monthly HDI average of', country_name, 'is', HDI_monthly)
Monthly HDI average of Ghana is 0.0725
For instance, if we want to print the index 0 position of the variable course
= Global Studies
.
course = 'Global Studies'
print(course[0])
G
[start:stop]
, where start
is replaced with the index of the first element we want and stop
is replaced with the index of the element just after the last element we want.If we want to print the first 6 character of the variable course
# print the variable course and get only Global
course[0:6]
'Global'
len
to find the length of a string:¶# print length course
len(course)
14
Last tips:
course
and Course
are different variables.# assign variable values with impossible names
flabafe = 'Ghana'
wrt_33_6 = HDI/months
print('Monthly HDI average of', flabafe, 'is', wrt_33_6)
Monthly HDI average of Ghana is 0.0725
EXERCISES - 5 min
position
in the program below? (Try to predict the value without running the python code, then check your prediction):initial = 'Ghana'
position = initial
initial = 'Laos'
IDH
the value = 0.0005
, what happens if you try to get the second digit (e.g. .
) of IDH
via index IDH[1]
?1. ts = m * 60 + s
2. tot_sec = min * 60 + sec
3. total_seconds = minutes * 60 + seconds
city_name = 'Arequipa'
print('city_name[1:3] is', city_name[1:3])
len()
.longest_word = 'pneumonoultramicroscopicsilicovolcanoconiosis'