Skip to content

Learning Python: Day 17

Chapter 7 – User input and while loops

  • most programs are meant to solve user’s problem
  • that means you need the user to input their info first
  • for example, if a person wants to find out if they’re old enough to vote
  • input() function – prompt user for information
  • while loop – to keep programs running as long as conditions are met
  • this will allow you to write interactive programs

How the input() function works

  • input() function pauses program and waits for the user to provide info
  • Python will assign the input to a variable so we can work with it

parrot.py

message = input(“Tell me something, and I will repeat it back to you: “)

print(message)

  • input() function takes one argument: the prompt we display to the user so they know what we want
  • program continues after user presses enter

Tell me something, and I will repeat it back to you: Hello everyone!

Hello everyone!

Writing clear prompts

greeter.py

name = input(“Please enter your name: “)

print(f”\nHello, {name}!”)

Please enter your name: Eric

Hello, Eric!

  • can assign prompt to a variable and pass that variable to the input() function

greeter.py

prompt = “If you share your name, we can personalize the messages you see.”

prompt += “\nWhat is your first name? “

name = input(prompt)

print(f”\nHello, {name}!”)

  • example highlights multiline string
  • first line assigns the first part to the variable
  • second line operator += takes the string and adds the new string to the end

If you share your name, we can personalize the messages you see.

What is your first name? Eric

Hello, Eric!

End of study session.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *