Lesson 11. Interacting with the user

 

After reading lesson 11, you’ll be able to

  • Print values for the user
  • Ask the user for input
  • Store user input in variables and do operations with it

Many programs are written to do computations behind the scenes, but few of them are useful without some sort of input from a user. One main reason you’d want to write a program is to provide users with a certain experience; that experience relies on a back-and-forth between the user and the program.

Consider this

Find another person and have a conversation. What kinds of questions can you ask? What responses do you get? Can you build upon a specific response you get?

Answer:

  • How are you?
  • Good, looking forward to the weekend.
  • Me too! Any weekend plans?
  • Yes, we’re going camping, then checking out the science museum. If we have time, maybe hit the beach and then going out for a nice dinner. You?
  • Watching TV.

11.1. Showing output

To get started with this lesson, recall that you can use the print() command to show the user values on the console in Python. You’ll use print a lot from now on.

11.1.1. Printing expressions

You can put any expression inside the parentheses of print(), because all expressions evaluate to a value. For example, the float 3.1 has a value 3.1, and the expression 3 * "a" has a value "aaa".

Listing 11.1 shows how to print the values of a few expressions to the user. You can have fairly complex expressions in the parentheses. The code in this listing prints out the following:

11.2. Getting user input

 
 
 

Summary

 
 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage