Python triad operator question.

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

import random

def main():
    while 1:
        menu = input("8.Rps ")
        if menu == "0":
            break
        elif menu == "8":
            rps = Quiz08Rps (int("1 : fist 2: scissors 3: cloth \ninput : ")))))
            print(f'user: {rps.user} \nComputer: {rps.com} \nResult: {rps.res()}')
        else:
            print("You have entered it incorrectly.")

def myRandom(start, end):
    return random.randint(start,end)


class Quiz08Rps:
    def __init__(self,user):
        self.user = user
        self.com = myRandom(1,3)
    def res(self):
        if self.user == 1 or 2:
            res = "Draw" if (self.user == self.com) else "Win" if (self.user > (self.com + 1) % 3) else "Lose"
        elif self.user == 3:
            res = "Draw" if (self.user == self.com) else "Win" if (self.user > self.com + 1)else "Lose"
        return res

if __name__ == '__main__':
    main()

I'm going to play rock-paper-scissors with a three-term operator, but when the user is 1 or 2, it runs well without a problem When the value of com is 3, Win for both 1 and 2 No matter how I change it, Win comes out, so which part should I modify?


2022-09-20 11:07

2 Answers

>>> def check_or_condition(user):
    if user == 1 or 2:
        print(f"expectation : user is 1 or 2")
        print(f"user actually is {user}")
    else:
        print("this block can't happen")


>>> for user in range(1, 5):
    check_or_condition(user)


expectation : user is 1 or 2
user actually is 1
expectation : user is 1 or 2
user actually is 2
expectation : user is 1 or 2
user actually is 3
expectation : user is 1 or 2
user actually is 4
>>> def check_or_condition(user):
    if (user == 1) or (user == 2):
        print(f"expectation : user is 1 or 2")
        print(f"user actually is {user}")
    else:
        print("user not 1 nor 2")
        print(f"user actually is {user}")


>>> for user in range(1, 5):
    check_or_condition(user)


expectation : user is 1 or 2
user actually is 1
expectation : user is 1 or 2
user actually is 2
user not 1 nor 2
user actually is 3
user not 1 nor 2
user actually is 4

The code that determines victory or defeat is written in one line with two three-term operators appears to be because of poor readability. Even if it is slightly longer, it is better to make it easier for others to read.The other person here includes himself a year later.


2022-09-20 11:07

If you have any answers or tips


© 2022 pinfo. All rights reserved.