Why does this code not go to an infinite loop? (Python) - python

I'm currently beginning to learn Python specifically the while and for loops.
I expected the below code to go into an infinite loop, but it does not. Can anyone explain?
N = int(input("Enter N: "))
number = 1
count = 0
while count < N:
x = 0
for i in range(1, number+1):
if number % i == 0:
x = x + 1
if x == 2:
print(i)
count = count + 1
number = number + 1

For this code to not infinitely loop, count needs to be >= N.
For count to increase, x needs to be equal to 2.
For x to be equal to 2 the inner for loop needs to run twice:
for i in range(1, number+1):
if number % i == 0:
x = x + 1
For the inner for loop to run twice number must not have factors besides 1 and the number itself. This leaves only prime numbers.
The inner loop will always set x == 2 when number is a prime number. As there are an infinite amount of prime numbers, count >= N will eventually be satisfied.

Try to change N to number:
while count < N:
while count < number:

Ok let's dissect your code.
N = int(input("Enter N: "))
number = 1
count = 0
Here you are taking user input and setting N to some number,
for the sake of brevity let's say 4. It gets casted as an int so it's now
an integer. You also initialize a count to 0 for looping and a number variable holding value 1.
while count < N:
x = 0
for i in range(1, number+1):
if number % i == 0:
x = x + 1
if x == 2:
print(i)
count = count + 1
number = number + 1
Here you say while count is less than N keep doing the chunk of code indented.
So in our N input case (4) we loop through until count is equal to 4 which breaks the logic of the while loop. Your first iteration there's an x = 0 this means everytime you start again from the top x becomes 0. Next you enter a for loop going from 1 up to but not including your number (1) + 1 more to make 2. you then check if the number is divisible by whatever i equals in the for loop and whenever that happens you add 1 to x. After iteration happens you then check if x is 2, which is true and so you enter the if block after the for loop. Everytime you hit that second if block you update count by adding one to it. now keep in mind it'll keep updating so long as that if x == 2 is met and it will be met throughout each iteration so eventually your while loop will break because of that. Hence why it doesn't go forever.

Related

Python - why is this an infinite loop?

I have the following code:
sum_of_primes = 0
n = 2
while n < 10:
for i in range(2,n):
if n%i == 0:
n += 1
break
else:
sum_of_primes += i
n += 1
print(sum_of_primes)
I can't seem to figure out why this is an infinite loop.
Below is my modified code which works, but i still don't understand why the original code is creating an infinite loop:
counter = 0
primes = 0
number = 2
while counter < 10:
for x in range(2, number):
if number % x == 0:
number += 1
counter+=1
break
else:
primes +=number
counter = number
number += 1
print(primes)
You inner loop is never executed since range(2, 2) is empty. Since the inner loop updates n, n is never changed, so the outer loop will never terminate.
n = 2
while n < 10:
for i in range(2,n): # list(range(2,2)) == [] ...
# ... so this loop never executes
# and n is never updated
# so this loop runs forever
Initially n is 2. The for loop is therefore for i in range(2,2) which is an empty range so the loop never executes. That means you never get into the code that might increment n.
sum_of_primes = 0
n = 2
while n < 10: # n == 2
for i in range(2,n): # loop repeats zero times
if n%i == 0:
n += 1
break
else:
sum_of_primes += i
n += 1
# n == 2 still the case down here.
print(sum_of_primes)
You wrote that for i in range(2,n): and at start point n=2. So your range will be range(2,2) so it will return empty list so this for loop never executes and your program will be gone in an infinite loop.
And in second code you are using for...else
for x in range(2, number):
if number % x == 0:
number += 1
counter+=1
break
else:
primes +=number
counter = number
number += 1
Here, the meaning of for...else is if for loop will be not executed a single time then the else part of for loop will be executed. And in else part you are increase the counter and number.
so, first time number = 2 and for loop become for x in range(2, number): mean for loop will be not executed so, as per I discussed above if for loop is not exceute single time else part will be execute
So, in else part number will be increased by 1, then in next iteration your for loop become for x in range(2,3) so, at that time for loop will be executed successfully...
For for...else Reference
for i in range(2,n):
it means range is (2,2) the loop never started since it's starting and ending is the same that is 2-2.

Find all positive numbers divisible by 10 and less than n

