Input & Output
Real programs talk with people. The output half you already know: print() sends text out to the screen.
The input half uses input(). It pauses the program, waits for the person to type a line, and hands back what they typed as a string:
name = input("What is your name? ")
print(f"Hello, {name}!")One thing to remember: input() always returns a string, even if the person types digits. To do math with it you convert first, with int(...) or float(...):
age_text = input("Your age? ") # e.g. "20", a string
age = int(age_text) # now the number 20
print(age + 1)Why we will use functions here instead
This lesson runs inside an auto-grader that has no keyboard waiting on the other end, so calling input() would just hang. The professional habit anyway is to keep the talking-to-humans part separate from the logic. So we wrap the logic in a function that takes the value as a parameter, and the real input would simply be passed in:
def greet(name):
return f"Hello, {name}!"
print(greet("Ada")) # Hello, Ada!
# In a real app: greet(input("Name? "))Write a function greet(name) that returns the string Hello, <name>! for whatever name is passed in. For example greet("Sam") must return "Hello, Sam!". Do not call input(). After defining it, print greet("Sam") so you can see it work.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.