Python中的Else语句工作不正常

2024-04-25 09:16:36 发布

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

我想知道是否有人能帮我修复最后一个带有错误消息的else语句。如果我输入任何不是YyNn的东西,它就会工作,但是,如果我输入YyNn,错误消息仍然会显示。我整晚都在努力,我觉得我错过了一个显而易见的答案——但这让我发疯了。希望能有个解决办法。非常感谢。你知道吗

import random
score = 0

def rollAllDice():
   values=random.randint(1,6), random.randint(1,6), random.randint(1,6), random.randint(1,6), random.randint(1,6)
   print("You rolled 5 dice. The values are:")
   print("Die 1:", values[0]) 
   print("Die 2:", values[1]) 
   print("Die 3:", values[2]) 
   print("Die 4:", values[3]) 
   print("Die 5:", values[4])
   return values
myDice=rollAllDice()

def allSame(myDice):
    result = myDice[0] == myDice[1] and myDice[0] == myDice[2] and myDice[0] == myDice[3] and myDice[0] == myDice[4]
    len(set(myDice)) == 1
    return result

def diceReroll(myDice):
   if allSame(myDice):
      if keepDie1[0] in 'YyNn':
         die1 = random.randint(1,6)
      elif keepDie2[1] in 'YyNn':
         die2 = random.randint(1,6)
      elif keepDie3[2] in 'YyNn':
         die3 = random.randint(1,6)
      elif keepDie4[3] in 'YyNn':
         die4 = random.randint(1,6)
      elif keepDie5[4] in 'YyNn':
         die5 = random.randint(1,6)
   else: # < ---- the else statement I need help on.
      print("I'm sorry. Please only enter Y or N.")

keepDie1=input("\nWould you like to reroll die 1? [Y/N]: ")
keepDie2=input("Would you like to reroll die 2? [Y/N]: ")
keepDie3=input("Would you like to reroll die 3? [Y/N]: ")
keepDie4=input("Would you like to reroll die 4? [Y/N]: ")
keepDie5=input("Would you like to reroll die 5? [Y/N]: ")
diceReroll(myDice)

Tags: toinyouinputrandomlikevaluesprint
2条回答

@Simas的出色回应。你知道吗

我只想指出的是,你永远不能重新推出任何东西,除非所有5个骰子是相同的。原因是在allSame中使用的是逻辑and运算符。根据定义,所有条件都必须为true才能返回true。因此,如果你得到1假,它返回假。所以在diceReroll中,第一个if条件的值总是false。也许这就是你想要的,但是你不应该问用户是否想要重新滚动任何东西,如果是这样的话。通过将and更改为or,您将得到这样的行为:只有当第一个骰子至少等于另一个骰子时,骰子重新滚动才会起作用。(不确定len(set(mydice)) == 1用于什么…它似乎是一个布尔语句,但没有通过andor连接到上一个语句)

对于当前的if-elif结构,只有第一个有“Y”的骰子将被重新滚动,因为在它计算它之后,它会忽略其余的骰子。因此,这可能更适合作为一系列if语句。另外,所有的keepDiex都需要在括号中有0,否则您会得到一个超出界限的索引。你知道吗

def diceReroll(myDice):
    if allSame(myDice):
        if keepDie1[0] is 'Y':
            die1 = random.randint(1, 6)
            print(die1)
        if keepDie2[0] is 'Y':
            die2 = random.randint(1, 6)
            print(die2)
       if keepDie3[0]is 'Y':
            die3 = random.randint(1, 6)
            print(die3)
       if keepDie4[0] is 'Y':
            die4 = random.randint(1, 6)
            print(die4)
       if keepDie5[0] is 'Y':
            die5 = random.randint(1, 6)
            print(die5)

I took the liberty to make a few assumptions about your code. If you think I went too far, let me know in the comments and I will refractor the answer according to your needs.

if/else循环的基本问题是缩进(其他人在注释中已经提到)。但我认为出现这个问题的真正原因在于代码的结构。因此,我建议您进行两个更改,以隔离用户输入并删除有问题的if/else子句。你知道吗

首先,您正在验证骰子滚动逻辑中的输入,因此有了if/else循环:

if allSame(myDice):
      if keepDie1[0] in 'YyNn':
         die1 = random.randint(1,6)
      elif keepDie2[1] in 'YyNn':
         die2 = random.randint(1,6)
      elif keepDie3[2] in 'YyNn':
         die3 = random.randint(1,6)
      elif keepDie4[3] in 'YyNn':
         die4 = random.randint(1,6)
      elif keepDie5[4] in 'YyNn':
         die5 = random.randint(1,6)
   else: # <    the else statement I need help on.
      print("I'm sorry. Please only enter Y or N.")

正如@Selcuk所指出的,这里的else部分严重缩进,导致您收到错误消息。此函数已包含您的应用程序逻辑,它根本不应处理用户输入验证。

我建议您将用户输入部分重写为一个单独的函数(对用户提示消息的更改称为f字符串)。你不懂的话可以查一下):

def diceRerollPrompt(diceNumber):
    while True:
        prompt = input(f'Would you like to reroll die {diceNumber}? [Y/N]: ').upper()
        if prompt in 'YN':
            return prompt
        else:
            print("I'm sorry. Please only enter Y or N.")

keepDie1=diceRerollPrompt(1)
keepDie2=diceRerollPrompt(2)
keepDie3=diceRerollPrompt(3)
keepDie4=diceRerollPrompt(4)
keepDie5=diceRerollPrompt(5)

This piece of code would repeatedly ask the user to input characters until our user enters yYn or N. It ensures that if the user makes a mistake, the user is immediately telegraphed that his/her input is wrong. You also isolate your code from bad input very early on and not need to write heavy validation in the business logic greatly simplifying your allSame() function. Win-win for you and the user.

之后,您只需删除有问题的if/else循环,并更改diceReroll函数,如下所示:

def diceReroll(myDice):
   if allSame(myDice):
      if keepDie is 'Y':
         die1 = random.randint(1,6)
      elif keepDie2 is 'Y':
         die2 = random.randint(1,6)
      elif keepDie3 is 'Y':
         die3 = random.randint(1,6)
      elif keepDie4 is 'Y':
         die4 = random.randint(1,6)
      elif keepDie5 is 'Y':
         die5 = random.randint(1,6)

Note that I took the liberty to change the YyNn to just Y as you would not want to reroll the dice if the user said NO, right?

下面的完整解决方案

import random
score = 0

def rollAllDice():
   values=random.randint(1,6), random.randint(1,6), random.randint(1,6), random.randint(1,6), random.randint(1,6)
   print("You rolled 5 dice. The values are:")
   print("Die 1:", values[0]) 
   print("Die 2:", values[1]) 
   print("Die 3:", values[2]) 
   print("Die 4:", values[3]) 
   print("Die 5:", values[4])
   return values
myDice=rollAllDice()

def allSame(myDice):
    result = myDice[0] == myDice[1] and myDice[0] == myDice[2] and myDice[0] == myDice[3] and myDice[0] == myDice[4]
    len(set(myDice)) == 1
    return result

def diceReroll(myDice):
   if allSame(myDice):
      if keepDie1 is 'Y':
         die1 = random.randint(1,6)
      elif keepDie2 is 'Y':
         die2 = random.randint(1,6)
      elif keepDie3 is 'Y':
         die3 = random.randint(1,6)
      elif keepDie4 is 'Y':
         die4 = random.randint(1,6)
      elif keepDie5 is 'Y':
         die5 = random.randint(1,6)

def diceRerollPrompt(diceNumber):
    while True:
        # if you want to use the simple string concatenation:
        # prompt = input('Would you like to reroll die ' + diceNumber +'? [Y/N]: ').upper()
        prompt = input(f'Would you like to reroll die {diceNumber}? [Y/N]: ').upper()
        if prompt in 'YN':
            return prompt
        else:
            print("I'm sorry. Please only enter Y or N.")

keepDie1=diceRerollPrompt(1)
keepDie2=diceRerollPrompt(2)
keepDie3=diceRerollPrompt(3)
keepDie4=diceRerollPrompt(4)
keepDie5=diceRerollPrompt(5)
diceReroll(myDice)

'''

相关问题 更多 >