I need to find all positive numbers that are divisible by 10 and less than n, i found a string with the same question but i have a hard time interpreting it as the user was using java so the codes are very different and confusing.
i tried to make a code by piecing together codes i've checked out but it only works if its divisible by other numbers, if its 10 it would keep going on forever with 0.
n = int(input("Enter a number: "))
x = 0
while x < n :
r = n % 10
if r % 10 != 0 :
x = x + r
print("positive numbers divisible by 10 ", x)
Below is simpler code which will help to get the list of numbers divisible by 10 and less than n:
n = int(input("Enter a number n: "))
divisibleBy10 = []
for i in range(0, n):
if i % 10 == 0:
divisibleBy10.append(i)
print(divisibleBy10)
You can do like this:
n = 100
i = 0
while i<n:
if i%10==0:
print(i)
i+=1
You can also try the following:
# grab the user's input
n = int(input('please enter a number: '))
# set x to 0, so the while loop can stop when 'n' is greater than '0'
x = 0
while n > x:
if n % 10 == 0:
print('{} is divisible by 10.'.format(n))
n -= 1
So basically the loop enters with the value that the user inputs, let's say 10.
Is 10 greater than 0? Yes (while loop executes), the if statement evaluates the remainder with the mod. The value is printed because the if statement evaluates True , the remainder is equal to zero. At last, n is subtracted by 1
Is 9 greater than 0? Yes (while loop executes), the if statement evaluates the remainder with the mod. The value is not printed because the if statement evaluates False , the remainder is not equal to zero. At last, n is subtracted by 1
Is 8 greater than 0? Yes (while loop executes), the if statement evaluates the remainder with the mod. The value is not printed because the if statement evaluates False , the remainder is not equal to zero. At last, n is subtracted by 1
...
And so on until n reaches 0, the while loop stops because 0 is not greater than 0.
This code below tries to reduce the number of loops. If 'x' is extremely large, it helps to optimize the solution. The idea is to not do the divisibility check for each number starting from 1 to n-1. Here, we use the fact that the least positive number divisible by 10 is 10. The next number of interest is 10 + 10 = 20, there by skipping numbers 11 to 19. This helps improve the performance.
x = input('Enter any number ')
y = 10
while y < x:
print(y)
y = y + 10
I think use inline for loop:
print([i for i in range(10,n,10) if i % 4 == 0])

Looking for Clarification on how this "For-Loop" works

I'm a complete beginner to programming so forgive me for my naivete.
I wanted to make a program in Python that lets me print a given N number of prime numbers, where N is inputted by the user. I searched a little on "for/while" loops and did some tinkering. I ran a program I saw online and modified it to suit the problem. Here is the code:
i = 1
print("Hi! Let's print the first N prime numbers.")
nPrimes = int(input("Enter your N: "))
counter = 0
while True:
c = 0 #another initialization
for x in range (1, (i + 1)):
a = i % x # "a" is a new variable that got introduced.
if a == 0:
c = c + 1
if c == 2:
print(i, end = " ")
counter = counter + 1
if counter > = nPrimes: #if it reaches the number input, the loop will end.
break
i = i+1
print(": Are your", nPrimes, "prime number/s!")
print()
print("Thanks for trying!")
This should be able to print the amount of prime numbers the user so likes. It is a working code, though I am having difficulty trying to understand it. It seems that the variable c is important in deciding whether or not to print the variable i (which in our case is the supposed prime number during that interval).
We do c + 1 to c every time our variable a has a remainder of 0 in a = i % x. Then, if c reaches 2, the current variable i is printed, and variable c re-initializes itself to 0 once a prime number has been found and printed.
This I can comprehend, but I get confused once the numbers of i get to values 4 and onwards. *How is 4 skipped by the program and not printed when it has 2+ factors in the range that makes its remainder equal to zero? Wouldn't c == 2 for 4 and thus print 4? *And how would the program continue to the next number, 5? (Given that variable N is a large enough input).
Any clarifications would be greatly appreciated. Thank you so much!
From Wikipedia we know:
A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.
So to find a prime, is to find a natural number, aka an integer, which can only be exactly divided by 1 or itself. This is called Approach of Definition to find primes.
Hence, the following loop traverses through all integers from 1 to i,
and it counts how many times the integer i can be exactly divided by them.
for x in range (1, (i + 1)):
a = i % x # "a" is a new variable that got introduced.
if a == 0:
c = c + 1
And later you judge if the integer i can only be exactly divided by 1 and itself.
If true, you got a prime;
otherwise you just keep on.
if c == 2:
print(i, end = " ")
counter = counter + 1
if counter > = nPrimes: #if it reaches the number input, the loop will end.
break
Meanwhile, you can improve this prime searching algorithm a little bit by changing i = 1 to i = 2 in the beginning and adding an if statement:
# Start from 2 instead of 1
# and end at `i - 1` instead of `i`
for x in range (2, i):
a = i % x # "a" is a new variable that got introduced.
if a == 0:
c = c + 1
# Abandon the loop
# because an integer with factors other than 1 and itself
# is unevitably a composite number, not a prime
if c > 0:
break
if c == 0:
print(i, end = " ")
counter = counter + 1
if counter >= nPrimes: #if it reaches the number input, the loop will end.
break
This twist improves the efficiency of your program because you avoid unnecessary and meaningless amount of work.
To prevent potential infinite loop resulting from while expression,
you should replace while True: with while counter < nPrimes:. And the code turns out to be like this:
#if it reaches the number input, the loop will end.
while counter < nPrimes:
c = 0 #another initialization
# Start from 2 instead of 1
# and end at `i - 1` instead of `i`
for x in range (2, i):
a = i % x # "a" is a new variable that got introduced.
if a == 0:
c = c + 1
# Abandon the loop
# because an integer with factors other than 1 and itself
# is unevitably a composite number, not a prime
if c > 0:
break
if c == 0:
print(i, end = " ")
counter = counter + 1
i = i + 1
If you want to read more about how to improve your program's efficiency in finding primes, read this code in C language. :P
c in this case is used to count the number of numbers that divide evenly into i.
for example, if i = 8: 8 is divisible by 1, 2, 4, and 8. so c = 4 since there are 4 things that divide evenly into it
if i = 5: 5 is divisible by 1 and 5. so c = 2 since there are 2 numbers that divide evenly into it
if i = 4 (where you seem to be confused): 4 is divisible by 1, 2, and 4. so c = 3, not 2.

