🐍 Python Course 3: More About Variables

📋 Background Information Quiz

Please answer the following questions to check your understanding before continuing. These are quick questions to refresh your memory.

Question 1: What is a variable?




Question 2: What are the main data types we discussed in the previous course?




Question 3: How do you read user input in Python?




📚 Table of Contents

đŸŽ¯ Learning Objectives

After completing this section, you will be able to:

  • You will be able to use variables in different contexts
  • You will know what kind of data can be stored in variables
  • You will understand the difference between strings, integers and floating point numbers

🔧 Variables Basics

Variables are needed for various purposes in programming. You can use variables to store any information that will be needed later in the program's execution.

In Python programming variables are created like so:

variable_name = ...

Here ... means the value stored in the variable.

For example, when you used the input command to read a string from the user, you stored the string in a variable and then used the variable later in your program:

name = input("What is your name? ") print("Hi, " + name)
Sample output:
What is your name? Paul Python
Hi, Paul Python

The value stored in a variable can also be defined using other variables:

given_name = "Paul" family_name = "Python" name = given_name + " " + family_name print(name)
Sample output:
Paul Python

Here the values stored in the three variables are not obtained from user input. They remain the same every time the program is executed. This is called hard-coding data into the program.

🔄 Changing the Value of a Variable

As implied by the name variable, the value stored in a variable can change. In the previous section we noticed that the new value replaces the old one.

During the execution of the following program, the variable word will have three different values:

word = input("Please type in a word: ") print(word) word = input("And another word: ") print(word) word = "third" print(word)
Sample output:
Please type in a word: first
first
And another word: second
second
third

The value stored in the variable changes each time the variable is assigned a new value.

The new value of a variable can be derived from its old value. In the following example the variable word is first assigned a value based on user input. Then it is assigned a new value, which is the old value with three exclamation marks added to the end.

word = input("Please type in a word: ") print(word) word = word + "!!!" print(word)
Sample output:
Please type in a word: test
test
test!!!

📝 Choosing a good name for a variable

📋 Best Practices for Variable Names

  • Descriptive: Use names that describe what the variable contains
  • Lowercase: Use only lowercase letters
  • Underscores: Use underscores to separate words in multi-word names
  • Start with letter: Variable names must start with a letter
  • Valid characters: Can contain letters, numbers, and underscores

Good Examples:

# ✅ Good variable names user_name = "Alice" student_age = 25 total_score = 100 first_number = 42 # ✅ Multi-word variables final_result = "passed" error_message = "Invalid input" maximum_attempts = 3

Bad Examples:

# ❌ Bad variable names a = "Alice" # Too short, not descriptive StudentAge = 25 # Mixed case (not Pythonic) total-score = 100 # Hyphens not allowed 42number = 42 # Can't start with number error message = "Invalid" # Spaces not allowed

Case Sensitivity

Python variables are case-sensitive. These are all different variables:

name = "Alice" Name = "Bob" NAME = "Charlie" print(name) # Alice print(Name) # Bob print(NAME) # Charlie

đŸ”ĸ Integers

Integers are whole numbers without decimal points. They can be positive, negative, or zero.

Creating Integer Variables

# Integer examples age = 25 temperature = -5 score = 0 year = 2024 print(age) print(temperature) print(score) print(year)
Sample output:
25
-5
0
2024

âš ī¸ Important Note

Notice there are no quotation marks around integers! If you add quotes, Python treats it as a string:

number = 42 # Integer text = "42" # String print(number + 1) # 43 (addition) print(text + "1") # 421 (concatenation)

đŸˇī¸ Variable Types & Operations

Different data types behave differently with various operations. Understanding this is crucial for writing correct programs.

Type-Specific Operations

# Integer operations integer_number = 100 print(integer_number + integer_number) # 200 (addition) print(integer_number / 2) # 50.0 (division) # String operations string_number = "100" print(string_number + string_number) # 100100 (concatenation) # print(string_number / 2) # ERROR! Can't divide strings
Sample output:
200
50.0
100100

Common Data Types in Python

  • int: Integers (whole numbers)
  • float: Floating-point numbers (decimals)
  • str: Strings (text)
  • bool: Boolean values (True/False)

🔗 Combining Values When Printing

