Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Newbie question
#1
I am trying to answer one of the questions in Automate the Boring Stuff with Python. The function (which seems to work correctly) should retun x if an even number and 3*x+1 if an odd number. I am then trying to call the function with a user given integer, calling the function until it gives the answer 1 and then ending the process. When I run it I keep getting the same number (which I think is the return value of the first function call) repeated indefinitely. Can you please tell me where I am going wrong, I suspect it is something to do with scoping rules, but don't know what.

def collatz(x):
    if x%2==0:
        return x
    else:
        return x*3+1
y=int(input("Enter a number\n"))
while True:
    y=collatz(y)
    print(y)
    if y==1:
        break
Reply
#2
you want line 6 to be after line 7 (i.e. you want to get user input in the loop)
Although it will work, you may want to use different variable names for user input and value returned by collaz function

EDIT: or maybe I don't understand correctly? Check what the required output should be when even number. I have some recollections if x is even it should return x/2....
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Seems the mistake is not my code which works, but that it should have been x/2 as you said for even in your post. It was of course repeating the first even number it came across in my version. Oops! I've changed return x to return x/2 and it works fine.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How is pandas modifying all rows in an assignment - python-newbie question markm74 1 653 Nov-28-2023, 10:36 PM
Last Post: deanhystad
  newbie question - can't make code work tronic72 2 626 Oct-22-2023, 09:08 PM
Last Post: tronic72
  Newbie question about switching between files - Python/Pycharm Busby222 3 543 Oct-15-2023, 03:16 PM
Last Post: deanhystad
  Newbie.... run for cover. OpenCV question Stevolution2023 2 921 Apr-12-2023, 12:57 PM
Last Post: Stevolution2023
  numpy newbie question bcwilly_ca 4 1,127 Feb-10-2023, 05:55 PM
Last Post: jefsummers
  Question from complete python's newbie Davicom 3 2,304 Jun-09-2021, 06:09 PM
Last Post: bowlofred
  Newbie question about running Python via GUI on OSX ejwjohn 8 3,446 Feb-05-2021, 03:20 PM
Last Post: Larz60+
  super newbie question: escape character tsavoSG 3 2,397 Jan-13-2021, 04:31 AM
Last Post: tsavoSG
  newbie question....importing a created class ridgerunnersjw 5 2,570 Oct-01-2020, 07:59 PM
Last Post: ridgerunnersjw
  Dumb newbie question JonEdward 5 3,181 Jul-22-2020, 10:06 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020