Equivalent while loop block for a for loop block - python-3.x

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

Related

is it an infinite looping?(Python 3)

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.

How to extract numbers with repeating digits within a range

I need to identify the count of numbers with non-repeating digits in the range of two numbers.
Suppose n1=11 and n2=15.
There is the number 11, which has repeated digits, but 12, 13, 14 and 15 have no repeated digits. So, the output is 4.
Wrote this code:
n1=int(input())
n2=int(input())
count=0
for i in range(n1,n2+1):
lst=[]
x=i
while (n1>0):
a=x%10
lst.append(a)
x=x//10
for j in range(0,len(lst)-1):
for k in range(j+1,len(lst)):
if (lst[j]==lst[k]):
break
else:
count=count+1
print (count)
While running the code and after inputting the two numbers, it does not run the code but still accepts input. What did I miss?
The reason your code doesn't run is because it gets stuck in your while loop, it can never exit that condition, since n1 > 0 will never have a chance to be evaluated as False, unless the input itself is <= 0.
Anyway, your approach is over complicated, not quite readable and not exactly pythonic. Here's a simpler, and more readable approach:
from collections import Counter
n1 = int(input())
n2 = int(input())
count = 0
for num in range(n1, n2+1):
num = str(num)
digit_count = Counter(num)
has_repeating_digits = any((True for count in digit_count.values() if count > 1))
if not has_repeating_digits:
count += 1
print(count)
When writing code, in general you should try to avoid nesting too much stuff (in your original example you have 4 nested loops, that's readability and debugging nightmare), and try using self-describing variable names (so a, x, j, k, b... are kind of a no-go).
If in a IPython session you run import this you can also read the "Zen of Python", which kind of sums up the concept of writing proper pythonic code.

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.(I am not getting what is wrong in this code)

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

(Python 3) Spent an hour but couldn't find the error

I am a beginner at learning python 3 and I am just writing basic programs. I wrote this simple program which would take a number in and divide it by numbers starting from 1 to the square root of the number and find the remainders and add it to a list and print it.
import math
def prime_checker(num):
n=1
list_of_remainder=[]
while n == math.floor(num**0.5):
var=int(num % n)
list_of_remainder.append(var)
n += 1
return list_of_remainder
var=prime_checker(10)
print(var)
Please tell me what I did wrong. I would like to point out here that I did try to research a bit and find error but I couldn't and only then have I posted this question.
The problem that I faced was that it printed out an empty list.
to start with, your while loop is not executed even once. The condition for your while loop is
while n == math.floor(num**0.5):
The argument num you are passing to the function prime_checker is equal to 10. In this case your condition test is:
while 1 == math.floor(10**0.5)
which is
while 1 == 3 which is obviously not true and as a result the loop is not executed even once.
import math
def prime_checker(num):
list_of_remainder = []
number=num;
n=1
x=math.floor(number**0.5)
while n <= x:
v=int(number % n)
list_of_remainder.append(v)
n += 1
return list_of_remainder
var=prime_checker(10)
print(var)

changing the value of iterator of for loop at certain condition in python

Hello friend while learning python it came into my mind that is there any way by which we can directly jump to a particular value of iterator without iterating fro example
a=range(1.10) or (1,2,3,4,5,6,7,8,9)
for i in a
print ("value of i:",i)
if (certain condition)
#this condition will make iterator to directly jump on certain value of
#loop here say if currently i=2 and after this it will directly jump the
#the iteration value of i=8 bypassing the iterations from 3 to 7 and
#saving the cycles of CPU)
There is a solution, however it involves complicating your code somewhat.
It does not require an if function however it does require both while and try loops.
If you wish to change the numbers skipped then you simply change the for _ in range() statement.
This is the code:
a = [1,2,3,4,5,6,7,8,9,10]
at = iter(a)
while True:
try:
a_next = next(at)
print(a_next)
if a_next == 3:
for _ in range(4, 8):
a_next = next(at)
a_next = str(a_next)
print(a_next)
except StopIteration:
break
The iterator interface is based on the next method. Multiple next calls are necessary to advance in the iteration for more that one element. There is no shortcut.
If you iterate over sequences only, you may abandon the interator and write an old-fashioned C-like code that allows you to move the index:
a = [1,2,3,4,5,6,7,8,9,10]
a_len = len(a)
i = 0
while i < a_len:
print(a[i])
if i == 2:
i = 8
continue
i += 1

Resources