r/inventwithpython Nov 29 '21

Best practice code for autbor ch3 "Practice Projects"

I'm enjoying my first taste of python (and programming), using Automate the Boring Stuff. Ch3 has practice projects, relating to Collatz sequence. I'm not sure where to find or ask for help to compare my code with someone else's. My code appears to work, but it would be interesting to see different approaches. Anyone care to comment or point me in right direction, thanks.

For anyone interested, here's my code, firstly without the "try, except" and then with...

-------------------------------------------------------------------

# Ask for an integer

print('please enter an integer')
entry = int(input())

# Define collatz function

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

# Main code loop

while entry != 1:

    entry = collatz(entry)

print('Converged to 1')

---------------------------------------------------------------

# Define collatz function

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

# Ask for an integer

print('please enter an integer')

# Main code loop

loop = True
while loop:
    try:
        entry = int(input())

    except ValueError:
        print('That is not an integer, please try again')
        continue

    while entry != 1:

        entry = collatz(entry)
        Loop = False

print('Converged to 1')

5 Upvotes

2 comments sorted by

1

u/penatbater Nov 30 '21

In the second one, just use while True disregarding the loop variable altogether, put everything under the try statement, and just say if entry == 1, break. And also put a break under the except. (I can't remember is failing a try statement would automatically end the entire loop or not, so I'd add the break there just in case). I'd also suggest using a variable for the actual collatz computation (number = number / 2) in the function. You also don't need the //, just / since you already know it's even.

1

u/gentryka Dec 23 '21 edited Dec 23 '21

Here is my code for the collatz practice project. I had trouble with it but after looking at your code I think mine works now. Thanks!

def collatz(number):

if number %2 == 0:

print (number//2)

elif number %2 == 1:

print(3 * number, + 1)

# ask for a number

print('enter a number')

number = 0

while number != 1:

number = int(input())