【问题标题】:Data Structure and Algorithms using Python使用 Python 的数据结构和算法
【发布时间】:2023-01-13 15:45:36
【问题描述】:

字符串可以有任何外壳。 Rock, ROCK, rock 都是可能和有效的。 任何人都可以帮助我的代码接受任何情况,如 rOcK 和所有...?

player1 = input('Enter rock/paper/scissors: ') player2 = input('Enter rock/paper/scissors: ')

if (player1 == player2): print("The game is a Tie") elif (player1 == 'rock' and player2 == 'scissors'): print("player 1 wins") elif (player1 == 'rock' and player2 == 'paper'): print("player 2 wins") elif (player1 == 'paper' and player2 == 'rock'): print("player 1 wins") elif (player1 == 'paper' and player2 == 'scissors'): print("player 2 wins") elif (player1 == 'scissors' and player2 == 'paper'): print("player 1 wins") elif (player1 == 'scissors' and player2 == 'rock'): print("player 2 wins") else: print("Invalid input")

我的代码运行完美,只是不知道如何编码以允许它接受任何情况。

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以在 Python 中使用 string.lower()string.upper(),将字符串转换为小写/大写字母。这样你就可以让你的弦全高或全低,无论你想要什么。

    f.e:如果player1='ROCK'和你比较player1.lower(),你的player1将被评估为rock而不是ROCK

    string.lower()文档:

    lower() 方法将字符串中的所有大写字符转换为小写字符并返回。

    【讨论】:

      【解决方案2】:

      您可以在任何情况下接受输入并将两个输入转换为相同的情况,然后再编写如下条件:

      player1 = input('Enter rock/paper/scissors: ') 
      player2 = input('Enter rock/paper/scissors: ')
      player1 = player1.lower()
      player2 = player2.lower()
      
      # then continue with if cases
      

      【讨论】:

        最近更新 更多