如果条件为假,如何打破循环?

2024-10-02 18:24:19 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的程序中,我希望输出所有小于10000的数字(例如,如果我将数字154乘以2,它应该只返回小于10000的值)。然而,在我的程序中,我仍然得到一个大于10000的值。有人能帮我吗

这是我的节目:

import statistics

def verdoppeln(zahl):
    liste = []
    if zahl > 10000:
            print("Zahl nicht gültig.")
    else:
        print(zahl)
        while zahl < 10000:
            print(zahl * 2)
            zahl_neu = zahl * 2
            liste.append(zahl_neu)
            zahl = zahl_neu
            if zahl > 10000:
                print("Zur Kontrolle: Summe = ", sum(liste), "Anzahl: ", len(liste))
                print("Mittelwert: ", statistics.mean(liste))
        

verdoppeln(154)


Tags: import程序ifdef数字节目printstatistics
3条回答

不间断的替代方案:

import statistics

def verdoppeln(zahl):
    liste = []
    if zahl > 10000:
            print("Zahl nicht gultig.")
    else:
        print(zahl)
        zahl *= 2
        while zahl < 10000:
            print(zahl)
            liste.append(zahl)
            zahl *= 2            
        print("Zur Kontrolle: Summe = ", sum(liste), "Anzahl: ", len(liste))
        print("Mittelwert: ", statistics.mean(liste))
        
verdoppeln(154)

问题是while-检查只在每个循环的开始处进行。因此,如果zahl大于10000zahl * 2之后,它仍将被打印并添加到liste。如果将while终止条件更改为True,并在zahl的值大于10000时使用break-语句从内部中断while循环,则应该会得到所需的结果

另外,不需要使用zahl_neu,您可以只使用zahl,这样就可以了

试试这个:

import statistics

def verdoppeln(zahl):
    liste = []
    if zahl > 10000:
            print("Zahl nicht gültig.")
    else:
        print(zahl)
        while True: # Changed the termination condition to True, in other words, never stop
            zahl *= 2
            if (zahl >= 10000): # Added termination condition from inside the loop
                break
            print(zahl)
            liste.append(zahl)
        print("Zur Kontrolle: Summe = ", sum(liste), "Anzahl: ", len(liste))
        if (len(liste) >= 1): # statistics.mean need liste to have at least one element
            print("Mittelwert: ", statistics.mean(liste))
        
verdoppeln(154)

这将输出:

154
308
616
1232
2464
4928
9856
Zur Kontrolle: Summe =  19404 Anzahl:  6
Mittelwert:  3234

我认为你需要改变你的限制:

import statistics

def verdoppeln(zahl):
    liste = []
    if zahl >= 5000:
            print("Zahl nicht gültig.")
    else:
        print(zahl)
        while zahl < 5000:
            zahl *= 2
            print(zahl)
            liste.append(zahl)
        print("Zur Kontrolle: Summe = ", sum(liste), "Anzahl: ", len(liste))
        print("Mittelwert: ", statistics.mean(liste))
        

verdoppeln(154)

相关问题 更多 >