简体   繁体   English

函数不产生整数,而是产生“无”输出

[英]Function is not producing an integer, but instead producing a “none” output

The getvalidint function is explained below, as I am calling the function getvalidint and giving it a input so it may produce an integer output. 下面说明了getvalidint函数,因为我正在调用函数getvalidint并为其提供输入,因此它可能会产生整数输出。 It is not as I print the functions output(see below in the main program) it prints out "none", I am running on python33. 不是因为我打印了函数输出(请参见主程序中的以下内容),而是“无”打印,所以我正在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()

If the while newInt <= minn & newInt >= maxx: condition is never met, then nothing will be returned. 如果while newInt <= minn & newInt >= maxx:条件从不满足,则不会返回任何内容。 This means that the function will implicitly return None . 这意味着该函数将隐式返回None Also, assuming you're using python 3 (which I induced from your int(input()) idiom). 另外,假设您使用的是python 3(我是从您的int(input())习惯用法中得出的)。

The deeper issue is that the input code will only run once, regardless of whether or not the value meets the constraint. 更深层的问题是,无论值是否满足约束,输入代码将只运行一次。 The typical way of doing this would be something along the lines of: 执行此操作的典型方式可能是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM