[英]How can i stop my python program from crashing
I wrote a program to calculate the factorial of a number all work perfectly but crashes when for test I enter a float number. 我编写了一个程序来计算数字的阶乘,它们都可以正常运行,但是在测试中输入浮点数时崩溃。 My goal is for a floating number to be accepted but not calculated. 我的目标是要接受但不计算浮点数。 As the program will accept but return something like "Bad entry, only integers are accepted." 程序将接受但返回诸如“错误输入,仅接受整数”之类的信息。 I have tried multiple statement but it only work for the number I put in the statement. 我已经尝试了多个语句,但是它仅适用于我在语句中输入的数字。 So I thought maybe something should be built, maybe by naming some floats and doing some sort of subtraction. 所以我认为也许应该建立一些东西,也许是通过命名一些浮点数并进行某种减法来实现的。 But I get lost. 但是我迷路了。 here is the program I have so far without the floating statement included: 这是我到目前为止没有包含浮动语句的程序:
def main():
# take input from the user
num = int(input("Enter a number: "))
factorial = 1
if num > 100:
print("Bad entry. It should be an integer less than or equal to 100!")
print("Please try again: ")
elif num == 0:
print("The factorial of 0 is 1")
elif num < 0:
print("Bad entry. It should be an integer superior than or equal to 0!")
print("Please try again: ")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
main()
You should use a try/catch block, since int('3.2')
(or any other float string) will raise an error. 您应该使用try / catch块,因为int('3.2')
(或任何其他浮点字符串)将引发错误。 For example: 例如:
try: num = int(input('Enter a number...'))
except ValueError:
print 'We only accept integers.'
return
As many have suggested, you should use a try/except
block. 正如许多建议所建议的,您应该使用try/except
块。 However if you want to accept user input like "6.12"
and just calculate from the integer part, you should do: 但是,如果要接受"6.12"
类的用户输入并仅从整数部分进行计算,则应该执行以下操作:
user_in = "6.12" # or whatever the result from the input(...) call is
user_in = int(float(user_in)) # 6
int
cannot operate on a string that's not integer-like, but it CAN operate on a floating point number. int
不能对非整数形式的字符串进行运算,但是可以对浮点数进行运算。 Calling float
on the string will give you a floating point number, and calling int
on that floating point number will return the integer part. 在字符串上调用float
将为您提供一个浮点数,而在该浮点数上调用int
将返回整数部分。
def main():
# take input from the user
num = float(input("Enter a number: "))
if (num%1 != 0):
print("Bad entry, only integers are accepted.")
return
num = int(num)
factorial = 1
if num > 100:
print("Bad entry. It should be an integer less than or equal to 100!")
print("Please try again: ")
elif num == 0:
print("The factorial of 0 is 1")
elif num < 0:
print("Bad entry. It should be an integer superior than or equal to 0!")
print("Please try again: ")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.