2 Numbers, Strings, Variables, and Assignment Statements
Notebook 2 - Numbers, Strings, Variables, and Assignment Statements¶
You should make your own copy of this notebook by selecting File->Save a copy in Drive from the menu bar above.
Things you'll learn in this lesson:
- The basic data types you can work with in Python
- What are variables and why they are useful
- How to create and assign values to variables in Python
Data Types¶
Python knows about several types of data. Three common ones are:
- numeric types
- integers
- floating point numbers
- character strings
Numeric Types¶
Python supports two main types of numbers
- int, arbitrary size signed integers, like these:
2024
-999999999999
- float, arbitrary precision floating point numbers, like these:
3.14159
3.8 * 10**6
For the most part, you don't need to worry about which type of number to use - Python will take care of that for you. The decimal point tells Python which to use.
Numerical/Arithmetic Operators¶
operator | operation on numbers | operation on strings |
---|
+|addition|concatenation -|subtraction|undefined *|multiplication|repetition //|integer division|undefined /|floating point division|undefined %|modulus (remainder)|undefined **|exponentiation|undefined ()|prioritization|prioritization
Mixing floats and ints results in a float so, for example, 2024 * 3.14
results in a floating point number.
Try entering these expressions in the following cell:
print(5 - 6)
print(8 * 9)
print(6 // 2)
print(6 / 2)
print(5.0 / 2)
print(5 % 2)
print(2 * 10 + 3)
print(2 * (10 + 3))
print(2 ** 4)
Were there any outputs you didn't expect?
print(5 - 6)
print(8 * 9)
print(6 // 2)
print(6 / 2)
print(5.0 / 2)
print(5 % 2)
print(2 * 10 + 3)
print(2 * (10 + 3))
print(2 ** 4)
Strings¶
Rules of the Road¶
- a character string (or just "a string") is a sequence of characters surrounded by quotes
- strings give you the ability to operate on a sequence of characters as a basic unit
- strings are an example of a general category of data types called sequences, which we'll see more of later
- you can use single or double quotes to delineate strings but you must be consistent within a string
"this works"
and'this works'
too"this is not ok'
,'nor is this"
Embedded Quotes¶
How to embed a single or double quote inside a string?
You can embed a single quote in a double quoted string:
"this string's fine"
'but this doesn't work'
You can embed a double quote in a single quoted string:
'but this string is "A-OK"'
"but this "example" fails"
You can also "escape" a single or double quote with the backslash character:
'Marc\'s string'
"I like \"The Office\""
Escape Sequences¶
These are useful for embedding special characters in a string.
character | escape sequence |
---|---|
tab | \t |
newline | \n |
single quote | \' |
double quote | \" |
backslash | \\ |
Examples are shown in the next cell...
# escape sequence examples
print(“Quoth the raven: "nevermore".")
print(‘My country 'tis of thee’)
print(‘line1\nline2\nline3’)
print(“field1\tfield2\tfield3”)
print(‘c:\directory\file’)
print(‘several escape sequences:\n1/1\t1/2\n2/1\t2/2’)
Triple Quoted Strings¶
Sometimes you want to define a long string, that spans multiple lines, or a string containing embedded single and/or double quotes and don't want to use a lot of escape characters. Triple quoted strings are perfect for this job:
longstr = """
This is a triple quoted string.
It goes on for multiple lines.
It contains things like ' and ",
which would normally have to be escaped,
but anything goes in a triple quoted string.
"""
print(longstr)
Challenge¶
For each of the following examples tell me if it’s a legal Python string...
'Go ahead, make my day.'
"There's no place like home."
'Frankly my dear, I don't give a damn'
'Say "hello" to my little friend'
"You\'re gonna need a bigger boat"
'"You talkin' to me?"'
'Fasten your seatbelts, it\'s going to be a bumpy night'
'''Striker: "Surely you can't be serious!" Rumack: "I am serious... and don't call me Shirley".'''
"You had me at "hello"."
String Operators¶
+
and *
can be used to operate on strings.
Try the code in the cell below. One of these raises an error. What do you think the error message means?
print("Cat")
print("Cat", "videos")
print("Cat" + 3)
# To notice: 33 (the integer) is different from "33" (the string)
print(33 + 33)
print(type(33+33))
print(“33” + “33”)
print(type(“33” + “33”))
add * operator
Converting to a string¶
You can use the str()
function to convert a numeric type into a string, like this:
print("Cat" + "3")
print("Cat" + str(3))
String Methods¶
Method: A reusable piece of code that that is connected to a value or a variable
We invoke a method using the
.
syntax, e.g.mystr.upper()
.Methods are specific to a data-type e.g.
.upper()
can be used with a string but not an integer or a float
print("Cat".upper())
print("Cat".lower())
print("the lord of the rings".title())
Challenge¶
- you have 5 cats
- each cats consumes two tins of food per day
- how many tins needed per week
In the next cell, create a program that calculates how many FIX. You will need:
- A
print()
function call to output the result
Extension: change the calculation to work out the amount needed for 7 days.
Variables¶
Variables are names - a reusable label for a data value
name = 'Marc'
print(name)
name = 3.14
print(name)
Variable Naming Rules¶
There are some special rules governing variable names:
- variable names may start with a letter or an underscore
- the rest of the letters in the name may be letters, numbers or underscore case is significant
name
is different fromNAME
, which is different fromNaMe
Challenge¶
Which of the following are legal Python variable names?
average = 1
Max = 1
print = 1
LadyGaGa = 1
_Lady_Ga_Ga = 1
FiftyYardLine = 1
50_yard_line = 1
yard_line_50 = 1
raise = 1
my-cat-is-awesome = 1
my_cat_is_awesome = 1
Reserved Words¶
The following words have special meaning in Python. We call them keywords or reserved words and you may not use these names for your program variables.
and, as, assert, async, await, break, class, continue, def, del, elif, else, except, False, finally, for, from, global, if, import, in, is, lambda, nonlocal, None, not, or, pass, raise, return, True, try, while, with, yield
Constants vs. Variables¶
Literal values (like
"marc"
and2024
) are called constants because their value is fixed, unlike variables, whose associated value may change (or vary) over time.The data a variable refers to may be simple, e.g. a number or a string, or it may be complex, e.g. a list or an object (we'll learn about those later).
customer_id = "1234"
account_balance = 1000
print(f'customer id: {customer_id} account balance: {account_balance * 2}')
F-strings¶
We often need to combine variables, values, and strings. For example, if we have the following variables:
customer_id
account_balance
we might want to print a report, where each line summarizes the values above. We could do that like this:
print("customer id: ", customer_id, ", account balance:", account_balance)
which produces this output:
customer id: 123 , account balance: 17.9
This sort of construct gets a bit tedious. Plus the space between the customer id and the following comma is unintended and undesirable.
A relatively new addition to Python, called f-strings, offer a simpler and more readable solution to this problem. If you prefix a string with the character f
, it gives the string magic powers. Specifically, the sting has the ability to interpolate variables inside curly braces. Here's how we could express the previous print
statement using an f-string:
print(f"customer id: {customer_id} account balance: {account_balance}")
This is shorter, less tedious, easier to read and write, and solves the formatting issue related to the comma between the two fields.
Note that you can put any Python code inside the curly braces, so this technique is very powerful. Once you get going with Python, you'll find all sort of wonderful ways to use f-strings.
Assignment Statements¶
Assignment statements are used to associate a variable name with some simple or complex value general form:
variable_name = 'some_value'
If a variable doesn’t already exist, when you assign to it, Python creates it on the fly.
If you assign to a variable that already exists, Python replaces its current value with a new value.
Examples¶
instructor = 'marc' # string value
instructor = 'my evil twin' # same name, diff string value
instructor = 42 # same name, integer value
todays_high_temp = 71.3 # diff name, floating point value
Try some experiments in the next cell...
a = 0
print('a =', a)
a = 42
print('a =', a)
a = 3.14159
print('a =', a)
a = "Marc"
print('a =', a)
b = 42
print(‘a =’, a, ‘b =’, b)
a = b
print(‘a =’, a, ‘b =’, b)
b = 43
print(‘a =’, a, ‘b =’, b)
Usage Example¶
Let's print a list of the first 9 multiples of 9...
# Tedious version...
print(19)
print(29)
print(39)
print(49)
print(59)
print(69)
print(79)
print(89)
print(9*9)
# Nicer version...
factor = 8
print(1factor)
print(2factor)
print(3factor)
print(4factor)
print(5factor)
print(6factor)
print(7factor)
print(8factor)
print(9*factor)
Why is that nicer? Think about changing the requirement to print multiples of eight, instead of nine. How many lines would you have to change in the firat example? How about the second example?
The second example uses a redirection via a variable to make the code much easier to update. This is a very powerful and important concept in software engineering.
# Coming soon...
factor = 8
for i in range(1, 9):
print(i * factor)
Key Points¶
- Basic data types in Python include integers, floating-point numbers, and strings (there are others but we'll start with these).
- Use
variable = value
to assign a value to a variable in order to store it in memory. - Variables are created on demand whenever values are assigned to them for the first time.
Challenges¶
Problem 1¶
Prompt for user's name and print it back with "Nice to meet you, name!".
#@title Double click here to reveal solution
name = input (‘What is your name? ‘)
print (‘Nice to meet you,’, name +’!’)
Problem 2¶
Prompt for dog's age and return in people years in this format:
X dog years = Y people years.
#@title Double click here to reveal solution
dog_to_people_years = 7
dog_age = input(‘How old is your dog? ‘)
people_age = int(dog_age) * dog_to_people_years
print(dog_age,‘dog years =’, str(people_age), ‘people years.’)
Problem 3¶
Write a program to calculate the total number of hours in a fixed set of days, where the number of days is assigned to a variable.
#@title Double click here to reveal solution
days = 365
hours = 24
total_hours = days * hours
msg = f‘There are {total_hours} hours in {days} days.’
print(msg)
Problem 4¶
Write some Python code that uses all the maths operators you've learned.
#@title Double click here to reveal solution
a = 2 + 3
print(a)
a = 3 - 2
print(a)
a = 2 3
print(a)
a = 2 / 3
print(a)
a = 2 // 3
print(a)
a = 2 % 3
print(a)
a = 2 ** 3
print(a)
a = (2 + 3) 4
print(a)
Problem 5¶
In one statement, calculate and print your weekly pay if you earn $100 a day in a five day work week.
Store your daily pay rate in a variable and use the variable to calculate and print your weekly pay.
Congratulations - you just got a raise. Your new daily pay rate is $120. Assign a new value to the daily pay variable, then calculate and print your new weekly pay.
Store the number of days in a week in a variable, then calculate and print your weekly pay.
Calculate and print your weekly, monthly, and annual pay using only variables. Assume 5 workdays per week, 20 workdays per month and 240 workdays per year.
Print the your first, middle, and last name, each on a separate line.
Print the your first, middle, and last name, all on one line.