【问题标题】:Validate and restart python for loop if validation is false如果验证为假,则验证并重新启动 python for 循环
【发布时间】:2021-07-12 04:52:46
【问题描述】:

好的,我正在尝试制作 Mastermind 猜色游戏的屏幕版本。这是人对计算机。计算机将随机生成 4 种颜色的数组(来自 5 种预定义颜色的列表)。此选择将对用户隐藏。接下来,用户将一一输入 4 种颜色选择。游戏会通过将颜色与系统颜色数组进行比较来告诉用户颜色是否正确以及位置是否正确。

我不能做的是,如果用户输入的颜色不在预定义列表中,程序应该抛出错误消息Wrong Color! Please try again,并且循环应该从那个点重新开始。

这是我写的代码:

#User Defined Functions
def FetchColor(x):  #Function to take the randomly generated number, match it with color scheme and return the color based on scheme.
    if x <= 10 and x >= 1:
        temp_color = 'Red'
    
    if x <= 20 and x >= 11:
        temp_color = 'Green'

    if x <= 30 and x >= 21:
        temp_color = 'Blue'

    if x <= 40 and x >= 31:
        temp_color = 'Purple'

    if x <= 50 and x >= 41:
        temp_color = 'Yellow'

    return temp_color

def DisplayInfo():
    print()
    print("Please Enter Color: Red, Green, Blue, Purple, Yellow")
    print("NOTE: Colors are case sensitive (Enter Colour with First Letter Capital)")
    print()



#Color Scheme
#1-10 Red
#11-20 Green
#21-30 Blue
#31-40 Purple
#41-50 Yellow

#Introduction 



#System Part

import random

colors = ['','','',''] #Array to store System choosen colors

position = 0
num_guess = 0

for i in range(4):
    temp_color = ''
    temp_int = random.randint(1, 50) #Generate Random Integer
    color = FetchColor(temp_int) #Fetch the Color From Pre-Defined Scheme In the Function

    colors[position] = color #Add Generated Colors To Color Array
    position = position + 1 #increase position to edit next value

#print(colors)  #Uncomment this line when the game is in testing mode. This line will print the system choosen colors before executing the user part


#User Part

user_colors = ['','','',''] #Array to store colors user guess
DisplayInfo()

while user_colors != colors:
    user_colors = ['','','',''] #This ensures that array is empty if user is retrying. Otherwise there will be an outofbound exception.
    position2 = 0

    for z in range(4):
        usr_color = input('Guess The Color: ') #input color from user
        user_colors[position2] = usr_color #saving user color into a separate array
        position2 = position2 + 1



    print()
    print()

    #Result Engine

    user_c = 0
    user_c2 = 0
    

    for c in range(4):
        if user_colors[user_c] in colors: #Validate if the Color Entered is in the System Generated Color Array
            print('Color is Correct ' + user_colors[user_c] ) #Print the result
            user_c = user_c + 1
            found = True
        else:
            print('Color is incorrect.') #Print incorrect if color not in the systen array
            user_c = user_c + 1


    print()
    print()

    for v in range(4):
        if user_colors[user_c2] == colors[user_c2]: #Validate if the user input color position matches system color position
            print('Position is Correct for Color ' + user_colors[user_c2]) #print the result
            user_c2 = user_c2 + 1
        else:
            print('Position is incorrect: ', user_c2) #Position is incorrect if not same as system color array
            user_c2 = user_c2 + 1

    num_guess = num_guess + 1
    print()

print()
print('Number of Guess(s) Took You To Win: ', num_guess)

这是我尝试在#userpart 中实现的,但它不起作用。

user_colors = ['','','',''] #Array to store colors user guess
DisplayInfo()

while user_colors != colors:
    user_colors = ['','','',''] #This ensures that array is empty if user is retrying. Otherwise there will be an outofbound exception.
    position2 = 0
    should_restart = True

    while should_restart:
        for z in range(4):
            should_restart = False
            usr_color = input('Guess The Color: ') #input color from user

            if user_colors[position2] in colors:
                print("Wrong Color. Please Try again!")
                should_restart = True
                break

            user_colors[position2] = usr_color #saving user color into a separate array
            position2 = position2 + 1

【问题讨论】:

标签: python python-3.x for-loop


【解决方案1】:

我会通过在循环中调用一个函数并为无效输入情况引发异常来设计它

您还可以使用自定义异常退出或将输入放入异常字符串(允许用户使用Q/q 转义)

def some_test_fuction():
    ...

def main():
    while True:
        try:
            some_test_function()
        except CustomException:  # you could use this to quit
            break  # or simply sys.exit()
        except ValueError:  # try to make the Exception as specific as possible
            print("invalid input")

【讨论】:

    【解决方案2】:

    已解决:

    我只是添加了一个硬编码的预定义颜色数组,例如

    pre_def_colors=['Red','Green','Purple','Yellow','Blue']

    我只是使用了一个带有计数的while循环,如果颜色存在于预定义的列表中,系统将继续前进,但如果没有,系统将显示错误并继续询问:

    #User Part
    
    user_colors = ['','','',''] #Array to store colors user guess
    DisplayInfo()
    
    while user_colors != colors:
        user_colors = ['','','',''] #This ensures that array is empty if user is retrying. Otherwise there will be an outofbound exception.
        position2 = 0
        loop = 0
    
        while loop < 4:
            usr_color = input('Guess The Color: ') #input color from user
    
            if(usr_color in pre_def_colors):
                user_colors[position2] = usr_color #saving user color into a separate array
                position2 = position2 + 1
                loop = loop + 1
            else:
                print('Please enter a valid choice')
                continue
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-17
      • 2014-11-20
      • 1970-01-01
      相关资源
      最近更新 更多