iterating same number using while loop - python

I'm just starting to learn while loops.
I'm trying to iterate same number 10 times using a while loop.
I figured out how I can utilize while loop in order to stop at a certain point as it increases
But I can't figure out how to stop at a certain point without having to add 1 and setting a limit.
Here is my code
i = 1
total = 0
while i < 11:
print i
i += 1
total = i + total
print total
This prints
1,2,3,4,5,6,7,8,9,10,65
in a separate line
How could I modify this result?
1,1,1,1,1,1,1,1,1,1,10?

Just print a literal 1 and add 1 to the total:
while i < 11:
print 1
i += 1
total += 1
You need to keep track of how many times your loop is run, and using i for that is fine, but that does mean you need to increment it on each run through.
If, during each loop, you only want to add one to the total, just do that and don't use the loop counter for that.

i = 1
total = 0
res = []
while i < 11:
res.append(1)
i += 1
print ', '.join(res) +', '+ str(sum(res))
or with for:
vals = [1 for _ in range(10)]
print ', '.join(vals) +', '+ str(sum(vals))

The whole point of a while loop is to keep looping while a certain condition is true. It seems that you want to perform an action n times then display the number of times the action was performed. As Martijn mentioned, you can do this by printing the literal. In a more general sense, you may want to think of keeping your counter separate from your variable, e.g.:
count = 1
number = 3
while count <11:
print number*count
print "While loop ran {0} times".format(count)

Related

How to continue a loop on a new line?

I'm new to python and have a problem that asks to output "#"a certain number of times based upon the value that the user entered. However it also asks to do it twice on two different lines.
I understand that I need to utilize a loop to output the "#" character.
num = int(input())
counter = 0
while counter != num:
print("#", end='')
counter = counter + 1
In the case of num = 3, the output I receive is ### however, it is supposed to be
###
###
This looks like a bit of a trick question. You are on the right path requiring a loop but you need to loop the required number of times eg
NUMBER_OF_LINES = 2
num = int(input())
# Loop the required number of lines
for _ in range(NUMBER_OF_LINES):
# Print the number of "#" symbols. Multiplying a string duplicates it.
print("#" * num)
That will produce the required results.
Is this what you want:
num = int(input())
num_of_lines = 2
for i in range(num_of_lines):
counter = 0
while counter != num:
print("#", end='')
counter = counter + 1
print()

I have some problem with my homework. It's about stop the loops

I'm in the middle of my homework. And i can't find out how to do this solution.
I have tried to used the break under for-statement but nothing return.
The problem is "Complete the following program so that the loop stops when it has found the smallest positive integer greater than 1000 that is divisible by both 33 and 273."
This is my code that i have tried to do it
n = 1001 #This one is required
while True: #This one too
for i in range(n,___): # I don't know what should i put in the blank
if i%33 == 0 and i%273 == 0: # I really confused about this line
break # Should i break it now?, or in the other lines?
print(f"The value of n is {n}") #This one is also required
I don't know that i should put break in which lines (or i don't have to used it?) or i should created a function that called a minimum number of the list?
I'm sorry about my language and how silly i am at my programming skill
I would accept every comment. Thank you
You already have a while True: loop, you don't need the inner for loop to search for your number, just keep incrementing n in the while loop instead of adding a new counter, when the number you're looking for is found, the infinite while True: loop will stop (using break), and so your print statement will be executed:
n = 1001 # start at 1001
while True: # start infinite loop
if n % 33 == 0 and n % 273 == 0: # if `n` found
break # exit the loop
n += 1 # else, increment `n` and repeat
print(f"The value of n is {n}") # done, print the result
Output:
The value of n is 3003
Thanks for saying it's homework! Makes it better to explain things in more detail than just giving an answer.
There are few things to explain:
1) n%33 is the remainder of dividing n by 33. So 66%33 is 0 and 67%33 is 1.
2) For loops are generally when you need to loop over a defined range (not always, but usually). E.g. "add up the first 100 integers". A while loop makes more sense here. It will definitely terminate, because at some point you'll get to 33 * 237.
3) if i%33 == 0 and i%237 == 0: means we want to do something when the number can be divided evenly (no remainder) by both 37 and 237.
n=1001
while True:
if n%33==0 and n%237==0:
print(n)
break
n+=1
A for loop will not help you here, because you don't know when to end the loop. You usually use for loops when the range of things you want to loop over is already known.
Instead, do the following:
before starting your while: True loop: set i to 0,
then increase i with 1 every time to the loop
also, don't forget to stop the loop when i>1000!
Well you could still use a for loop, as long as the upper limit is at least as high as the maximum possible result. The result would be in i, not in n, and the for loop will suffice, not an additional while loop. The for loop will break when the remainder when dividing by both 33 and 237 is zero (i.e. they are both factors).
n = 1001 #This one is required
for i in range(n, 33 * 237 + 1): # I don't know what should i put in the blank
if i % 33 == 0 and i % 237 == 0: # I really confused about this line
break #
print(f"The value of i is {i}") #This one is also required
You could also use a while loop and use the same logic for the condition. In this case we test that at least one is not a factor and continue the loop until both 33 and 237 are evenly divisible into i.
n = 1001 #This one is required
i = n
while i % 33 or i % 237:
i += 1
print(f"The value of i is {i}")

