I'm doing a quiz on sololearn and I'm confused, it says I have to loop from 5 to 1 when I use hint I get this code and when I run the code it becomes infinite loop instead of looping from 5 to 1
is it an infinite looping?
x = 5
while x > 0:
print(x)
x -= 1
Python is sensitive to the indenting of code. In order for your decrement statement to fall within the loop it must be indented to fall under the print statement.
Related
sum = 2
x=3
y=5000
for i in range (x,y):
for j in range (2,i):
if i%j==0:
break
elif i%j!=0 and j==i-1:
sum += i
if i==y-1 and y<2000000:
x=y
y+=5000
else:
continue
print(sum)
**I am not getting what is wrong in this code. By running this I came to know that the Last If and Else statement are not running **
Given your code, there are a couple of things wrong. First, sum is a python function name and should never be used as a variable name. It will get you into trouble in more ways than I care to think about. Second, the last else statement is not needed, because whether the if clause above it is or is not executed executed, the for loop will be executed again. Third, I don't understand the purpose of y and the magical value 5000, unless you are trying to provide an end value for your loop. The problem with this approach is you seem to try and extend it's range in increments of 5000. The problem is that once the initial for loop is executed, it creates a local iterable from x to 5000, and subsequent changes to y do not affect the for loops range.
I would approach the problem differently, by creating a list of primes and then use the python sum method to add all the values. Here is the code:
def sum_primes(max_prime):
""" Return Sum of primes Less than max_prime"""
primes = [2]
indx_num = 3
while primes[-1] <= max_prime:
update = True
for prime in primes:
if indx_num == prime or indx_num % prime == 0:
update = False
break
if update:
primes.append(indx_num)
indx_num += 2
#return summ of all values except the last
return sum(primes[:-1])
Executing sum_primes(2000000)
yields 1709600813
I took a quiz, the output for this following code is 1 1 instead of 1 1 2 3. And the explanitaion for this answer is that when the code encounter the break(when it reach 2) ,then loops stop.
I understand that the loops stop when it reach 2, but since print() has the same indentation as if() statement, I thought they are excuted seperately,
(but both still under for loop). So when number reaches 2, even if the loop stops, it will still execute the print(), for it is still under for loops. Hence, the result is the 1 1 2 3. And no matter what if() statement is, the result is the same.
numbers = [1, 1, 2, 3]
for number in numbers:
if number % 2 == 0:
break
print(number)
No, the commands are interpreted in order. When the if condition becomes true, the break exits the for loop before the print can execute. The first two loops the break is skipped since 1 % 2 == 0 is false, but 2 % 2 == 0 is true exiting the loop before getting to 3 which would also be true and print... if the loop hadn't already exited.
When the break statement executes the execution pointer goes to the next statement outside the loop, not the statement after the if block containing the break statement, so the print function is not called once break is executed as the execution is then outside the loop.
I am a novice trying to learn python from Automate The Boring Stuff with Python by Al Sweigart and I came across his block of code to answer a math problem: "What is the sum of all the numbers from 0 to 100?" Apparently, this was a question Gauss got when his teacher wanted to keep him busy.
Sweigart used a for loop and range() function to get the answer:
total = 0
for num in range(101):
total=total+num
print(total)
A page later he states that "you can actually use a while loop to do the same thing as a for loop; for loops are more concise."
How would this statement be rendered in a while loop?
I tried replacing the for with while but got an error: "name 'num' is not defined." I also tried to set up a summation math equation using another block of code from another forum, but completely got lost.
print('Gauss was presented with a math problem: add up all the numbers from 0 to 100. What was the total?')
a=[1,2,3,4,5,...,100]
i=0
while i< len(a)-1:
result=(a[i]+a[i+1])/2
print(result)
i +=1
Then, I tried to setup i in an equation that would loop until each number was added, but got stuck.
print('Gauss was presented with a math problem: add up all the numbers from 0 to 100. What was the total?')
i=0
while i<101:
i=i+1
a=i
Would the while statement be too complex to warrant the effort?
Your last example comes close.
A for loop of this form:
for x in range(N):
# ...
can be replaced by a while loop like this:
x = 0
while x < N:
# ...
x += 1 # equivalent to x = x + 1
Just make sure you leave the rest of the code unchanged!
The for loop is more concise. Notice how we need a "counter" variable , in this case i with the while loop. That's not to say we don't need them in a for loop, however they're integrated nicely into the syntax to make for cleaner code.
i = 0
total = 0
while i < 101:
total += i
i += 1
print(total)
Python's for loop syntax is also a foreach equivalent:
for eachItem in list:
# Do something
I am new to python programming. Why does this code does not work?
# Print out 2,5,8,11 using `for` loop and `range()`.
for x in range (2,12):
print (x)
x=x+3
I know the following will make the program work
# Print out 2,5,8,11 using `for` loop and `range()`.
for x in range (2,12,3):
print (x)
But I can't understand why the first one doesn't give the desired result whereas the equivalent code would work in C++/C.
Even you try to increment x as x=x+3, it is being changed in every iteration, and take the new value from 2 to 12, depending upon how many iteration has been progressed( if the loop is in 4th cycle, then x will be updated as 4 at the start of the 4th cycle). Even if you've placed x=x+3before the print statement, what it will do is simply printing "iteration + 3"
for x in range (2,12):
print (x)
x=x+3
So this code will produce an output like this;
5
6
7
8
9
10
11
12
13
14
So, there is no way to update x and then use this updated version in next iteration when you are using a for loop in Python.
You cannot increment the value of x when using range() function. There are two ways you can get your desired output.
First Method :
print [x for x in range(2,12,3)]
Second Method :
for x in range(2,12, 3):
print(x)
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
I don't understand what the above command wants to do.
I know about looping but can you explain what this command is actually doing?
Python's for and while loops have a feature that may look confusing to people who are more familiar with those loops in other programming languages: You can put an else clause after the loop body.
The else block will be run only if the loop terminated in the normal way (a for loop reaching the end of the iterable or a while loop's condition being false). It will not be run if the loop was terminated by a break statement.
In the code you're looking at, the inner loop tests to see if the number n is prime by testing if it can be evenly divided by any x value. If an x does divide it exactly, the factors x and n // x are printed and a break statement ends the loop.
If no such factor is found in the range, the loop ends. As I mentioned above, this the situation where the else block is run. It prints that n is prime.