0

I am currently working on a Yahtzee game written in Python 3.5. I have defined a function that asks the user to type in the names of the people who will be playing, before checking if this is correct.

def get_player_names():

   while True:
      print("Who are playing today? ")

      players = [str(x) for x in input().split()]

      n = len(players)

      if n == 1:
          for p in players:
              print("So", p, "is playing alone today.")

          choice = input("Is this correct?(y/n)\n")

          if choice == "y" or "Y":
              break
          elif choice == "n" or "N":
              continue
          else:
              print("You should enter either y/Y or n/N")
              continue

      elif n > 1:
          print("So today, ", n, " people are playing, and their names are: ")

          for p in players:
              print(p)

          choice = input("Is this correct?(y/n)\n")

          if choice == "y" or "Y":
              break
          elif choice == "n" or "N":
              continue
          else:
              print("You should enter either y/Y or n/N")
              continue

      else:
          print("Sorry, but at least one person has to participate")
          continue

  placeholder()


def placeholder():
  print("KTITENS")

get_player_names()

The program creates the list of players without a problem, as well as when the user confirm that the names of the players are correct, at which point the loop breaks and the next function is called. (Which is currently just a function that prints KITTENS. The problem is that if the user enters "n"/"N" or something else, I would like the loop to repeat, but it breaks instead.

Hopefully someone can assist me! Apologies if this question is a duplicate, but I couldn't find a similar question concerning Python 3.

MechMayhem
  • 75
  • 7

2 Answers2

4

The problem are those lines :

if choice == "y" or "Y":
    break
elif choice == "n" or "N":
    # Some stuff

Which should be :

if choice == "y" or choice == "Y":
    break
elif choice == "n" or choice == "N":
    # Some stuff

Indeed, or "Y" is always true, hence the break is always called.

You can check this by typing this in your python console :

>>> if 'randomstring': print('Yup, this is True')
Yup, this is True
3kt
  • 2,543
  • 1
  • 17
  • 29
2

Change

if choice == "y" or "Y":
          break
      elif choice == "n" or "N":
          continue

to

if choice == "y" or choice =="Y":
          break
      elif choice == "n" or choice =="N":
          continue

'Y' is a non empty string and therefore bool('Y') is always True

You can read here about Truth Value Testing

Ofir
  • 5,049
  • 5
  • 36
  • 61
  • This worked nicely, thank you very much. Two answer got posted with a minute's difference and had the same solution, so I checked the other answer as the solution, but still thanks! – MechMayhem Jun 02 '16 at 15:48