Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Python - How to convert this while loop to for loop?

percentNumbers = [ ]
finish = "n"
num = "0"
while finish == "n" :
       num = input("enter the mark : ")
       num = float(num)
       percentNumbers.append(num)
       finish = input("finished? (y/n) ")
print(percentNumbers)

...................................................................................................................

(( the question is : how can i convert this by using "for loop" instead of "while loop")) + (( I want the same result for both )). please help me ..


1 Answer
Pythonista

Usin count() function in itertools module gives an iterator of evenly spaced values. The function takes two parameters. start is by default 0 and step is by default 1. Using defaults will generate infinite iterator. Use break to terminate loop.

import itertools
percentNumbers = [ ]
finish = "n"
num = "0"
for x in itertools.count() :
    num = input("enter the mark : ")
    num = float(num)
    percentNumbers.append(num)
    finish = input("stop? (y/n) ")
    if finish=='y':break
print(percentNumbers)

Sample output of the above script

enter the mark : 11
stop? (y/n)
enter the mark : 22
stop? (y/n)
enter the mark : 33
stop? (y/n) y
[11.0, 22.0, 33.0]
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.