简体   繁体   English

我应该如何在我的 for 循环中添加 Try & except Block 来处理

[英]How should I add Try & except Block to handle in my for loop

        # This is a guess the number game.
        import random

        print ('Hello, What is your name?')
        name = input()

        print('Well, ' + name + '! I am thinking of a number between 1 to 20.') 
        secretNumber = random.randint(1,20)
        print('Debug:' + str(secretNumber))

        for guessTaken in range (1,7):
            print('Take a guess. '+ name +'!' )
            guess =int(input())


            if guess<secretNumber:
                print('Your guess is too low')
            elif guess>secretNumber:
                print('Your guess is too high')
            else:
                break # This is for correct guess is equal.

        if guess ==secretNumber:
            print('Good Job, ' +name+ '! You guess my number in ' + str(guessTaken)+ ' guesses!')
        else:
            print('Nope, The number I was thinking of was ' +str(secretNumber))

Hi my fellow super coders,嗨,我的超级程序员伙伴们,

So I am trying to put Try and Except block in this program, I try it putting just after guess=int(input()) unfortunately i am not able to make it work.所以我试图在这个程序中放置 Try 和 except 块,我尝试将它放在 guess=int(input()) 之后,不幸的是我无法让它工作。

So i am trying to handle the ValueError, So lets say user needs to input Integers (Numbers), If he types string like , "One","Six" etc. the program crashes.所以我正在尝试处理 ValueError,所以假设用户需要输入整数(数字),如果他输入像“一”、“六”等字符串,程序就会崩溃。 I want to handle this case.我想处理这个案子。 Please can some help me out.请帮我一下。 :) :)

Thank You so much.太感谢了。 Cobra眼镜蛇

How about this, it re asks if the user inputs a string:这个怎么样,它重新询问用户是否输入了一个字符串:

        # This is a guess the number game.
        import random

        print ('Hello, What is your name?')
        name = input()

        print('Well, ' + name + '! I am thinking of a number between 1 to 20.') 
        secretNumber = random.randint(1,20)
        print('Debug:' + str(secretNumber))

        for guessTaken in range (1,7):
            print('Take a guess. '+ name +'!' )
            try:
               guess =int(input())
            except:
               print("Must be a number, try again: ")
               continue

            if guess<secretNumber:
                print('Your guess is too low')
            elif guess>secretNumber:
                print('Your guess is too high')
            else:
                break # This is for correct guess is equal.

        if guess ==secretNumber:
            print('Good Job, ' +name+ '! You guess my number in ' + str(guessTaken)+ ' guesses!')
        else:
            print('Nope, The number I was thinking of was ' +str(secretNumber))

If the user enters something that is not a number python will skip to the exception because an error will occur, I added some text to the prints to clarify the rules of the game.如果用户输入的内容不是数字,python 将跳到异常,因为会发生错误,我在打印件中添加了一些文本以阐明游戏规则。 I used else after for loop which is very useful sometimes for the case where the user can't guess the number in 7 tries you can test it and see that even though the else is not after the if, when the if guess==secretNumber is true and you break the loop the else statement is not doing anything.我在 for 循环之后使用了 else 有时对于用户无法在 7 次尝试中猜出数字的情况非常有用,您可以测试它并查看即使 else 不在 if 之后,当 if guess==secretNumber是真的,你打破了循环 else 语句没有做任何事情。 PS still new to answering here so please give feedback about my answer PS在这里回答还很陌生,所以请对我的回答提供反馈

import random

print ('Hello, What is your name?')
name = input()

print('Well, ' + name + '! I am thinking of a number between 1 to 20.') 
secretNumber = random.randint(1,20)
print('Debug:' + str(secretNumber))

for guessTaken in range (1,7):
    print('Take a guess. '+ name +'!, You Have 7 tries'  )
    try:
        guess = int(input())
        if guess<secretNumber :
            print('Your guess is too low')
        elif guess>secretNumber : 
            print('Your guess is too high')
        if guess == secretNumber:
            print('Good Job, ' + name + '! You guess my number in ' + str(guessTaken)+ ' guesses!')
            break # This is for correct guess is equal.
    except:
        print('Please Enter A number ' + name + 'and not anything else' )


else:
    print('Nope, The number I was thinking of was ' +str(secretNumber))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我应该在try-except块中添加else语句来处理return语句吗? - Should I add an else statement to try-except block to handle the return statement? 我怎样才能让我的for循环从try和except块中停下来的地方继续呢? Python 3 - How can i make my for loop continue from where it left off in the try and except block? Python 3 如何在try中除了块之外在Python中处理多个相同的错误类型 - How can I handle multiple same Error type in Python in try except block 为什么我的try-except块卡在了循环中? - why is my try- except block stuck in the loop? 如何在具有相同条件的一个 try/except 块中对单个和循环操作进行分组? - How can I group single and loop operations in one try/except block with same condition? 我该如何尝试,除了:阻止此错误? - How do I make a try, except: block for this error? 如何编写捕获所有异常的 `try`/`except` 块? - How can I write a `try`/`except` block that catches all exceptions? 如何在try except块中检查某种类型的OSError? - How do I check for a certain type of OSError in a try except block? 在这种情况下我应该如何插入 try-except - How should I insert try-except in this scenario 除了定义函数外,我应该如何使用try ... - How should I use try…except while defining a function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM