-1

I'm still learning the basics of python and can't seem to figure out why my simple dice rolling code isn't working properly.

import random

def main():
  num = int(input("How many sides of the die?\n"))
  num_of_rolls = int(input("How many rolls?\n"))
  roll_y_n = input("Are you ready to roll? Y/N\n")
  var = 1

  def dice_roll(num):
    return random.randrange(1,num)

  if roll_y_n.lower() in "yes" or "y":
    while var <= num_of_rolls:
        print("You rolled a " + str(dice_roll(num)) + ".")
        var = var + 1

  else:
    print("Okay, Byeee!")
    exit()

  retry = input("Do you want to go again? Y/N\n")
  if retry.lower() == "yes" or "y":
    main()
  elif retry in "no" or 'n':
    print("Okay, Byeee!")
    exit()
main()

it runs it just fine, but when ever I type in "n" to get it to stop it still runs as if I typed in "y". Sorry if this is a dumb question, I just can't figure it out.

abrooks
  • 13
  • 1
  • You probably don't want recursion here. Consider *while True:* and then *break* when you're done – DarkKnight Feb 03 '22 at 12:27
  • 1
    `roll_y_n.lower() in "yes" or "y"` does something very different than you think. Firstly it is equivalent to `(roll_y_n.lower() in "yes") or "y"` which is `roll_y_n.lower() in "yes" or True` which is `True`. – luk2302 Feb 03 '22 at 12:27
  • Try using a do-while loop instead of recursion. – fractal397 Feb 03 '22 at 12:28

1 Answers1

0

There is lot of syntax error in your code: Use this:

if roll_y_n.lower() in ["yes", "y"]:
    while var <= num_of_rolls:
        print("You rolled a " + str(dice_roll(num)) + ".")
        var = var + 1
if retry.lower() in ["yes","y"]:
    main()
elif retry in ["no", 'n']:
    print("Okay, Byeee!")
    exit()
Prakash Dahal
  • 4,388
  • 2
  • 11
  • 25