Creating a program that counts the amount of adding the numbers from 1 to 100 (for example: 1+2+3+4+5....and so on), using the WHILE loop

I have a homework to create a program that counts the amount of adding the numbers from 1 to 100 (1+2+3+4+5.....), using the while loop!
I tried the code provided down below! But the problem with it is that I already know the amount, but I need to make the program calculate it!
Code I tried:
amount = 0
while amount <= 5050:
amount += 1
print("The amount is: " + str(amount))
So what you're doing now is adding 1 until you reach 5050. Instead, you want to add the numbers 1 through 100. The solution, then, is to have two variables - one representing the total sum so far (this can be amount), and another representing the number you're adding. You continue to increase the amount you add, for each iteration, until you've added 100 to your running total.
amount = 0
to_add = 1
while to_add <= 100:
amount += to_add
to_add += 1
A more traditional way to do this would be to use a for loop, which can let you iterate over "the list of numbers from 1 through 100" (which you get by using the built-in range() function):
amount = 0
for i in range(1, 101):
amount += i
i=0
sum=0
while i<=100:
sum+=i
i+=1
print(sum)

Why am I not getting an output for the following python code?

I am not getting any output from interpreter after I input a value.
Here's my code:
number = int(input("Enter the number to test:"))
count = 0
if number % 2 == 0:
while number > 1:
number /= 2
count += 1
else:
while number > 1:
number = (3 * number) + 1
count += 1
print("Iteration count: " + count)
Expected output is 15 for input = 11
Edit: The Collatz Conjecture (above) use the following algorithm: If n is even, divide it by 2, else multiply by 3 and add 1. Start over until you get 1.
You have created an infinite loop in your while statements. A good way you can check this yourself is to print number inside the while loop, and you will quickly see where you are going wrong.
I don't want to give away the solution as this sounds too much like homework - but you must ensure your while loop condition is met, or it will never exit.

Why does my while loop output an out-of-bounds value?

