User Input and Type Conversion
15 min In ProgressLearning Objectives
- Capture user input with input()
- Convert between data types
- Handle basic input errors
Getting Input from the User
The input() function pauses your program and waits for the user to type something.
name = input("What is your name? ")
print(f"Hello, {name}!")
Converting Input to Numbers
input() always returns a string. Use int() or float() to convert it for math.
age = int(input("Enter your age: "))
print(f"Next year you will be {age + 1}")
Course Example: Binary Converter
A script that takes a decimal number and converts it to binary.
number = input("Convert to binary: ")
# convert to integer
integer = int(number)
# convert integer to binary
binary = bin(integer)
print(binary)
Course Example: Days Converter
Break a total number of days into years, weeks, and remaining days.
days = int(input("Number of days:"))
years = days // 365
weeks = (days % 365) // 7
days = days - ((years * 365) + (weeks * 7))
print("Years:", years)
print("Weeks:", weeks)
print("Days:", days)
📝 Exercise: Simple Calculator
Ask the user for two numbers and print their sum, difference, product, and quotient.
code.py
Output