๐Ÿ Python for Teens & Beginners ยท Lesson 2 of 7

Variables and input

Google Classroom

Store information and ask the user.

Variables

name = "Maya"
age = 12
print(name)
print(age + 1)

A variable is a name for a value. = means โ€œstoreโ€ (not โ€œequalsโ€ like in math). Now name holds "Maya" and age holds 12.

Naming rules

Letters, digits, _favorite_color, score2
Canโ€™t start with a digit2score is an error
No spacesUse snake_case: high_score
Meaningfultotal_price, not x

input

name = input("What is your name? ")
print("Nice to meet you, " + name + "!")

input waits for the user to type and press Enter, and returns what they typed โ€” always as a string.

Numbers from input

age = int(input("How old are you? "))
print("Next year you will be", age + 1)

int() turns the string "12" into the number 12. Use float() for decimals like 3.5. print with commas adds spaces between items.

Tip

๐Ÿ’ก f-strings make printing easy: print(f"Hi {name}, you are {age}") โ€” put an f before the quotes and variables in {curly braces}.

โœ๏ธ Practice: your turn

  1. Ask the user for their name and favorite animal, and print a sentence with both
  2. Ask for a birth year and print the age they turn this year
  3. Rewrite one print using an f-string
  4. Try int("hello") and read the error

โœ๏ธ Run Python in your browser, no install โ†—

๐Ÿง  Quick quiz

Answer all 4 questions correctly to mark this lesson as done.

1. What does age = 12 do?
2. Which name is NOT allowed?
3. What type does input() return?
4. What does int("7") give?

0 of 4 correct