0

您好,我试图让我的输入只允许整数,一旦超过 10,它就会显示错误,任何帮助将不胜感激。

square_ct = input("Enter an integer from 1-5 the number of squares to draw: ")
triangle_ct = input("Enter an integer from 1-5 the number of triangles to draw: ")

while square_count(input) > 10:
    print ("Error!")
    square_count=input() #the statement reappears

while triangle_count(input) > 10:
    print ("Error!")
    triangle_count=input() #the statement reappears
4

2 回答 2

3

我首选的技术是使用while True带中断的循环:

while True:
    square_ct = input("Enter an integer from 1-5 the number of squares to draw: ")
    if square_ct <= 10: break
    print "Error"

# use square_ct as normal

或者,在 Python 3 上:

while True:
    square_ct = int(input("Enter an integer from 1-5 the number of squares to draw: "))
    if square_ct <= 10: break
    print("Error")

# use square_ct as normal
于 2012-09-16T00:18:24.093 回答
0

我选择了nneonneo提供的路径,并且非常接近我想要的。最终结果如下。

我感谢大家的意见。上一次我做任何有点像编程的事情是在 IBM 360 上的 Fortran 穿孔卡上。

我很抱歉提出这样的基本问题,但我真的很努力。

有效但实际上并没有准确指出发生了哪个错误的代码。我将尝试弄清楚如何将输入语句中的字符串转换为浮点数,看看是否有余数(可能是模数?),以便用户更好地提示出了什么问题。

import math
from datetime import datetime
import time

num = 0
start = 0
end = 0

try:
   num = int(input('Enter a positive whole number: '))
   if (num >= 0 and num <= 2147483647):
       start = datetime.now()
       print("The factorial of ", num, " is : ")
       print(math.factorial(int(num)))
       end = datetime.now()
   else:
      print('Number must be between 0 and 2147483647 are allowed.')
      print(f"Time taken in (hh:mm:ss.ms) is {end - start}")
except ValueError:
    print('Text or decimal numbers are not allowed. Please enter a whole number between 0 and 2147483647')

我有很多东西要学,因为我很无聊...

诺曼

于 2021-11-24T01:56:32.360 回答