Talking to Your Program

Intro to Python · Lesson 2 of 4

Goal: get input from the user and work with text

Getting input from the user

So far your programs only ever print what you already typed in. input() pauses the program and waits for the user to type something, then hands that text back to you:

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

Important: input() always returns a str, even if the user types a number.

Type casting

If you need that input as a number, convert it with int() or float():

age = input("How old are you? ")   # age is a string, e.g. "16"
age = int(age)                     # now age is the number 16
print(age + 1)                     # 17

Without the conversion, age + 1 would crash — you can't add a number to a string.

Combining text: concatenation vs. f-strings

You've already seen + used to glue strings together (concatenation). It works, but gets messy once numbers are involved — you have to convert everything to a string first. f-strings are cleaner: put an f before the quotes and drop variables directly into { }.

name = "Maya"
age = 16

# Concatenation
print("Hi " + name + ", you are " + str(age) + " years old.")

# f-string (preferred)
print(f"Hi {name}, you are {age} years old.")

Useful string tools

Code What it does
len(name) number of characters in name
name.upper() ALL CAPS version
name.lower() all lowercase version
name.title() Title Case Version
name = "maya"
print(len(name))     # 4
print(name.upper())  # MAYA
print(name.title())  # Maya

Try it yourself

Ask the user for their favorite food with input(), then print an f-string that shouts it back in all caps, e.g. Your favorite food is PIZZA!

Assignment: Mad-Libs Generator

Write a program that asks the user for three words — an adjective, a noun, and a verb ending in "-ing" — using three separate input() calls. Then use an f-string to drop them into a silly sentence, for example:

What's an adjective? sparkly
What's a noun? dinosaur
What's a verb ending in -ing? dancing

The sparkly dinosaur went dancing through the school cafeteria.

When you're done, copy your Replit link and submit it below.