如何检查用户的输入是否为字符串python3 [英] How to check if user's input is a string python3

查看:280
本文介绍了如何检查用户的输入是否为字符串python3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

那么,如果输入是字符串,那么如果你试图检查某人的输入怎么办?但是,只要在语句中捕获异常,变量的值就会被删除。你不能再打印了。你如何捕捉异常并仍然打印输入的值。

i希望你得到我说的话





so, what if you are trying to check someone's input if the input is a string or not. BUT whenever you catch an exception in the statement the value of the variable gets deleted. and you can't print it anymore. how can you catch a exception and still print the VALUE of the input.
i hope you got what i said


try:
    someValue =int(input('> '))
except ValueError:
    print(someValue)









错误是:





The error is:

NameError: name 'someValue' is not defined





我尝试过:



尝试使用sys.stdin .read,sys.stdin.readline

和许多其他东西



What I have tried:

trying sys.stdin.read, sys.stdin.readline
and many other things

推荐答案

你不能使用 someValue 除了语句之外,是因为如果输入except块,它永远不会被创建。 someValue 将包含已解析的整数,但如果您无法进行解析,则变量赋值将永远不会发生。所以变量被删除是假的,变量永远不会被创建将是一个正确的陈述。



试试这个:

You can't use someValue in the except statement, because it would never be created if you enter the except block. someValue would contain the parsed integer, but if you can't do the parsing, the variable assignment will never happen. So "the variable gets deleted" is false, "the variable never gets created" would be a correct statement.

Try this instead:
user_input = input('> ')
try:
    some_value = int(user_input)
except ValueError:
    print(user_input)


这篇关于如何检查用户的输入是否为字符串python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