Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # collatz Python exercise
- # Mike Kerry Dec 2020
- def collatz(number):
- if not number & 1: # bit-wise test for even
- return number >> 1 # >> 1 integer divides by 2
- return 3 * number + 1 # number was odd
- while True:
- mystr = input("Type a number: ") # input as a string
- if mystr.isdigit(): # if the input is an integer ...
- break # break out of while loop
- print("Invalid number, try again") # report invalid input and loop again
- y = int(mystr) # convert input string to an integer
- while y != 1: # Keep looping until y is 1
- y = collatz(y) # pass y to the function, and assign the return value to y
- print(y) # print y each time around loop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement