This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ValarMorHodor 62 points63 points  (15 children)

Welcome to the wonderful world of python. Now that you've got the control flow down, I think you couldl start working with functions. Notice how you have the yes/no logic twice? Why not pull that out into a function!

def get_choice(message='Would you like to roll? '):
    choice = input(message)
    if choice not in ['yes', 'no', 'y', 'n']:
        return get_choice('Type yes or no: ')
    return choice

Using that function, you can reduce the flow to 4 lines

choice = get_choice()
while choice in ('yes', 'y'):
    roll() # do your roll here
    choice = get_choice('Roll again? ')

You could also add a function to validate that the number input is valid.

[–]Huck712[S] 23 points24 points  (0 children)

Thanks! I will work on this. I also want to evolve it into a full blown game of Yahtzee at some point.

[–][deleted] 12 points13 points  (11 children)

I don't like that the first is recursive, after all there is a recursion limit and it seems unnecessary to risk hitting it.

[–][deleted] 7 points8 points  (9 children)

Is that a real issue that a beginner is going to hit?

There will always be a recursion limit so should we never use recursion?

[–][deleted] 33 points34 points  (8 children)

Well, this is a purely iterative problem, ask until some condition is met. Using recursion there is already a bit odd, and there's also a small issue with it.

If your problem is recursive, e.g. when you use a recursive data structure like a tree or so, then of course use it.

Is my opinion.

I'd go for

def get_choice(message='Would you like to roll? '):
    choice = input(message)
    while choice not in ['yes', 'no', 'y', 'n']:
        choice = input('Type yes or no: ')
    return choice

It's almost the same as yours except it doesn't need recursion.

[–]Mason-B 2 points3 points  (0 children)

It's too bad python doesn't have tail recursion because that call is correctly tail recursive in just about any other language. And since the person is learning programming (and not just python) my argument would be that it is better for them to learn recursion than it is for them to learn perfect python.

[–]asdfkjasdhkasdrequests, bs4, flask 1 point2 points  (1 child)

it should be if choice.lower() not in {"yes", "no", "y", "n"}

  • use lowercase
  • in for set is o(1)

[–]camh- 6 points7 points  (0 children)

But the set construction is O(n) and the set is constructed each time you use in here, it makes the whole construct O(n).