如何在这个Python函数中同时使用大小写?

2024-03-28 16:50:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着做upper()lower(),甚至在代码中把Y和N改成小写。如果我输入大写YN就可以了,但是如果我输入小写yn,就会不断出错。有人知道解决办法吗

def patternSum(myDice):
    if allSame(myDice):
       patternPoints=input("\nWould you like to score the pattern points for all different values (25 points)? [Y/N]: ")
       patternPoints.lower()
       if patternPoints == "Y":
          points = 25
          sumDice=input("Would you like to score the sum of the dice (16 points)? [Y/N]: ")
          if sumDice == "Y":
             points = 25 + 16
          if sumDice == "Y":
             points = 16
       elif patternPoints == "N":
          sumDice=input("Would you like to score the sum of the dice (16 points)? [Y/N]: ")
          points = 16
       else:
          print("Please try again by entering Y or N.")
    else:
        points = sum(myDice)
        print( "Your score is now:",patternSum([1,1,1,1,1]),".\n" )

    return points
score = score + patternSum(myDice)

Tags: thetoyouinputiflowerpointslike
2条回答

在您发布的代码中,您将lower()放入并与大写输入进行比较,但是, lower()和upper()函数返回转换后的字符串,它不会改变当前字符串

我已将您的代码更改为:

def patternSum(myDice):
    if allSame(myDice):
       patternPoints=input("\nWould you like to score the pattern points for all different values (25 points)? [Y/N]: ")
       if patternPoints.lower() == "y":
          points = 25
          sumDice=input("Would you like to score the sum of the dice (16 points)? [Y/N]: ")
          if sumDice.upper() == "Y":
             points = 25 + 16
          if sumDice == "Y":
             points = 16
       elif patternPoints.upper() == "n":
          sumDice=input("Would you like to score the sum of the dice (16 points)? [Y/N]: ")
          points = 16
       else:
          print("Please try again by entering Y or N.")
    else:
        points = sum(myDice)
        print( "Your score is now:",patternSum([1,1,1,1,1]),".\n" )

    return points
score = score + patternSum(myDice)

您没有更新变量patternPoints的值

patternPoints.lower()不会更改patternPoints的值

你应该在第四行做patternPoints = patternPoints.upper()

相关问题 更多 >