Python - 2. Variables
2.1.1 Two Types of Numbers: integers and floats
2.2.2 Using Variables With Numbers
2.2.3 Using Variables With Strings
2.2.4 Combining Numbers and Strings In A print Statement
2.2.5 Changing A Variable’s Value
A2.2 - Adding and Multiplying User Input
A2.3 - Gather Basic Information
2. Variables
2.1 Data Types
2.1.1 Two Types of Numbers: integers and floats
- There are two basic “types” of numbers that we are going to be dealing with in Python. Going back to basic math, we have:
- integers - Things that are not fractions or decimals. In Python, an integer is known as: int
- decimals - Things that are fractions, or decimals. In Python, a number with a decimal is known as a float. The name comes from the decimal place in different numbers floating from the front of one number (1.234) to the end of another (123456.7)
- When Python considers a number an integer, even if the number has a decimal, it doesn’t see the decimals at all, which results in strange behavior. It doesn’t even round, it just cuts off the decimal completely. To make Python consider a number as an integer, you use this form. This is known as casting the number to an integer:
int(number) - where number can be any number.
Examples:
Actual Math In Python
- 6 / 4 = 1.5 but int(6 / 4) = 1
- 100 / 9 = 11.1111 but int(100 / 9) = 11
- 5 / 6 = 0.83334 but int(5 / 6) = 0
2.1.2 Text: strings
- Often, data can take the form of text. We can think of text as made up of characters. A Character is any letter, number, space, punctuation mark, or symbol that can be typed on a computer.
Examples: (count them to make sure you understand)
- “This” - 4 characters
- “This and that” - 13 characters (include the spaces)
- “Don’t say %$#” - 13 characters (everything counts)
- When you put individual characters together, you have a string of characters. In Python, any one run of characters of text is called a string, represented as str. Strings are contained in either single or double quotes.
‘hello’ is the same as “hello”
2.1.3 True or False: Booleans
- Booleans have a special place in computer science. They have only two possible values: True or False.
Examples:
- print(5 < 10) - prints True
- print(5 > 10) - prints False
- We can cast text and numbers to booleans. Most values evaluate to True. Only blanks and zeros are False.
Examples: (Try these for yourself)
- print(bool(“Hello”)) - casting a string to a boolean returns True
- print(bool(15)) - casting 15 to a boolean returns True
- print(bool(0)) - casting 0 to a boolean returns False
- print(bool(“”)) - casting a blank to a boolean returns False
2.2 Introduction to Variables
- Variables are containers for storing data values. Creating a variable is like creating a box with a label on it and putting data in it. This data can be an integer, float or boolean. The label on the box is the variable name and what is in the box is the value of the variable.
- Variables have three parts:
- data type - Can be int, float, str, bool (there are more, but that’s for later)
- value - The number, text, True/False that we give it to hold
- name - Known as an identifier. We can pick this name
2.2.1 Naming Variables
- The name of a variable is known as its identifier. You get to make up your own identifiers (names of the boxes that hold the values). There are rules for picking an identifier for a variable:
- Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore ( _ ).
- An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name.
- Keywords (words that are specially defined by Python, also known as reserved words, like print) cannot be used as identifiers.
- We cannot use special symbols like !, @, #, $, % in our identifier.
- An identifier can be of any length.
- Things to remember about identifiers:
- Python is a case-sensitive language. This means, Variable and variable are not the same. It is good practice to stick with lower-case names.
- Always give the variable a name that makes sense. This will come with practice.
- Multiple words can be separated using an underscore, like a_long_variable.
2.2.2 Using Variables With Numbers
- Here is a sample program that is used to find the area of a right triangle with side lengths of 5 and 10 units. The area formula in general is 0.5 * side1 * side2:
print( 0.5 * 5 * 10 ) # Output is 25.0 ← This is a comment in the program
I could create two variables, called side1 and side2, to represent each of the sides. I could then write the program like this:
side1 = 5
side2 = 10
print( 0.5 * side1 * side2 ) # Output is still 25.0
2.2.3 Using Variables With Strings
- When you set a variable to a string, you surround the string in quotes. Here is a very simple program:
name = “Tommy”
print(name) # Output is: Tommy
- When you need to combine two strings in a print statement, you have to join them. There is a fancy word that is used in computer science called concatenation, which means to join things together. The plus ( + ) sign is used for this. Here is a program that demonstrates this:
first_name = “Rohan”
second_name = “Bernard”
print(first_name + second_name) # Output is: RohanBernard
If we want to format the output better, to include a space between the first and last name, we have to add in a space, which we represent as “ “ (quotes with a space between them)
first_name = “Rohan”
second_name = “Bernard”
print(first_name + “ “ + second_name) # Output is: Rohan Bernard
2.2.4 Combining Numbers and Strings In a print Statement
- So far, we have seen that you can print a number or a variable that represents a number. You can also print a string or a variable that represents a string. We have also seen how to join two strings using the + .
- When you are printing a string along with a number, Python has some trouble joining these two types of data. You need to cast a number to be read as a string. Python can see a number as a number, or as a string of characters. When printing, it needs to see the number as a string.
EXAMPLE #1:
Version #1:
num_apples = 5
print(“I have “ + num_apples + “ apples in a bag.”)
Generates the following error:
TypeError: can only concatenate str (not "int") to str
It is important to start to read errors as you learn how to program. This one is saying that there is a TypeError, meaning a problem with a data type. It then goes on to tell us that you can only concatenate (join) a str (string) with a str and not an int. To make this work, we would have to cast the int to a str.
Version #2:
num_apples = 5
print(“I have “ + str(num_apples) + “ apples in a bag.”)
OUTPUT: I have 5 apples in a bag.
The program works because it is now only concatenating strings.
EXAMPLE #2:
This is a program made of four simple print statements.
Version #1:
print(“There once was a man named Josh,”)
print(“he was 90 years old.”)
print(“He really liked the name Josh,”)
print(“but he didn’t like being 90.”)
OUTPUT: There once was a man named Josh,
he was 90 years old.
He really liked the name Josh,
but he didn’t like being 90.
We can represent the name Josh as a str variable and the age 90 as an int variable as seen in Version #2.
Version #2:
name = “Josh”
age = 90
print(“There once was a man named “ + name + “, ”)
print(“he was “ + str(age) + “ years old.”)
print(“He really liked the name “ + name + “, “)
print(“but he didn’t like being ” + str(age) + “.”)
This would have the same output as Version #1. Why would we do something like this? If the program was very long and printed the name and age many times, we would only have to change their values in one place and the program would adjust for us, as seen in Version #3.
Version #3:
name = “Paul”
age = 33
print(“There once was a man named “ + name + “, ”)
print(“he was “ + str(age) + “ years old.”)
print(“He really liked the name “ + name + “, “)
print(“but he didn’t like being ” + str(age) + “.”)
OUTPUT: There once was a man named Paul,
he was 33 years old.
He really liked the name Paul,
but he didn’t like being 33.
2.2.5 Changing A Variable’s Value
- Once a variable has a value, it is not fixed at that value. You can change it at any time. Follow this simple program as a demonstration:
counter = 0
print(“The counter is at: “ + str(counter))
counter = 1
print(“The counter is at: “ + str(counter))
counter = 2
print(“The counter is at: “ + str(counter))
OUTPUT: The counter is at: 0
The counter is at: 1
The counter is at: 2
The print statement is always the same, but the value that we are keeping in the container called counter is changing.
2.3 Reading User Input
- Defining a variable directly in a program with a number or string is called hard coding, but often, a program becomes much more useful if you can create variable values based on input from a user or from a file. Python makes it very easy to accept user input and assign the value to a variable. This input is usually entered through the keyboard and uses the keyword input.
EXAMPLE #1:
name = input(“What is your name? ”) # assigns user input to name
print(“Hello “ + name + “. Great to meet you!”)
OUTPUT: What is your name? Carla # pauses for input
Hello Carla. Great to meet you!
Input is always received as a string. If we ask for a name and an age, notice that we don’t have to cast the age to a string because it already is one:
name = input(“What is your name? ”)
age = input(“How old are you? ”)
print(“Hello “ + name + “. You are ” + age + “ years old!”)
OUTPUT: What is your name? Carla
How old are you? 7
Hello Carla. You are 7 years old!
EXAMPLE #2:
Our triangle area program from 2.2.2 can be made much more useful now. Notice that when we are reading in the values for the lengths of the sides of the triangle, they are being cast to integers right away and stored as numbers, not strings. If this was not done, the area calculation would not work because side1 and side2 would be strings.
side1 = int(input(“Length of the first side: “))
side2 = int(input(“Length of the second side: “))
area = 0.5 * side1 * side2
print(“The triangle has an area of “ + str(area) + ”.”)
OUTPUT: Length of the first side: 4
Length of the second side: 5
The triangle has an area of 10.
Chapter 2: Assignments
A2.1 - Favorites Version #2
This assignment is similar to one in Chapter 1, but here, you are creating variables for each of your favorites that you will use when printing.
PROGRAM STRUCTURE:
########################################
## Program title, author, date and description
########################################
# create a variable that holds the value of the name
# create a variable that holds the value of the birthday
# continue creating variables that hold the values of the hobbies, book and movie
# print out the variable values as shown in the SAMPLE RUN below
SAMPLE RUN:
Name: Josh Finkel
Birthday: March 30, 1972
Hobbies: Spending time with annoying students
Favorite book: East of Eden
Favorite movie: Princess Bride
A2.2 - Adding and Multiplying User Input
Here you will practice collecting information from the user. You will then process it and return the information. Do this by asking the user for two numbers. Take those numbers and return to the user the value of the product (multiply) and the sum (addition) of them. Match the output in the SAMPLE RUN as closely as possible.
PROGRAM STRUCTURE:
########################################
## Program title, author, date and description
########################################
# Ask the user for a number (the program should be able to handle decimals)
# Ask the user for a second number (your variable names make sense)
#
# return the sum of the numbers
# return the product of the numbers
SAMPLE RUN:
Please give me a number: 14
Thank you. Please give me another number: 10
If I add those numbers together, I get 24.
If I multiply those numbers together, I get 140.
A2.3 - Gather Basic Information
Create a program that asks a user for their first name, last name and age. Each of these values should be assigned to a different variable.
PROGRAM STRUCTURE:
########################################
## Program title, author, date and description
########################################
# Ask the user for their first name
# Ask the user for their last name
# Ask the user for their age
# Print the information back to the user as shown in the SAMPLE RUN
SAMPLE RUN:
What is your first name?
Peter
What is your last name?
Bigelow
How old are you?
32
Peter Bigelow is 32 years old!
A2.4 - Find the Average
Write a program that creates three variables called num1, num2 and num3 with values that you make up. It should then calculate and store their average in a float variable called avg. It should then print the results to the screen.
PROGRAM STRUCTURE:
########################################
## Program title, author, date and description
########################################
# Create three variables with three values that you pick
# Create a variable (avg) that calculates the average of the three variables. Make
# sure you use the variable names in the calculation and not the actual number.
# Print the information back to the user as shown in the SAMPLE RUN
SAMPLE OUTPUT #1:
The average of 4, 10, and 5 is 6.333333333333333
SAMPLE OUTPUT #2:
The average of 40, 152, and 5 is 65.66666666666667
A2.5 - Short Mad-Lib
Mad-libs is a game where one player prompts another for a list of words to substitute for blanks in a story. Your program will ask the user for at least two nouns, two verbs, two adjectives and two adverbs. They should be stored with the following variable names: noun1, noun2, verb1, verb2, adj1, adj2, adv1, adv2. Then have the program print a story to the screen based on these words.
PROGRAM STRUCTURE:
########################################
## Program title, author, date and description
########################################
# Prompt the user for all of their words.
# Return a story that you wrote with the words that the user substituted in it.
SAMPLE RUN:
Please give me a noun: house
Another noun: key
Please give me a verb: stick
Another verb (past tense): kicked
Please give me an adjective: fantastic
Another adjective: deathly
Please give me an adverb: quickly
Another adverb: smoothly
Here is the story that you generated:
Once there was a fantastic house. It liked to stick quickly. Yesterday, the house
smoothly kicked a deathly key.
Key Terms
bool - A data type in Python representing a boolean value, which is either True or False.
casting - The act of turning a variable or piece of data from one data type to another.
character - Any letter, number, space, punctuation mark, or symbol that can be typed on a computer.
float - A data type in Python that represents a number with a decimal or fractional component (piece)
hard coding - Embedding data directly into the code of a program as opposed to getting the data from external sources like keyboard input or a file.
identifier - The name of a variable that is selected by the programmer.
int - A data type in Python that represents an integer, which is a whole number, or a number that is not a fraction.
keywords - Also known as reserved words. These are words that are defined by a programming language and cannot be used as identifiers.
str - A data type in Python which is short for the word string. It represents one or more characters grouped together.