-1

I am going through book automate boring stuff with python and trying to solve the practical problems. In this project I need to define collatz() function and print results as seen in code until it gets 1. So basically i need to input only one number and program should return numbers until it returns 1. Program works fine but i have one question if i can make it better :D .

My question is after using try: and except: is there a way to not end process when typing string in input function but to get message below 'You must enter number' and get back to inputing new number or string and executing while loop normally. Code works fine just wondering if this is possible and if so how?

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



try:
    yourNumber = int(input('Enter number: '))
    while True:
        yourNumber = collatz(yourNumber)
        if yourNumber == 1:
            break

except ValueError:
    print('You must enter a number')
spiro10
  • 19
  • 4
  • 2
    Put the call to `input` inside the loop. – Scott Hunter Jun 03 '20 at 00:31
  • Thing is program should only take one input at the beginning and then run on its own until it returns 1. If i put input function inside while loop it will ask me to enter number every time after one result. – spiro10 Jun 03 '20 at 00:40

1 Answers1

1

Put the try/except inside a loop, such that on the except the loop will continue but on a success it will break:

while True:
    try:
        yourNumber = int(input('Enter number: '))
    except ValueError:
        print('You must enter a number')
    else:
        break

while yourNumber != 1:
    yourNumber = collatz(yourNumber)
Samwise
  • 68,105
  • 3
  • 30
  • 44
  • Thanks, i didn't know u can pair try:, except: and else: . Everyday u learn something new :D – spiro10 Jun 03 '20 at 00:50
  • You can also do this by putting the `break` right under `yourNumber` (inside the `try`), since then it'll only happen if the `except` isn't triggered, but I think it *looks* nicer to have the terminating condition go at the end of the loop rather than in the middle. :) – Samwise Jun 03 '20 at 02:31