In: Computer Science
Exercise 2. Automate the boring stuff, page 77, Input Validation. Add try and except statements to the previous project to detect whether the user types in a noninteger string. Normally, the int() function will raise a ValueError error if it is passed a noninteger string, as in int('puppy'). In the except clause, print a message to the user saying they must enter an integer.
THis is the previous project
#function definition def collatzSequence(number): # if number % 2 == 0: print((number) // 2) return number // 2 else: nextNumber = 3*(number)+1 print(nextNumber) return nextNumber n = input("Please input an integer: ") while n != 1: n = collatzSequence(int(n))
SOURCE CODE:
*Please follow the comments to better understand the code.
**Please look at the Screenshot below and use this code to copy-paste.
***The code in the below screenshot is neatly indented for better understanding.
#function definition
def collatzSequence(number):
#
if number % 2 == 0:
print((number) // 2)
return number // 2
else:
nextNumber = 3*(number)+1
print(nextNumber)
return nextNumber
while True:
n = input("Please input an integer: ")
try:
n=int(n)
break
except:
print('INVALID.. Please Enter an Integer.')
while n != 1:
n = collatzSequence(int(n))
==========================
SCREENSHOT: