Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Module 1 - Python Fundamentals Python Python Basics Python Programming: From Zero to Real-World Applications

Input and Output - Getting User Data in Python

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • How to get user input with input()
  • How to convert input to numbers
  • How to format output nicely
Terminalpython
# input() always returns a string
name = input("Enter your name: ")
print(f"Hello, {name}!")

# Convert to int
age_str = input("Enter your age: ")
age = int(age_str)
print(f"Next year you will be {age + 1}.")

# Convert to float
height = float(input("Enter your height in feet: "))
print(f"You are {height} feet tall.")
input() always returns string
input("Enter a number: ") returns "42" (string), not 42 (int). Always convert with int() or float() before doing math.

Handling Bad Input

Terminalpython
try:
    age = int(input("Enter your age: "))
    print(f"You are {age} years old.")
except ValueError:
    print("That is not a valid number!")

Formatted Output

Terminalpython
# Multiple values on one line
print("Name:", "Anita", "Age:", 28)
# Name: Anita Age: 28

# Using sep and end
print("A", "B", "C", sep="-")   # A-B-C
print("Loading", end="...")        # Loading... (no newline)
print("Done")

# f-string formatting
price = 19.99
qty = 3
print(f"Total: ${price * qty:.2f}")   # Total: $59.97

Practical Exercise

Ask the user for their name: input("Name: ")
Ask for their age and convert to int
Print: f"Hi {name}, you are {age} years old"
Calculate and print their age in 10 years
Handle invalid input with try/except

Key Takeaways

  • input() always returns a string - convert with int() or float().
  • Always wrap int(input()) in try/except for user input.
  • print() with sep= and end= for custom formatting.
  • f-strings: f"Total: ${price:.2f}" for formatted output.
  • sep="-" changes the separator. end="" removes the newline.
Previously: Lesson 07 covered strings.
Today: You learned: Get data from users and display results.
Next: Module 1 complete! Module 2 begins with lesson 09.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments