[Solved] how to use a while loop in my python code


You could modify the code from the HandlingExceptions – Python Wiki:

def collatz(number):
    if number % 2 == 0:
        print(number // 2)
        return number // 2
    elif number % 2 == 1:
        print(3 * number + 1)
        return 3 * number + 1

has_input_int_number = False 
while has_input_int_number == False: 
    try: # try to convert user input into a int number 
        x = int(input("Enter a number: "))
        has_input_int_number = True # will only reach this line if the user inputted a int
        while x != 1:
            x = collatz(x)
    except ValueError: # if it gives a ValueError
        print("Error: Please enter a numerical int value.")

Example Usage:

Enter a number:  a
Error: Please enter a numerical int value.
Enter a number:  1.5
Error: Please enter a numerical int value.
Enter a number:  5
16
8
4
2
1

0

solved how to use a while loop in my python code