Click here to Skip to main content
15,063,416 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
def my_func(c=1, n=-1):
    while True:
        if n>-1 and c > n:
            # if counter > number of iterations required
            break
        a = int(c * (c + 1)/2)
        yield a
        c += 1

def get_valid_user_input():
    user_input = input("Enter a number, or leave blank for infinite loop: ")
    if user_input == "":
        return -1
    try:
        return int(user_input)
    except ValueError:
        print("Error! Please enter a number or leave blank.")
        return get_valid_user_input()

my_object = my_func(n=get_valid_user_input())
while True:
    try:
        print(next(my_object))
    except StopIteration:
        print("End of Iteration")
        break


Hi Basically I would like to print the first 10 iterations of triangular numbers ..ie (1 3 6 9 12 etc...once 10 iterations are reacher I would like to provide the user with a prompt ..if yes is selected continue loop until infinity ..if No is selected then break the loop and ask the user to enter a new amount of iterations..

What I have tried:

I set
my_object = my_func(n=10)
which gives the fist 10 iterations ..but then I don't know how to switch to user input prompt to select Yes or No question.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900