Home > Blockchain >  Python: How can i compare a User-Input-String in an if-Statement?
Python: How can i compare a User-Input-String in an if-Statement?

Time:06-02

i know this question may sound stupid, but i´m having problems to check/compare Strings in an if-Statement.

I´m new to Python and we need to make a little project for our school work in python. I decided to do "Rock, Paper, Scissors" as an Console Application.

The Problem i am facing, is that i can´t really compare the User-Input with strings in an if-Statement. I already tried different versions for ex.

Benutzerwahl = input("Wähle aus: Schere, Stein, Papier:")
if not Benutzerwahl == "Schere" or Benutzerwahl == "Stein" or Benutzerwahl == "Papier":
    print ("\n")
    print ("Wrong Input, please type in again!")
    print ("\n")
    continue

But when i execute the Program and type in for ex. "Papier" (engl. paper) it goes in the if-Statement for some reason, also for every other word i type in.

Am i missing something or what is the Problem?

Here is the whole Code:

while (1<2):
    Benutzerwahl = input("Wähle aus: Schere, Stein, Papier:")
    if Benutzerwahl != "Schere" or Benutzerwahl != "Stein" or Benutzerwahl != "Papier":
        print ("\n")
        print ("Falsche Eingabe, bitte richtig eintragen")
        print ("\n")
        continue

    print ('Du hast gewählt: ')   Benutzerwahl
    Wahloptionen = ['Schere', 'Stein', 'Papier']
    GegnerWahl = random.choice(Wahloptionen)
    print ('Ich habe gewählt: ')   GegnerWahl

    if GegnerWahl == Benutzerwahl:
        print ('Unentschieden')
    elif GegnerWahl == 'Schere' and Benutzerwahl == 'Papier':
        print('Schere schneidet Papier! Ich habe gewonnen!')
        continue
    elif GegnerWahl == 'Stein' and Benutzerwahl == 'Schere':
        print('Stein schlägt Schere! Ich habe gewonnen!')
        continue
    elif GegnerWahl == 'Papier' and Benutzerwahl == 'Stein':
        print('Papier schlägt Stein! Ich habe gewonnen')
        continue
    else:
        print('Du hast gewonnen!')

CodePudding user response:

Your condition is always true, because only one of the inequalities can be false at the same time. So false or true or true => true.

You should use and instead of or.

Even better, you could check whether the input is part of a set:

if Benutzerwahl not in {"Schere", "Stein", "Papier"}:
   ...

CodePudding user response:

use "and" instead of "or" "or" will be true as long as one of your checks is true

  • Related