在整数用户输入中打印消息而不是valuerror吗? [英] Printing message rather than valuerror in an integer user input?
问题描述
我有一个十进制到二进制的转换器,如下所示:
I have a decimal to binary converter as seen below:
print ("Welcome to August's decimal to binary converter.")
while True:
value = int(input("Please enter enter a positive integer to be converted to binary."))
invertedbinary = []
initialvalue = value
while value >= 1:
value = (value/2)
invertedbinary.append(value)
value = int(value)
for n,i in enumerate(invertedbinary):
if (round(i) == i):
invertedbinary[n]=0
else:
invertedbinary[n]=1
invertedbinary.reverse()
result = ''.join(str(e) for e in invertedbinary)
print ("Decimal Value:\t" , initialvalue)
print ("Binary Value:\t", result)
用户输入立即声明为整数,因此输入的数字以外的任何内容都会终止程序并返回ValueError
.我该如何打印消息而不是用ValueError
结尾的程序?
The user input is immediately declared as an integer so anything other than numbers entered terminates the program and returns a ValueError
. How can I make it so a message is printed instead of the program terminating with a ValueError
?
我尝试采用从二进制到十进制转换器使用的方法:
I tried taking the method I used from my binary to decimal converter:
for i in value:
if not (i in "1234567890"):
我很快意识到这是行不通的,因为value
是整数而不是字符串.我以为我可以将用户输入保留为默认字符串,然后再将其转换为int
,但是我觉得这是一种懒惰而粗糙的方式.
Which I soon realised won't work as value
is an integer rather than a string. I was thinking that I could leave the user input at the default string and then later convert it to int
but I feel like this is the lazy and crude way.
但是,我是否认为我在用户输入行之后尝试添加的任何内容将不起作用,因为程序会在到达该行之前终止?
However, am I right in thinking that anything I try to add after the user input line will not work because the program will terminate before it gets to that line?
还有其他建议吗?
推荐答案
在这些情况下,我认为最被认为是 Pythonic 的方式是在try/中换行以获取异常捕获(或尝试/除外)并在出现ValueError
异常时显示正确的消息:
What I believe is considered the most Pythonic way in these cases is wrap the line where you might get the exception in a try/catch (or try/except) and show a proper message if you get a ValueError
exception:
print ("Welcome to August's decimal to binary converter.")
while True:
try:
value = int(input("Please enter enter a positive integer to be converted to binary."))
except ValueError:
print("Please, enter a valid number")
# Now here, you could do a sys.exit(1), or return... The way this code currently
# works is that it will continue asking the user for numbers
continue
您拥有的另一个选项(但是比处理异常要慢得多)不是使用立即转换为int
而是使用 continue
语句).
Another option you have (but is much slower than handling the exception) is, instead of converting to int
immediatly, checking whether the input string is a number using the str.isdigit()
method of the strings and skip the loop (using the continue
statement) if it's not.
while True:
value = input("Please enter enter a positive integer to be converted to binary.")
if not value.isdigit():
print("Please, enter a valid number")
continue
value = int(value)
这篇关于在整数用户输入中打印消息而不是valuerror吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!