下面解释了getvalidint函数,因为我调用函数getvalidint并给它一个输入,因此它可能产生一个整数输出。这不是因为我打印函数输出(见下面的主程序)它打印出“无”,我在python33上运行。
#getValidInt() takes in a minn and maxx, and gets a number from the
# user between those two numbers (inclusive)
#Input: minn and maxx, two integers
#Output: an integer, between minn and maxx inclusive
MIN_VAL = -1000000
MAX_VAL = 1000000
def getValidInt(minn, maxx):
message = "Please enter a number between " + str(minn) + " and " + \
str(maxx) + " (inclusive): "
newInt = int(input(message))
while newInt <= minn & newInt >= maxx:
# while loop exited, return the user's choice
return newInt
def main():
userNum = getValidInt(MIN_VAL, MAX_VAL)
print(userNum)
main()
答案 0 :(得分:2)
如果永远不会满足while newInt <= minn & newInt >= maxx:
条件,则不会返回任何内容。这意味着该函数将隐式返回None
。另外,假设您正在使用python 3(我从int(input())
成语中引出)。
更深层次的问题是输入代码只会运行一次,无论该值是否满足约束条件。这样做的典型方式是:
import sys
def get_int(minimum=-100000, maximum=100000):
user_input = float("inf")
while user_input > maximum or user_input < minimum:
try:
user_input = int(input("Enter a number between {} and {}: ".format(minimum, maximum)))
except ValueError:
sys.stdout.write("Invalid number. ")
return user_input