Sometimes you need to print a message that combines strings and numbers. Python provides several ways to do this.

Using str() Function

Convert numbers to strings using the str() function:

result = 10 * 25 print("The result is " + str(result))
Sample output:
The result is 250

Using Comma Separation

Python automatically adds spaces between comma-separated values:

result = 10 * 25 print("The result is", result)
Sample output:
The result is 250

⚡ F-Strings (Formatted Strings)

F-strings are a modern and convenient way to format strings in Python. They were introduced in Python 3.6.

Basic F-String Usage

name = "Alice" age = 30 city = "New York" # F-string with variables print(f"Hello, {name}! You are {age} years old.") print(f"You live in {city}.")
Sample output:
Hello, Alice! You are 30 years old.
You live in New York.

F-Strings vs Other Methods

name = "Alice" age = 30 city = "New York" # Using concatenation (old way) print("Hi " + name + ", you are " + str(age) + " years old.") # Using comma separation print("Hi", name, ", you are", age, "years old.") # Using f-strings (recommended) print(f"Hi {name}, you are {age} years old.")
Sample output:
Hi Alice, you are 30 years old.
Hi Alice , you are 30 years old.
Hi Alice, you are 30 years old.

đŸŽ¯ Why F-Strings Are Better

  • More readable and concise
  • No need for type conversion
  • Better control over formatting
  • Less error-prone

🐍 F-Strings and Python Versions

If you are using an older version of Python, f-strings may not work. They were introduced in Python version 3.6. Later on during the course you will install Python on your own computer. Unfortunately, the more modern versions of Python are not always available for older operating systems. If that is the case with your computer, when there are exercises requiring the use of f-strings, you can always try them out in the in-browser exercise templates in this course.

🌊 Floating Point Numbers

Floating point numbers (or floats) are numbers with decimal points. They can represent fractional values.

Creating Float Variables

# Float examples pi = 3.14159 temperature = -2.5 height = 5.8 average = 85.5 print(f"Pi: {pi}") print(f"Temperature: {temperature}") print(f"Height: {height}") print(f"Average: {average}")
Sample output:
Pi: 3.14159
Temperature: -2.5
Height: 5.8
Average: 85.5

Float Arithmetic

number1 = 2.5 number2 = -1.25 number3 = 3.62 mean = (number1 + number2 + number3) / 3 print(f"Mean: {mean}")
Sample output:
Mean: 1.6233333333333333

đŸ–Ĩī¸ Programming Exercise: Extra space

Your friend is working on an app for jobseekers. She sends you this bit of code:

name = "Tim Tester" age = 20 skill1 = "python" level1 = "beginner" skill2 = "java" level2 = "veteran" skill3 = "programming" level3 = "semiprofessional" lower = 2000 upper = 3000 print("my name is ", name, " , I am ", age, "years old") print("my skills are") print("- ", skill1, " (", level1, ")") print("- ", skill2, " (", level2, ")") print("- ", skill3, " (", level3, " )") print("I am looking for a job with a salary of", lower, "-", upper, "euros per month")

The program should print out exactly the following:

Sample output:
my name is Tim Tester, I am 20 years old

my skills are
- python (beginner)
- java (veteran)
- programming (semiprofessional)

I am looking for a job with a salary of 2000-3000 euros per month

The easiest way to transform the code so that it meets requirements is to use f-strings. You can print an empty line by adding an empty print command, or by adding the newline character \n into your string.

đŸ–Ĩī¸ Programming Exercise: Arithmetics

This program already contains two integer variables, x and y:

x = 27 y = 15

Please complete the program so that it also prints out the following:

Sample output:
27 + 15 = 42
27 - 15 = 12
27 * 15 = 405
27 / 15 = 1.8

The program should work correctly even if the values of the variables are changed. That is, if the first two lines are replaced with this

x = 4 y = 9

the program should print out the following:

Sample output:
4 + 9 = 13
4 - 9 = -5
4 * 9 = 36
4 / 9 = 0.4444444444444444

đŸ–Ĩī¸ Programming Exercise: Fix the code: Print a single line

Each print command usually prints out a line of its own, complete with a change of line at the end. However, if the print command is given an additional argument end = "", it will not print a line change.

For example:

