【发布时间】:2020-08-09 08:11:42
【问题描述】:
开发者和工程师们您好:
我该如何处理这两种类型的输入1)当用户输入“-0”和2)当用户输入减号“-”时,在我的while 循环用于添加非负整数。
程序在整体设计中开发了一些功能,就是添加非负整数,但是当用户输入-0或-(减号)符号时它有一个缺陷。当用户输入这些条目时,我想打印('你输入了一个负整数或负/减号')。
目前,当用户在输入中提交-0时程序继续运行而不添加,当用户仅提交-符号时出现ValueError。
请提供反馈。
entry = 0
sum = 0
# Request input from the user
print('This is nonnegative integer addition program. \n',)
while entry >= 0:
entry=int(input('Please enter numbers to add: '))
if entry >=0:
sum+=entry
elif entry<0 or str(entry[0])=='-' or str(entry)=='-0': # -0 nor (first index -(minus) does not work
print('You have entered a negative integer or symbol:', \
entry, ', therefore you have been exited out of the program')
print('total integer input sum =',sum)
【问题讨论】:
-
你可以通过省略一堆前锋来解决这个问题,关于你读到的,这个问题很有趣。等等等等。并说出为什么它不起作用。 stackoverflow.com/help/how-to-ask
-
你需要检查输入的字符串是否有
"-0",然后才能将其转换为整数并正常处理。 -
感谢马特,更新后的描述。
-
为什么需要将
'-'和'-0'分开?两者都属于entry[0] == '-'...如果您发现自己在尝试解析字符串时遇到了太多条件,您可以考虑使用正则表达式...
标签: python-3.x