简体   繁体   English

Python 中的这个 try/except 块有什么问题?

[英]What's wrong with this try/ except block in Python?

    try:
        user_name = str(input("Enter your full name: "))
    except:
        print("Enter a string")

    user_age = int(input("Enter your age: "))
    user_country = str(input("Enter the country you live in: "))
    user_postcode = str(input("Enter your postcode: "))

When I enter an integer for the first one it moves on to the next variable but I want it to say "Enter a string"当我为第一个输入一个整数时,它会移动到下一个变量,但我希望它说“输入一个字符串”

Any input is already a string.任何输入都已经是一个字符串。 When you read an integer (such as 123), the input comes as a string (such as "123").当您读取一个整数(例如 123)时,输入是一个字符串(例如“123”)。 Casting it to str does nothing.将它转换为str什么都不做。 You need to be far more specific about what you expect as input, and test for that .你需要了解你所期望的输入,并测试远远更具体。

For instance, you might want to determine that all characters are in a particular set -- such as letters, spaces, and certain punctuation marks.例如,您可能想要确定所有字符都在一个特定的集合中——例如字母、空格和某些标点符号。 Then you'd need to write a particular test or two for those characteristics.然后,您需要针对这些特征编写一两个特定的测试。

I think you want to test if there is a number in the name: You could do something like this:我想您想测试名称中是否有数字:您可以执行以下操作:

while True:
    user_name = str(input("Enter your full name: "))
    if [i for i in list(user_name) if i.isdigit()]:
        print("invalid input")
    else:
        break

Or maybe better check that all inputs are letters in the alphabet:或者也许更好地检查所有输入都是字母表中的字母:

alphabet = list("abcdefghijklmnopqrstuvwxyz")

while True:
    errors = 0

    user_name = str(input("Enter your full name: "))
    for i in user_name.split(" "):
        for ii in i:
            if ii not in alphabet:
                errors += 1

    if errors:
        print("You have {} errors".format(errors))
    else:
        break

The return type of input is always an instance of str . input的返回类型始终是str一个实例。 Even if the user enters what appears to be a number the result is still a string containing the number.即使用户输入的似乎是数字,结果仍然是包含数字的字符串。 eg if they enter 5 , it is still given to you as the string '5' .例如,如果他们输入5 ,它仍然作为字符串'5'提供给您。

So instead what you need to do is to check to see if it is an integer.因此,您需要做的是检查它是否是整数。

eg例如

user_name = input("Enter your full name: ")
try:
    int(user_name)
except ValueError:
    pass
else:
    print("Enter a string")

The above code first reads the input into a variable, this will always be a string.上面的代码首先将输入读入一个变量,这将始终是一个字符串。 It then tries to convert it to an integer with the int() method.然后它尝试使用int()方法将其转换为整数。 If that conversion fails (which is what we want).如果转换失败(这是我们想要的)。 We just carry on as normal (using pass ).我们只是照常进行(使用pass )。 Otherwise it will hit the else and print our your message.否则它会点击else并打印我们的消息。

The except -part of try-except only run if what's inside the try -part throws an error.except的双组分尝试-除了里面有什么是唯一运行,如果try -part抛出一个错误。

An example is divisibility by zero.一个例子是被零整除。 The following code will throw an error when trying to run it in the python shell;下面的代码在 python shell 中尝试运行时会抛出错误;

print(5/0)

You can catch this error, and print your own message instead of the python shell printing its own.您可以捕获此错误,并打印您自己的消息而不是 python shell 打印自己的消息。 In this case ZeroDivisionError is the certain type of error python will throw.在这种情况下ZeroDivisionError是 python 将抛出的某种类型的错误。 With the following code, python will just catch that error, and not any other.使用以下代码,python 只会捕获该错误,而不会捕获任何其他错误。

try:
     print(5/0)
except ZeroDivisionError:
     print("Cannot divide by zero")

If you want to catch all errors, you simply just write except instead of except zeroDivisionError .如果您想捕获所有错误,只需编写except而不是except zeroDivisionError

The code inside the except -block don't run because there is no error when trying to run what's inside the try -block. except -block 中的代码不会运行,因为在尝试运行try -block 中的内容时没有错误。 What is happening inside the try-block is simply assigning an input to a variable. try 块中发生的事情只是将输入分配给变量。 There is no error throwed for this line, and thus the except -block don't run.该行没有抛出错误,因此except -block 不会运行。

There are different ways to get the functionality you want.有多种方法可以获得您想要的功能。 You probably want to repeat that the input needs to be a string, until the user actually enters a string.您可能想重复输入必须是字符串,直到用户实际输入字符串。 You can do just that with a while -loop.你可以用一个while循环来做到这一点。 The specific error that is thrown if string to integer conversion fails is ValueError .如果字符串到整数转换失败,则抛出的特定错误是ValueError

isString = False
while not isString:
      userInput = input("Enter here: ")

      try:
           int(userInput)
      except ValueError:
           # if string to integer fails, the input is a string
           isString = True
      else:
            print("Please enter a string")

The while loop above runs as long as isString is False .只要isStringFalse上面的 while 循环就会运行。 First we try to convert from string to integer.首先,我们尝试将字符串转换为整数。 If this throws an error, the input is a string, therefore we're setting the isString to True , and the while-loop will not run anymore.如果这引发错误,则输入是一个字符串,因此我们将 isString 设置为True ,while 循环将不再运行。 If the conversion is sucessfull, it implies that the input is actually an integer, and thus the else-statement will run, printing that the user needs to enter a string.如果转换成功,则意味着输入实际上是一个整数,因此 else 语句将运行,打印用户需要输入一个字符串。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM