Home Python Course #14: User Input
Post
Cancel

Python Course #14: User Input

Now that you know how to use for and while loops in Python, you can start getting input from outside of your program. In this article, you will learn how to capture a user’s input and build a small calculator in Python.

Python input()

Python provides a straightforward way to get input from a user with the input(...) function. When input(...) is called, the execution of your program is suspended until the user enters something on the command line and presses Enter. The characters entered before the user pressed Enter are returned as a string. The input(...) function takes one argument as a string: the prompt printed on the command line. The following calls input(...) and then returns the string entered by the user (which is, in this case, you):

1
2
3
if __name__ == "__main__":
    s = input("Please insert your text > ")
    print(s)

On the command line, the output of the program looks like this:

1
2
Please insert your text > Hello!
Hello!

Making a Simple Calculator with Python

Before implementing the calculation part of the calculator, you first need a menu where the user can choose what they want to do. The menu resides inside an infinite while loop where a command is requested from the user in each iteration. The entered command is then compared in several if/elif blocks to carry out the corresponding action. In the beginning, there are only two commands, h for help that prints out all available commands and x, which closes the calculator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if __name__ == "__main__":
    while True:
        command = input("Command [h for help] > ")

        if command == "h":
            print("Available Commands:")
            print("  h: display this help menu")
            print("  x: quit")

        elif command == "x":
            break

        else:
            print("unrecognized command!")

    print("Good bye!")

When the command x is entered break is called, leading to leaving the infinite while loop and ending the program because there is only a “Good bye!” print statement after the while loop. Within the while loop, there is also an else whose code is executed if the command entered by the was not recognized.

With the menu setup, you can start adding the first calculation command. For this example, you will implement the + operation. The + operation uses + as a command and then reads two numbers from the command line, adds them together, and prints the result on the command line. The following code extends the menu with a + operation:

1
2
3
4
5
6
7
8
9
10
11
12
        [...]
        if command == "h":
            print("Available Commands:")
            print("  +: add two numbers")
            print("  h: display this help menu")
            print("  x: quit")

        elif command == "+":
            a = input("first  number > ")
            b = input("second number > ")
            print(a, "+", b, "=", a+b)
        [...]

However, if you run the code, you will notice something odd with the result of the addition:

1
2
3
4
Command [h for help] > +
first  number > 23
second number > 42
23 + 42 = 2342

The sum of 23 and 42 is not 2342. It is 65. This is because the numbers entered are returned as strigs from input(...), and the + operation is defined as the concatenation (a fancy word for gluing strings together) when two strings are involved. The issue to solve here is converting a string into an int. Luckily, Python strings already offer a function that checks if the string is composed of numbers only. With .isdigit(), you can check if a string only contains numbers.

1
2
3
>>> s = "123"
>>> s.isdigit()
True

Now you can use .isdigit() to check if the user input is a number and then use an int cast to turn the string into an int. If the user input is not a number, you can prevent the program from crashing by stopping the current iteration of the while loop and start over again:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
        [...]
        elif command == "+":
            a = input("first  number > ")

            if a.isdigit():
                a = int(a)
            else:
                print(a, "is not a number!")
                continue

            b = input("second number > ")

            if b.isdigit():
                b = int(b)
            else:
                print(b, "is not a number!")
                continue

            print(a, "+", b, "=", a+b)
        [...]

In the code above, you can see that for each input a and b, it is checked if they are a number, and if that is the case, they are cast into an int. When one of the inputs is not a number, an error message is printed, and continue is used to stop the current iteration.

When you run the calculator now, it will return the correct result:

1
2
3
4
Command [h for help] > +
first  number > 23
second number > 42
23 + 42 = 65

Here you can find the complete code for the calculator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
if __name__ == "__main__":
    while True:
        command = input("Command [h for help] > ")

        if command == "h":
            print("Available Commands:")
            print("  +: add two numbers")
            print("  h: display this help menu")
            print("  x: quit")

        elif command == "+":
            a = input("first  number > ")

            if a.isdigit():
                a = int(a)
            else:
                print(a, "is not a number!")
                continue

            b = input("second number > ")

            if b.isdigit():
                b = int(b)
            else:
                print(b, "is not a number!")
                continue

            print(a, "+", b, "=", a+b)

        elif command == "x":
            print("Good bye!")
            break

        else:
            print("unrecognized command!")

I encourage you to add a sum function to this calculator that adds an arbitrary amount of numbers together. Make sure to get the free Python Cheat Sheets in my Gumroad shop. If you have any questions about this article, feel free to join our Discord community to ask them over there.

This post is licensed under CC BY 4.0 by the author.