python - 尝试从 while 循环返回 python 中的正确整数?

标签 python while-loop

我已经尝试解决这个问题有一段时间了,但我似乎仍然无法理解!我试图返回并打印用户输入的正确行数和列数(当用户输入大于或等于5时),当用户未输入时,再次提示输入语句。

这是迄今为止我的代码:

#CONSTANTS 
CON_NUM = int(5)

def correctInteger(row):
    #get valid row number:  
    while row < CON_NUM:
        row = int(input("Please enter a number bigger than or equal to 5: "))
        if row >= CON_NUM:
            return(row)
    if row >= CON_NUM:
        return(row)

def correctNum(cols):
    #get valid column number:  
    while cols < CON_NUM:
        cols = int(input("Enter a number bigger than / equal to 5: "))
        if cols >= CON_NUM:
            return(cols)
    if cols >= CON_NUM:
        return(cols)

def main():
    #ask for number of rows:
    print("Choose the number of rows:")
    rows = int(input("Please enter a number bigger/ equal to 5: "))

    #ask for columns:
    print("Please choose the number of columns:")
    columns = int(input("Please enter a number bigger/ equal to 5: "))
    validRow = correctInteger(rows)
    validColumn = correctNum(columns)
    print(validRow)
    print(validColumn)

main()

这是该代码的输出:

Please choose the number of rows:
Please enter a number bigger/equal to 5: 3
Please choose the number of columns:
Please enter a number bigger/equal to 5: 5
Please enter a number bigger/equal to 5: 6
6
5

输出很奇怪,我不知道如何修复它!我不知道为什么行数的 while 循环不起作用,它只打印列。

我试图获得的输出可能类似于:

Please choose the number of rows:
Please enter a number bigger/equal to 5: 4
Please enter a number bigger/equal to 5: 5
Please choose the number of columns:
Please enter a number bigger/equal to 5: 3
Please enter a number bigger/equal to 5: 7
5
7

(顶部数字是行,底部数字是列)

我知道这很长,但我希望我说得有道理!感谢您的宝贵时间!

最佳答案

与@Prune的答案类似,但处理非数字条目的结构略有不同。您有共同的要求,因此将其分解并创建一个函数来进行验证,例如询问():

# ask for a number at least as big as n
def ask(n):
    while True:
        try:
            i = int(input("Please enter a number bigger than or equal to {}: ".format(n)))
            if i >= n:
                return i
        except ValueError:
            pass

def main():                                                                     
    #ask for number of rows:                                                                  
    print("Choose the number of rows:")
    rows = ask(5)

    #ask for columns:                                                               
    print("Please choose the number of columns:")
    columns = ask(5)
    ...

关于python - 尝试从 while 循环返回 python 中的正确整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40600518/

相关文章:

python - 变量不返回。赋值前引用

linux - while循环出错?脚本

python - 有没有办法杀死一个线程?

python - Django 如何在 Amazon S3 中存储 HTML 文件

Python 守护进程死掉

Java-在while循环中递减变量并打印列表

java - while (sc.hasNext) 循环 java

python - 我的代码未按 python 3 中的 try 和 except 函数的预期运行

python - Cassandra:文件 "cqlsh",第 95 行,除了 ImportError,e:

linux - 虽然 shell 脚本中的循环说 [ : too many arguments