0

I'm making a simple Rock, Paper, Scissor game. As you can see in the code snippet, the program asks the user if they want to play best out of 3 or 5.

If the input is 'five', '5' or 'cinco' the function best_out_of_five() executes (which prints '5555555' to console for now). Similarly, an input of 'three', '3', or 'tres' prints '3333333'

My problem is that whatever input is read, it just executes the best_out_of_five() function (even if the input is 'three'). I thought the if, elif and else would be the easiest part of my code since I have done it many times before, but I must be missing something that I just can't notice.

import time

    def best_out_of_three():
        print('333333333')

    def best_out_of_five():
        print('555555555')

    name = input("Hi, what's your name?\n")
    print('Alright %s, lets play a quick game of Rock, Paper,'
          'Scissors. Do you want to play best out of 3 or 5?' % name)
    game_type = input().lower()
    if game_type in ['five', '5', 'cinco']:
        best_out_of_five()
    elif game_type in ['three', '3', 'tres']:
        best_out_of_three()
    else:
        print("That is not a valid answer. Try again later.")
        time.sleep(5)
        exit()
mindink
  • 25
  • 4
rez
  • 77
  • 1
  • 8

3 Answers3

1

Included this in edit, but your if check should check all options. One way to do that quickly is to use a list:

if game_type in ['five', '5', 'cinco']:
        best_out_of_five()
    elif game_type in ['three', '3', 'tres']:
        best_out_of_three()

If your input is in the list (a linear check against all values in the list), then it will return true.

mindink
  • 25
  • 4
0

The conditionals are not correct. '5' is just a string and when used as a conditional it will evaluate as true while the string '' will be false. Therefore what you essentially have is

game_type == "five" or true or true:

This will always be true. Try

game_type == "five" or game_type == "5" or game_type == "cinco":
Massey101
  • 346
  • 1
  • 9
0

This is a common mistake. What you need is

if game_type == "five" or game_type == '5' or game_type == 'cinco':

or operates on boolean expressions, and does not distribute across ==. To oversimplify the evaluation, I'll just say that most expressions evaluate as True; there are a few exceptions, such as False, 0, None.

In particular, '5' comes across as True. When you say

if game_type == "five" or '5'

this must be True.

Prune
  • 76,765
  • 14
  • 60
  • 81