2016-11-11 27 views
0

你好hullo! 我正在研究计算输入分数并输出分数百分比和字母分数的程序。虽然字母分级部分非常简单,但我无法使while循环正确完成。 目前,我试图通过让用户只输入0到10之间的整数来添加一个输入陷阱。问题是,只要用户输入必要的输入,它就会循环并返回输出`“请输入一个整数。“连续循环虽然变量不是一个整数

print ("Enter the homework scores one at a time. Type \"done\" when finished.") 
hwCount = 1 
strScore = input ("HW#" + str (hwCount) + " score: ") 
while (strScore != int and strScore != "done") or\ 
     (strScore == int and (strScore < 0 or strScore >10)): 
     if strScore == int: 
      input = int (input ("Please enter a number between 0 and 10.")) 
     else: 
     print ("Please enter only whole numbers.") 
     #End if 
     strScore = float (input ("enter HW#" + str(hwCount) + " score: 

所以,我可能会觉得很愚蠢,一旦我知道了这一点,但我很难过。算法的溶液状态 循环while(strScore不是整数和strScore!= “完成”)或 (strScore是整数,(strScore < 0或strScore> 10)))

提前感谢!

+3

你绝对应该看看Python风格指南[PEP 8](https://www.python.org/dev/peps/pep-0008/)。 – brianpck

+0

1)'input'值总是一个字符串。 2)如果您想比较类型,请使用'type(strScore)'。 –

回答

1

strScore != int不测试值是否为整数;它会检查该值是否等于int类型。在这种情况下,您需要not isinstance(strScore, int)

但是,您应该尽量避免进行直接类型检查。重要的是,值表现为像浮动一样的

print("Enter the homework scores one at a time. Type \"done\" when finished.") 
hwCount = 1 
while True: 
    strScore = input("HW#{} score: ".format(hwCount)) 
    if strScore == "done": 
     break 
    try: 
     score = float(strScore) 
    except ValueError: 
     print("{} is not a valid score, please try again".format(strScore)) 
     continue 

    if not (0 <= score <= 10): 
     print("Please enter a value between 1 and 10") 
     continue 

    # Work with the validated value of score 
    # ... 
    hwCount += 1 
+0

感谢您的帮助!有没有一种方法可以写出不使用While True格式的文件? –

+0

这是一个常见的Python成语。假设一个循环是无限的,在适当的时候断开,而不是试图在退出条件下适应所有的逻辑。当你有代码(比如'input(“HW#1 score:”)')“时,它应该至少执行一次*,这有助于保证你将进入循环。 – chepner