Using the Input Function as an Argument in Another Function (Python)

I am playing around with Python trying to learn the basics, and as a short test, I wrote the following code:

import random

def random_number():
    return int(random.randint(0, 10))

def lottery(input):
    num = random_number()
    while num != input:
        print(num, "Not yet...")
        num = random_number()
    else:
        print(num, "We have a winner!")

lottery(4)

This code works as expected in the console, but I thought it would be interesting to allow a user to enter a number using the input() method, so I changed the function call to the following:

lottery(input("Pick a number between 0 and 10: "))

The result was that the while loop ran indefinitely, crashing the console. I was wondering if anyone had any thoughts as to why, and how to correctly use the input() function as an argument in a function (or, how to write the above code to use the input() function in general).

Thank you very much!

input() always returns str type, even if entered is just number, to compare it with the result of random.randint(), it needs to be changed first to int. After setting up the type conversion, you also may try to handle case when somebody wouldn’t enter a number.

Some other general comments:

  • As input is a build-in function it’s best to avoid using it as a function parameter (def lottery(input)) or variable name.
  • random.randint() on the other hand doesn’t need the type conversion to int, as it will always return int.
  • As you have found out there’s can be else after the while loop. Keep in mind that code within such else block will be executed only when while loop ends normally - when it’s condition ends up as false. If you’d be using break statement to break out of the loop, the code in the else block would not be called.

Thank you very much!

I’ll be sure to keep the types of returned values in mind in the future.

1 Like