3.4. How the input() functions works

The input() function pauses your program and waits for the user to enter some text. Once Python receives the user's input, it assigns that input to a variable.

The text "Write something: " inside the input is called the instruction.

Writing Clear Instructions

Each time you use the input() function, you should include an easy-to-follow instruction. See the example.

Sometimes you'll want to write a longer instruction. See the example.

This example shows one way to build a multi-line string. The operator += takes the string that was assigned to instruction and adds the new string onto the end.

Using int() to Accept Numerical Input

When you use the input() function, every input will be seen as a string. To input an integer, you can use the int() function, which tells Python to interpret the input as a numerical value. Try to delete line 2 in the example and see what will happen:

> The program can compare age because age = int(age) change the input value to a numerical value before the comparison is made.

The modulo operator

One useful tool when working with numbers is the modulo operator (%). This operator divide one number by another number then returns the remainder:

When one number is divisible by another number, the remainder is 0, so the modulo operator always returns 0. Module operator frequently use to tell even or odd number.

In the example, even numbers are always divisible by two, so if the modulo of a number and two is zero (here, if number % 2 == 0) the number is even. Otherwise, it's odd.

Exercise 3.4

  1. Rental Car
    Write a program that asks:
    What kind of rental car you would like?
    Then print,
    Let me see if I can find you a {car name in titlecase}.

  2. Seat in a Car
    Write a program that asks:
    Specify the number of seats in your car.
    If the answer is more than eight, print a message:
    Unfortunately, you have to wait for a week.
    Otherwise,
    Your car is ready soon.

  3. Multiples of Ten
    Ask the user
    How many miles are you planning to use this car? (Write in a multiple of 10)
    Then, if the number is a multiple of 10 write
    Thank you, we will process your request.
    Otherwise,
    Your miles request will be rounded to the nearest multiple of 10. Thank you, we will process your request.