Python Code to Find x Prime Numbers w/ For Loop?

I am trying to put together a simple program which could work out n prime numbers. I would like to do this by using a nested for loop, where one would go through the numbers, and another would divide that number by all of the numbers up to it to see if it would be divisible by anything.
The problem I am having is that in the main for loop, I need to start it at 2, seeing as 1 would mess up the system and I don't want it to be considered a prime. For the loop to have a starting number however, it also needs an ending number which is difficult in this instance as it is hard to generate the largest prime that will be needed prior to the loop working.
Here's the program that I am using right now. Where I have marked X is where I need to somehow put an ending number for the For Loop. I guess it would be much simpler if I let the For Loop be completely open, and simply take out anything that '1' would produce in the loop itself, but this feels like cheating and I want to do it right.
check = 0
limit = int(input("Enter the amount of Prime Numbers"))
for i in range(2,X):
check = 0
if i > 1:
for j in range(2,i):
if (i % j) == 0:
check = 1
if check == 0:
print (i)
Thanks for your help!
You can step through an unlimited amount of numbers using a generator object.
Insert the following somewhere near the top of your code:
def infinite_number_generator(initial_value=2):
""" Generates an infinite amount of numbers """
i = initial_value
while True:
yield i
i += 1
What this does is it creates a function for constructing generator objects that "pause" whenever they reach the yield statement to "yield" whatever value is specified by the yield command, and then continue to execute from the next line beneath the yield statement.
Python's own range function is itself an example of a generator, and is roughly equivalent to (ignoring the step argument and other peculiarities)
def range(start, end):
i = start
while i < end:
yield i
i += 1
So your program would then look like this:
def infinite_number_generator(initial_value=2):
""" Generates an infinite amount of numbers """
i = initial_value
while True:
yield i
i += 1
check = 0
limit = int(input("Enter the amount of Prime Numbers"))
for i in infinite_number_generator():
check = 0
for j in range(2,i):
if (i % j) == 0:
check = 1
if check == 0:
print (i)
if i == limit:
break
I should also point out that the code you provided is buggy - it will never stop printing because there's no checking whether you've found your limit number of primes yet or not.
This should do what you want.
check = 0
limit = int(input("Enter the amount of Prime Numbers"))
counter = 0
i = 2
while counter < limit:
check = 0
if i > 1:
for j in range(2,i):
if (i % j) == 0:
check = 1
if check == 0:
counter += 1
print (i)
i += 1
In your code you start i with 2 and always increment by 1, so the i will always remain greater than 1, therefore the test if i > 1 is useless.
For efficiency you can stop the check at the square of i or i/2 (no divisors in [i/2 + 1, i[ ).
you can update your code as follow:
n = int(input("Enter the amount of Prime Numbers: "))
FoundPrimes = 0
i = 2
while FoundPrimes < n:
isPrime = True
for j in range(2,1 + i//2):
if (i % j) == 0:
isPrime = False
if isPrime:
FoundPrimes += 1
print(i, end = '\t')
i += 1

Python, counting the number of even digits

for homework in an introductory python class, one of the questions is to count the number of even numbers in n. here's my code so far:
def num_even_digits(n):
i=0
count = 0
while i < n:
i+=1
if n%2==0:
count += 1
return count
print(num_even_digits(123456))
Pythonic answer:
def num_even_digits(x):
return len([ y for y in str(x) if int(y) % 2 == 0])
print(num_even_digits(123456))
Disclaimer: I recognized that, for an introductory Python class, my answer may not be appropriate.
you are comparing the whole number every time. you need to convert it to a string and then loop over every number in that string of numbers, cast it back to an integer and see if its remainder is 0
def num_even_digits(numbers):
count = 0
numbers = str(numbers)
for number in numbers:
try:
number = int(number)
except ValueError:
continue
if number % 2 == 0:
count += 1
return count
print(num_even_digits(123456))
if you want to actually loop through every possible number in the range of 0 to your large number you can do this.
def num_even_digits(numbers):
count = 0
for number in range(0, numbers):
if number % 2 == 0:
count += 1
return count
print(num_even_digits(10))
problems with your current function:
def num_even_digits(n): # n is not descriptive, try to make your variable names understandable
i=0
count = 0
while i < n: # looping over every number from 0 to one hundred twenty three thousand four hundred and fifty six.
i+=1
if n%2==0: # n hasn't changed so this is always going to be true
count += 1
return count
print(num_even_digits(123456))

Categories