Printing a square in python3 with two whiles | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Printing a square in python3 with two whiles

Hello, It's my first time using sololearn, sorry if I mess something up :) I started learning python3 and I have a problem with my square printing code. Here it is: def square( x ): i = int(0) while x > 0: while x > i: i += 1 print("*", end='') x -= 1 x=int(input()) square(x) I want it to print x lines with x length, but it only prints one line. It seems like it only does the "inside while" once. I have no clue why tho. Any help appreciated!

9th Oct 2018, 12:34 PM
Konik
Konik - avatar
3 Answers
+ 3
It only goes trough the loop once because you set the value of i outside the first while loop. So after it loops through the inner while you have to reset the value. def square(x): i = int(0) while x > 0: i = int(0) while i < 10: # print(i,x) i += 1 print("*", end='') x = x- 1 # print(x) x=10 square(x)
9th Oct 2018, 1:09 PM
Willem Roos
+ 3
I guess this is what you meant? def square(x): i = 0 while i < x: j = 0 while j < x: print('*', end=' ') j += 1 print() i += 1
9th Oct 2018, 1:07 PM
Ipang
+ 1
thank you guys! answer is always so easy when you finally know it :D
9th Oct 2018, 1:29 PM
Konik
Konik - avatar