0
[SOLVED] How can I change for loop to while loop
Just a beginner in 11th grade
11 Antworten
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).
+ 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!
+ 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)
+ 2
A no. Such as 151 or 606.. If you invert it it will give the same answer
+ 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')
+ 1
I'm confused 😕
+ 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);
}
0
What is a palindrome xDDD
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.
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.