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


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]

Updated on: 20-Jun-2020

934 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements