满足条件时如何停止循环?

时间:2020-08-16 08:05:53

标签: python loops

我是尝试使用python的编码的完全新手。在编写一个简单的程序来计算年龄时,无论如何努力,我似乎​​都无法解决。该代码粘贴在下面。该程序将在我输入未来的一年时运行,但是当使用了过去的一年时,代码会再次循环询问该年份是否正确。任何帮助表示赞赏。

sort -k4nr unix.txt | grep -e 'admin' | awk '{ if ((NR >= 2) && (FNR == 2)) {print $1,$2} else if (NR < 2) {print "No Sufficient Records in the file"}}'


Getting output like this:
No Sufficient Records in the file
Harry Manager

The contents of unix.txt file is as follows
Name Designation Department Salary
Sheetal Clerk Admin 12000
tarun peon sales 15000
Rahul HR aCCounts 20000
Deepak Clerk admin 23000
Ajay manager Admin 45000
amit manager ACCOUNTS 47000
varun manager sales 50000
satvik director purchase 80000
Raju Engineer admin 40000
Harry Manager admin 35000

2 个答案:

答案 0 :(得分:1)

尝试

...
   if future_age > 0:

        print(future_age)
        return

    else:

        print('do you really want to go back in time?, enter "yes" or "no"')
...

答案 1 :(得分:1)

在这种情况下,您的函数只需要包含一个具有适当条件的while循环,然后就无需中断循环或进行任何递归调用。

def process():
    if future_age > 0:
        print(future_age)
    else:
        print('do you really want to go back in time?, enter "yes" or "no"')
        answer = None
        while answer not in ('yes', 'no'):
            answer = input()
            if answer == 'yes':
                print(future_age)
            elif answer == 'no':
                print('cya')