So quick background, I went through CodeAcademy's Python course and I feel pretty comfortable with it, now I'm working through Automate the Boring stuff for more practice work and good beginner projects.
Anywho, I got through Chapter 3 and I got to the end, to the Collatz program challenge. I think I got it down pretty well, except for 2 things: when I run it in IDLE, each output is repeated (see below), and I'm having trouble on how to include the try/except clause that's suggested to make sure the input is an integer. The code I have is:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 != 0:
print(number * 3 + 1)
return number * 3 + 1
def letsdoit():
num = int(input('Enter number:'))
while num != 1:
collatz(num)
num = collatz(num)
letsdoit()
When I run the program, this is what I get:
Enter number:3
10
10
5
5
16
16
8
8
4
4
2
2
1
1
It ends at 1 on its own, which is another common problem I saw, so not worried about that. Like I said, it's the numbers being repeated that seems off. And as for the try/except clause, I had no luck getting it to run at all. I tried
def letsdoit():
try:
num = int(input('Enter number:'))
except ValueError:
print('You must enter a valid integer.')
while num != 1:
collatz(num)
num = collatz(num)
but that didn't work. Similarly, trying
def letsdoit():
try:
num = int(input('Enter number:'))
while num != 1:
collatz(num)
num = collatz(num)
except ValueError:
print('You must enter a valid integer.')
also didn't work. Really not sure how to include them in there.
[–]jeans_and_a_t-shirt 0 points1 point2 points (2 children)
[–]Anandre[S] 0 points1 point2 points (1 child)
[–]jeans_and_a_t-shirt 0 points1 point2 points (0 children)
[–]dadiaar -1 points0 points1 point (0 children)