简体   繁体   English

Python 2.7仅数字作为输入,出现ValueError问题

[英]Python 2.7 Only numbers as input, the ValueError issue

How do i stop python from giving me an ValueError everytime I put a letter in? 每当我写一封信时,如何阻止python给我一个ValueError? Input must be a number! 输入的必须是数字! Using Python 2.7.3 使用Python 2.7.3

Instead of using input() , use raw_input() , which returns a string. 代替使用input() ,使用raw_input() ,它返回一个字符串。

input() is equivalent to eval(raw_input()) in Python 2.7. input()等效于Python 2.7中的eval(raw_input()) Hence, if you input a letter (let's say 'a' ), it will try look for a variable called 'a' . 因此,如果您输入字母(假设为'a' ),它将尝试查找名为'a'的变量。 If there isn't one, a NameError is raised. 如果没有,则会引发NameError

if you're working with numbers, then you can always call int() on the input received by using raw_input() . 如果您正在处理数字,则始终可以使用raw_input()在收到的输入上调用int() raw_input() You could also use a try: except: structure to catch any ValueErrors incase the input is not a number. 如果输入不是数字,也可以使用try: except:结构来捕获任何ValueErrors

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

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