So I was doing while loops and I noticed something strange.
count = 0
while count <= 5:
count += 1
print(count)
output:
1
2
3
4
5
6
it's not that I don't understand while loops. It's that how come the count is printed up to six? when it's supposed to print count only if count is less than or equal to 5?
and well 6 is beyond 5. why is this?
I know I could do
count = 0
while count != 5:
count += 1
print(count)
but I just want to understand why does putting <= behave in an odd way?
There is nothing odd about <=; your loop condition allows for numbers up to and including 5. But you increment count and then print it, so you will print 6 last.
That's because count = 5 satisfies your loop condition, then you add one to make it 6 and print. The next time through the loop count <= 5 is no longer true and only then loop ends.
So your code does this:
count = 0, count <= 5 -> True, count += 1 makes count = 1, print 1.
count = 1, count <= 5 -> True, count += 1 makes count = 2, print 2.
count = 2, count <= 5 -> True, count += 1 makes count = 3, print 3.
count = 3, count <= 5 -> True, count += 1 makes count = 4, print 4.
count = 4, count <= 5 -> True, count += 1 makes count = 5, print 5.
count = 5, count <= 5 -> True, count += 1 makes count = 6, print 6.
count = 6, count <= 5 -> False, end the loop.
You could increment the counter after printing:
while count <= 5:
print(count)
count += 1
or you could use < to only allow numbers smaller than 5:
while count < 5:
count += 1
print(count)
Let's walk through the code and see what's happening.
Note: If your code is doing something that you didn't expect it to do, this is a good practice to follow.
count = 0
while count <= 5:
count += 1
print(count)
The count starts at 0
count = 0
while count <= 5: # count = 0. Is 0 <= 5? Yes. Run the code.
count += 1
print(count)
Increment the count so it now equals 1. Print it.
while count <= 5: # count = 1. Is 1 <= 5? Yes. Run the code.
count += 1
print(count)
Increment. Print. Repeat.
Let's move on to the interesting case that's causing the problem.
while count <= 5: # count = 5. Is 5 <= 5? Yes. Run the code.
count += 1
print(count)
In this case the count still satisfies the inequality, so the code runs.
What happens?
The count, which is 5, is incremented and thus prints out 6.
Now that I hope you understand why the problem exists, let's explore alternatives and their advantages, disadvantages, and outputs.
Let's start with your code.
count = 0
while count <= 5:
count += 1
print(count)
Advantages: Does not print out 0
Disadvantages: Prints out 6
What if we removed the = sign?
count = 0
while count < 5:
count += 1
print(count)
Output:
1
2
3
4
5
Advantages: Does what you want
Disadvantages: You have to start at 0 instead of 1
What if we did as you suggested and replaced the < sign with the ! sign?
count = 0
while count != 5:
count += 1
print(count)
Output:
1
2
3
4
5
Advantages: Does what you want
Disadvantages: Fragile. If you ever changed your increment so that it increased by a number like, say, 3, the end point would be skipped over accidentally and the code would continue to run forever. Better to use an inequality
What if we wanted where we start to be the first number that is displayed? Well, to do this we'd have to print out the current number before we change it, so that means we have to flip the order of the events.
count = 1 # Change the first number so it's what we want displayed first.
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
Advantages: Does what you want and starts on the first displayed number instead of below it.
Disadvantages: If you want to stick with while loops, this is the way to go, but there is a better way in this case.
In situations like this, where you increment numbers and then perform operations with them, it's much more logical to just use a for loop, which was designed for instances just like this one.
for count in range(1,5):
print(count)
Output:
1
2
3
4
5
Advantages: Does what you want, easier to read, easier to write, less likely to cause bugs based on placement.
Disadvantages: The upper boundary must be known, unlike in a while loop.
It is simple when count equals five you add 1 and it becomes 6 then it is printed and you exit the loop.
Your problem is not about how <= works.
You are adding 1 to count before printing it, so when count is equal to 5, you then add 1 and therefore print 6.
To make things clear i will show the two scenarios with concrete explanation:
a=0
while (a<4):
a=a+1
print(a)
output would be 1,2,3,4
Variable a=0 should satisfy the condition(a<4) of while loop to continue the execution.
a=a+1 is calculated and saved in memory of the loop which is now 1.
Therefore the number 1 would be outputted not 0 as a result of print(a).
In order to iterate again inside the loop; the number 1(that was saved in the memory of the first loop is checked against the a<4 condition). Which is True; continue execution as previous.
a=a+1 calculated and saved in memory of loop which is now 2.
Then the number 2 is outputted
and is saved in the memory of the second loop and checked afterwards against the a<4). Which is True; continue execution as previous.
a=a+1 calculated and saved in memory of loop which is now 3.
Then the number 3 is outputted
and is saved in the memory of the third loop which is checked afterwards against the a<4). Which is True; continue execution as previous.
a=a+1 calculated and saved in memory of loop which is now 4.
Then the number 4 is outputted, even though the condition a<4 should be satisfied. The reason is that, i have stuck inside the loop after satisfaction of previous condition 3<4 and now after i am inside the loop, the execution of the statements is inevitable which will hold to output 4. The number 4 is now saved in the memory of the fourth loop which is checked against the a<4). Which is False, execution stop here.
This scenario would be amenable and understandable to the case of the opposite scenario
a=0
while (a<4):
print(a)
a=a+1
Output would be 0,1,2,3
Variable a=0 should satisfy the condition(a<4) of while loop to continue the execution.
First the print statement is executed, and the first value coined by a in the memory of the first loop is 0. Therefore 0 is outputted.
Afterwards a=a+1 is calculated and saved in memory of the loop which will change to be 1 and not 0.
In order to iterate again inside the loop; the number 1(that was saved in the memory of the first loop is checked against the a<4 condition). Which is True; continue execution as previous.
The print statement is executed, and the value coined by a in the memory of the second loop is now 1. Therefore 1 is outputted.
Afterwards a=a+1 is calculated and saved in memory of the loop which is now 2.
In order to iterate again inside the loop; the number 2(that was saved in the memory of the second loop is checked against the a<4 condition). Which is True; continue execution as previous.
The print statement is executed, and the value coined by a in the memory of the third loop is now 2. Therefore 2 is outputted.
Afterwards a=a+1 is calculated and saved in memory of the loop which is now 3.
In order to iterate again inside the loop; the number 3(that was saved in the memory of the third loop is checked against the a<4 condition). Which is True; continue execution as previous.
First the print statement is executed, and the value coined by a in the memory of the fourth loop is now 3. Therefore 3 is outputted.
Afterwards a=a+1 is calculated and saved in memory of the loop which is now 4.
In order to iterate again inside the loop; the number 4(that was saved in the memory of the fourth loop is checked against the a<4 condition). Which is False; execution stops.
For completeness:
Many beginners have difficulty with this problem conceptually. They often expect the loop to exit as soon as the condition is met, even in the middle of an iteration.
It does not work that way. The while loop condition is only checked at the beginning of each loop. It is the same as how an if block works - if the condition is met at the beginning, the rest of the block will be run, even if the condition stops being met.
If you want to exit a loop partway through an iteration, break can do that. However, you need to check the condition again in order for it to matter. Also keep in mind that you are writing a condition to leave the loop, rather than a condition to stay; so the logic needs to be reversed.
A lot of the time, it is easier to write code logic that checks a condition only partway through, and use an unconditional loop. That looks like (admittedly this is a silly example):
while True:
count += 1
if count > 5:
break
print(count)
In Python 3.8 and above, it is sometimes possible to simplify that sort of code using the so-called "walrus" operator, which assigns a value but also creates an expression rather than a statement (like how = works in C and C++):
count = 0
while (count := count + 1) <= 5:
print(count)
(Note that we cannot use :+= or +:= to avoid repeating count; those simply don't exist.)

Categories

Resources