0

[SOLVED] How can I change for loop to while loop

Just a beginner in 11th grade

20th Mar 2020, 3:52 PM
Piyush
11 Respuestas
0
Try for i in range(len(str(n))): for i in range means loop will run this many times whats inside range. the range i set is the length of n like 131's length is 3, but integer doesnt have a function of length so i converted it into string by str(n).
20th Mar 2020, 4:17 PM
maf
maf - avatar
+ 4
That's code-dependent and will be different every time. Do you have a specific piece of code in mind? Please think about it, give it a try, and show us your attempt!
20th Mar 2020, 4:00 PM
HonFu
HonFu - avatar
+ 3
Heres an example. You want to print numbers from 1 to 10, you can use both for and while loop. #WHILE num = 0 while num < 10: num = num + 1 #or num+=1 print(num) #FOR for i in range(1,11): print(i)
20th Mar 2020, 4:04 PM
maf
maf - avatar
+ 2
A no. Such as 151 or 606.. If you invert it it will give the same answer
20th Mar 2020, 4:11 PM
Piyush
+ 1
How about.. For to find if a no. Is palindrome or not n=131 t=n c = 0 while (n>0): r = int(n%10) c = (c*10)+r n = n//10 if (c==t): print ('n is palindrome') else: print ('n is not a palindrome')
20th Mar 2020, 4:05 PM
Piyush
+ 1
I'm confused 😕
20th Mar 2020, 4:22 PM
Piyush
+ 1
Good question Piyush, Assum a program of printing first 10 natural number ... What we do in for loop to print first natural number. 1. Initialise a variable and assigning a value like int i=1; 2.writing a condition like i<=10; 3.Incrementing the variable like i++; Let's create a for loop and while loop for the question by using above steps // For loop for(int i=1; i<=10;i++) { print(i); } //While loop Int i=1; while(i<=10){ print(i); }
22nd Mar 2020, 10:42 AM
Sunny Akhil
Sunny Akhil - avatar
0
What is a palindrome xDDD
20th Mar 2020, 4:07 PM
maf
maf - avatar
0
Piyush look. In while loop u need a counter variable like a = 0, inside while loop a = a + 1. In for loop u don't need a counter coz FOR i IN range means i is itself a counter. So, for i in range(5) means i will run until it reaches 5. a = 'hello' print(len(a)) this prints out the number of characters or length of the word which is 5 in 'hello'. if u didnt get it tell me again.
20th Mar 2020, 4:31 PM
maf
maf - avatar
0
Piyush a = 'hello' for i in range(len(a)): OR for i in range(5): Both would work the same way coz len(a) #length of a is 5.
20th Mar 2020, 4:34 PM
maf
maf - avatar