Python while cycle beginner

Hello,guys!Can you please explain why does this code not return to 'n = int(input())’ after printing the star,but turns into an infinite loop? And how to fix it?

n = int(input())
stars = '*'
while len(stars) <= n:

Because you never change n inside the loop, so it always has the same value that you got with the first input. You also never change the length of the stars string. So if a user inputs, for example 3 as the first n value (that’s line 1), and the length of the stars string is 1 (it only has one character and you never change it), so len(stars) <= n will always be true - hence the infinite loop.

You need to change one of the variables inside the while loop. If you want to get another value for n, you need to ask the user for an input again at the end of the loop. Or (if you want to print n many stars, for example if n = 3 and you want to print "***"), then you need to concatenate additional stars to the string so that its length increases until you reach n.

I hope this cleared things up at least a little bit :slight_smile:

1 Like

The line at the top will only run once no matter what you do with the code below it.

Since stars’ length is 1, the print(stars) line will run forever if the value entered by user greater or equal to 1.

1 Like

Thank you for an answer:)

Yep,thank you :smiley:

1 Like