← All chapters

Python curriculum / Chapter 02

Variables

Data types, variables, strings, numbers, user input, and five assignments.

Python - 2. Variables

2. Variables

2.1 Data Types

2.1.1 Two Types of Numbers: integers and floats

2.1.2 Text: strings

2.1.3 True or False: Booleans

2.2 Introduction to Variables

2.2.1 Naming Variables

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

2.3 Reading User Input

Chapter 2: Assignments

A2.1 - Favorites Version #2

A2.2 - Adding and Multiplying User Input

A2.3 - Gather Basic Information

A2.4 - Find the Average

A2.5 - Short Mad-Lib

Key Terms

2. Variables

2.1 Data Types

2.1.1 Two Types of Numbers: integers and floats

int(number) - where number can be any number.

Examples:

Actual Math In Python

  1. 6 / 4 = 1.5 but int(6 / 4) = 1
  2. 100 / 9 = 11.1111 but int(100 / 9) = 11
  3. 5 / 6 = 0.83334 but int(5 / 6) = 0

2.1.2 Text: strings

Examples: (count them to make sure you understand)

  1. “This” - 4 characters
  2. “This and that” - 13 characters (include the spaces)
  3. “Don’t say %$#” - 13 characters (everything counts)

‘hello’ is the same as “hello”

2.1.3 True or False: Booleans

Examples:

  1. print(5 < 10) - prints True
  2. 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)

  1. print(bool(“Hello”)) - casting a string to a boolean returns True
  2. print(bool(15)) - casting 15 to a boolean returns True
  3. print(bool(0)) - casting 0 to a boolean returns False
  4. print(bool(“”)) - casting a blank to a boolean returns False

2.2 Introduction to Variables

  1. data type - Can be int, float, str, bool (there are more, but that’s for later)
  2. value - The number, text, True/False that we give it to hold
  3. name - Known as an identifier. We can pick this name

2.2.1 Naming Variables

  1. 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 ( _ ).
  2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name.
  3. Keywords (words that are specially defined by Python, also known as reserved words, like print) cannot be used as identifiers.
  4. We cannot use special symbols like !, @, #, $, % in our identifier.
  5. An identifier can be of any length.

2.2.2 Using Variables With Numbers

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

name = “Tommy”

print(name) # Output is: Tommy

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

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

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

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.