Python Course #4: Input and Output - Getting User Input

Lesson 4 of 30

Input and Output - Getting User Input

In programming, interaction is key. We need to get information FROM users and show information TO users. Python makes this incredibly easy with the input() and print() functions.

Getting User Input

The input() function allows your program to pause and wait for the user to type something. It always returns what the user types as a string.

# Simple input example
name = input("What is your name? ")
print("Hello, " + name)
Output:
What is your name? Alice
Hello, Alice

Input is Always a String

Remember: input() always returns a string, even if the user types a number. If you want to use it as a number, you must convert it.

# Getting a number from user
age_text = input("How old are you? ")
age = int(age_text) # Convert to integer
print("Next year you will be", age + 1)
Output:
How old are you? 25
Next year you will be 26
Q1: What does the input() function return?
A) An integer
B) A float
C) A string

Converting Input to Different Types

You can convert input to different data types:

  • int() - Converts to integer
  • float() - Converts to floating-point number
  • str() - Converts to string (already a string)
# Converting to float
height = float(input("Enter your height in meters: "))
print("Your height is", height, "meters")
Output:
Enter your height in meters: 1.75
Your height is 1.75 meters
Q2: If you want to do math with user input, what should you do?
A) Nothing, input() gives numbers automatically
B) Convert it using int() or float()
C) Use a different function instead of input()

Formatting Output with f-strings

Python 3.6+ introduced f-strings (formatted string literals), which make it easy to insert variables into strings.

name = "Bob"
age = 30
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Bob and I am 30 years old.

Notice the f before the quotes and the curly braces {} around variable names.

Q3: What is the correct way to create an f-string?
A) "My name is {name}"
B) f"My name is {name}"
C) s"My name is {name}"

Practice Challenge

Your Task: Create a program that:

  1. Asks the user for their name
  2. Asks for their age
  3. Asks for their favorite number
  4. Prints a message using all three pieces of information with an f-string
  5. Calculates and prints what their age will be in 10 years

Hint: Remember to convert the age to an integer for the calculation!

Key Takeaways

  • input() gets information from the user
  • input() always returns a string
  • Use int() or float() to convert input to numbers
  • F-strings make it easy to format output with variables
  • Put an f before the quotes: f"text {variable}"
Great Work! Next: Operators and Expressions - Learn how to perform calculations

Post a Comment

0 Comments