-1

I am completely new to python and I just completed the first python project in the book. However, I am trying to improve my code so that the program will continue running until the user enters a valid integer. Currently if a user provides an input that's not an integer, the program just says 'Please enter an integer' and exits. How do I achieve this? I have been trying for hours but is still unable to get to a conclusion.

#! python3

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

try:
    givenNumber = int(input('Enter a number: '))
    while givenNumber != 1:
        givenNumber = collatz(givenNumber)
except ValueError:
    print('Please enter an integer.')
  • 1
    I think the problem is the control flow. Your "try" and "except" are not inside the loop, so the "except" part can only happen once. – user54038 Sep 26 '20 at 19:51

2 Answers2

1

You can wrap your logic inside a while loop:

while True:
    try:
        givenNumber = int(input('Enter a number: '))
        # break here if condition True
        
    except ValueError:
        print('Please enter an integer.')
Shivam Jha
  • 3,160
  • 3
  • 22
  • 36
0

I'm not sure it related to python programming specific, but try to learn from the exampls as this one:

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

givenNumber = None
while not isinstance(givenNumber,int):
    givenNumber = input('Enter a number: ')
    try:
        givenNumber = int(givenNumber)
    except ValueError:
        print("this is not an integer number")
givenNumber = collatz(givenNumber)

output for example:

Enter a number: 3.2
this is not an integer number
Enter a number: 2
1
Yossi Levi
  • 1,258
  • 1
  • 4
  • 7