'automate the boring stuff with python chapter 3 practice project
please help me.
for the practice project in chapter 3 of 'automate the boring stuff with python', I made my own code. but it has errors I could not fix.
def collatz(number):
if number == 1:
print('the sequence is done')
elif number % 2 == 0:
print(number / 2)
collatz(number / 2)
else:
print(number * 3 + 1)
collatz(number * 3 + 1)
def begin():
try:
num = int(input("enter an integer: "))
except ValueError:
print("Please enter an integer greater than 1.")
begin()
if not num > 1:
print("Please enter an integer greater than 1.")
begin()
collatz(num)
begin()
running it makes a loop error. I have tried to fix it but I just got stuck on it.
Solution 1:[1]
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
try:
user_input = int(input('Enter a number:\n'))
new_num = collatz(user_input)
while new_num != 1:
new_num = collatz(new_num)
except ValueError:
print('Please enter an integer')
It says to print and return, so you don't need to use recursion. Here's how I did the program. I also used a while loop to repeat the process until a certain condition was met (until the value was 1).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
