简体   繁体   English

如何在条件满足时退出While循环

[英]How to exit out of While loop is condition meet

I have a infinite loop need to exit the script if condition meets and print my expected output如果条件满足并打印我预期的 output,我有一个无限循环需要退出脚本

Code:代码:

import random

stud=[0,0]
studnme = ['a','b']

while (stud[0] !=50 or stud[1] !=50):
    if flag = 0:
        lucky_draw = random.randint(1,6)
        stud_marks = stud[0] + lucky_draw
        stud[0]    = stud[0] + lucky_draw  
        flag=1 
    else:
        lucky_draw = random.randint(1,6)
        stud_marks = stud[1] + lucky_draw
        stud[0]    = stud[1] + lucky_draw  
        flag=0         

Output: Output:

Student 'a' You have reached : 50
Student 'b' You have reached : 34

Need to print who as highest points需要打印谁是最高分

The values you're testing to exit the loop are incremented by random values, so they're not guaranteed to hit 50 exactly.您要测试以退出循环的值会按随机值递增,因此不能保证它们正好达到 50。 Make the loop run while those values are less than 50.当这些值小于 50 时使循环运行。

while (stud[0] < 50 and stud[1] < 50):

import random

stud=[0,0]
studnme = ['a','b']
flag=0
while (stud[0] <=50 or stud[1] <=50):
    if flag == 0:
        lucky_draw = random.randint(1,6)
        stud_marks = stud[0] + lucky_draw
        stud[0]    = stud[0] + lucky_draw  
        flag=1 
    else:
        lucky_draw = random.randint(1,6)
        stud_marks = stud[1] + lucky_draw
        stud[1]    = stud[1] + lucky_draw  
        flag=0      
print(f'Student a you have reached :{stud[0]}')
print(f'Student b you have reached :{stud[1]}')

First of all you have not defined the flag, so set it to 0 or 1 and also the condition that you have kept should be a little changed, that is as any of the student has marks greater than 50 the program should terminate.首先,您没有定义标志,因此将其设置为 0 或 1,并且您保留的条件也应该稍微改变一下,即任何学生的分数大于 50 程序应该终止。 Please check the above code.请检查上面的代码。

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

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