keep asking the user for a number until the user enters the number 42 in python

You can use a while loop and conditional statements to keep asking the user for a number until they enter the number 42. Here's an example code snippet to do this:

main.py
while True:
    num = input("Enter a number: ")
    if int(num) == 42:
        print("You entered 42!")
        break
118 chars
6 lines

In this code, we use a while loop with a condition of True, which means the loop will continue indefinitely until we use the break keyword to exit the loop. Within the loop, we use the input() function to prompt the user to enter a number, and store their input in a variable called num. We then use the int() function to convert their input to an integer, and check if it equals 42 using a conditional statement (if int(num) == 42). If it does, we print a message telling the user they entered 42, and then use the break keyword to exit the loop. If their input is not 42, the loop continues to prompt the user for more input until they enter 42.

gistlibby LogSnag