print("Hi ", end="") print("there!")
Sample output:
Hi there!

Please fix this program so that the entire calculation, complete with result, is printed out on a single line. Do not change the number of print commands used.

print(5) print(" + ") print(8) print(" - ") print(4) print(" = ") print(5 + 8 - 4)

🔄 Type Conversion

Sometimes you need to convert data from one type to another. Python provides built-in functions for type conversion.

Common Type Conversion Functions

  • int() - Converts to integer
  • float() - Converts to floating point number
  • str() - Converts to string

Converting Strings to Numbers

# Converting string input to integer age_str = input("Enter your age: ") age = int(age_str) print(f"Next year you will be {age + 1} years old") # Converting string to float height_str = input("Enter your height in meters: ") height = float(height_str) print(f"Your height is {height} meters")

Converting Numbers to Strings

result = 42 message = "The answer is " + str(result) print(message)

âš ī¸ Conversion Errors

Be careful when converting! If the string cannot be converted to the requested type, Python will raise an error:

number = int("not a number") # This will cause an error!

âŒ¨ī¸ Reading Integers from User Input

The input() function always returns a string. When you need to work with numbers from user input, you must convert them first.

Reading and Converting in One Line

# Ask for user's age and convert to integer age = int(input("What is your age? ")) print(f"You are {age} years old") # Calculate with the input next_year = age + 1 print(f"Next year you will be {next_year}")
Sample output:
What is your age? 25
You are 25 years old
Next year you will be 26

Reading Float Numbers

# Reading a decimal number temperature = float(input("What is the temperature? ")) print(f"The temperature is {temperature} degrees") # Calculations with floats fahrenheit = temperature * 9/5 + 32 print(f"That's {fahrenheit} degrees Fahrenheit")
Sample output:
What is the temperature? 20.5
The temperature is 20.5 degrees
That's 68.9 degrees Fahrenheit

You have reached the end of this section!

Continue to the next section: Arithmetic operations

🎮 Interactive Exercises

Test your understanding with these additional interactive exercises! Write your code in the editors below and click the buttons to see the results.

📝 Exercise 1: Basic Variable Creation (1 point)

Create variables to store your name, age, and favorite number:

Name: Alice Age: 25 Favorite number: 7
# Write your code here
📝 Exercise 2: Changing Variables (1 point)

Practice changing variable values:

hello world world!
# Write your code here
📝 Exercise 3: Integer Operations (1 point)

Practice arithmetic with integers. Write code that performs addition, subtraction, multiplication, and division:

Expected output:
27 + 15 = 42
27 - 15 = 12
27 * 15 = 405
27 / 15 = 1.8
# Write your code here x = 27 y = 15
📝 Exercise 4: String vs Integer (1 point)

Understand the difference between strings and integers. Show what happens when you add integers vs concatenate strings:

Expected output:
Integer: 200
String: 100100
# Write your code here
📝 Exercise 5: F-String Formatting (1 point)

Practice using f-strings for formatted output. Create a profile with name, age, and city:

Expected output:
Name: Alice, Age: 30, City: Wonderland
# Write your code here
📝 Exercise 6: Float Calculations (1 point)

Work with floating point numbers. Calculate the average of three decimal numbers:

Expected output:
Average: 2.4666666666666663
# Write your code here
📝 Exercise 7: Variable Reassignment (1 point)

Practice reassigning values based on current values. Start with a score of 10, add 5, then multiply by 2:

Expected output:
Initial score: 10
After bonus: 15
After multiplier: 30
# Write your code here
📝 Exercise 8: Mixed Data Types (1 point)

Combine different data types in output. Create variables for name (string), age (integer), and height (float):

Expected output:
Bob is 25 years old and 5.9 feet tall
# Write your code here
📝 Exercise 9: Variable Naming (1 point)

Practice proper variable naming conventions. Use descriptive names with underscores for multi-word variables:

Expected output:
Full name: John Doe
Age: 28 years
# Write your code here
📝 Exercise 10: Complete Student Profile (2 points)

Create a complete student profile with multiple variables and formatted output:

Expected output:
Student Profile:
Name: Emma
Age: 22
Grade: A
GPA: 3.8
# Write your code here

âŦ…ī¸ Previous

Course 2: Information from the user