In the sample program below, I tried to find the even number with the the number I typed in (2, 1, 4, 0) these 4 numbers. The result is 2, but I don't know what (n) means in this program.
a = int(input())
n = 0
while a != 0:
if a % 2 == 0:
n = n + 1
a = int(input())
print(n)
here n is used to count even numbers.
the loop will keep checking whether given input is 0 or not if it is 0 the loop will exit if not it will check whether it is even or odd, if the number is even it will increase the value of n by 1. If you input 10 even numbers the value of n will be 10 respectively.
n is your counter and probably you forgot to make a break from the loop the loop will be an infinite loop you have to add a condetion so that the loop stops like:
while n != 10 :
Or
add if statement
if n < 10 :
break #to quit the loop
Related
number = 50
while number >= 0:
if number % 5 == 0:
print(number)
number = number - 1
elif number % 5 == 1:
continue
number = number = number - 1
the answer it's giving me is 50 then the loop stops executing
Here is the program I am trying to make:
While Loops Practice #2
Create a While Loop that subtracts one by one the numbers from 50 to 0 (both numbers included) with the following additional conditions:
If the number is divisible by 5, show that number on the screen (remember that here you can use the modulus operation dividing by 5 and checking the remainder!)
If the number is not divisible by 5, continue executing the loop without showing the value on the screen (don't forget to continue subtracting so that the program doesn't run infinitely).
Here is your code, improved:
number = 50
while number >= 0:
if number % 5 == 0:
print(number)
number = number - 1
I'm confused about that too, but here are my thoughts: you only subtracted when number % 5 == 1, but it can also be 2, 3, 4 or 5.
num = 50
while num != 0:
if num % 5 == 0:
print(num)
num -= 1
would work for this as it will only print the number if it is divisible by 5, and always subtract.
Make sure you always subtract 1 from number before continuing the loop. As the prompt reminds you, this is especially important when you use the continue statement, since that brings you straight back to the top of the loop -- if you haven't subtracted before then, the loop will repeat infinitely!
One way to make sure that something always happens even if execution is interrupted (not just a continue but maybe a return, a break, a raise, etc) is try/finally:
number = 50
while number >= 0:
try:
if number % 5 == 0:
print(number)
elif number % 5 == 1:
continue
finally:
number -= 1
prints:
50
45
40
35
30
25
20
15
10
5
0
In this case, though, there's no need to immediately continue the loop, since there's nothing in the loop that you explicitly need to skip in the number % 5 == 1 case (note that this isn't the same as "not divisible by 5" -- what you're testing for here is "has a reminder of 1 after dividing by 5", i.e. 1, 6, 11, and so on, which isn't part of the problem statement).
You can therefore just do:
number = 50
while number >= 0:
if number % 5 == 0:
print(number)
number -= 1
The main structure is corret, but in the last line you wrote two times the code "number =" and "else" is useless in this case, because you need to substract 1 in every loop.
here's the code solved:
number = 50
while number != 0:
if (number%5) == 0:
print(number)
number = number - 1
This question already has answers here:
how to stop a for loop
(9 answers)
Closed 2 years ago.
As I am getting more and more comfortable with writing scripts in Python I wrote a script that finds prime numbers by trying to divide each number in a range in each number (kinda like Brute Force haha).
It works but I wanted to make the process faster and more efficient.
My code:
count = 0
for i in range(2,1000):
j = 2
while j < 1000:
if i%j==0:
count = count + 1
j = j + 1
if count == 1:
print(i)
count = 0
Explanation:
I check and store in count how many time does a number can be divided.
If by the end of the check count equals 1 that means that the number is prime (gets divided only by itself).
What I want now is to stop the process of checking how many times the number can get divided when the "count" variable exceed 1 (2 or more). How do I do that?
I wanted to do something with try and except but didn't know what...
Add an extra condition in here, and break out of the loop if the count is greater than one. Put this inside the while loop:
if i % j == 0:
count += 1
if count > 1:
break
As mentioned in the comments, it's cleaner to just use count as part of the loop condition. Here's an improved version:
for i in range(2, 1000):
j = 2
count = 0
while j <= i and count < 2:
if i % j == 0:
count += 1
j += 1
if count == 1:
print(i)
Of course, there are faster ways to find if a number is prime - in particular, in the inner loop you should not iterate until 1000, not even until i is reached, just until the sqrt(i), but I'll leave that as an improvement for you to make ;)
You can try using break. What break does is that it skips the remaining part of the loop and jumps to the statement following the loop.
count = 0
for i in range(2,1000):
j = 2
while j < 1000:
if i%j==0:
count = count + 1
break
j = j + 1 ### line 8
if count == 1:
print(i)
count = 0
In this code, when python encounters break, it skips the remaining part of the loop (that is, the remaining loop is not executed) and jumps straight to the next statement, which is line 8
Its all wrong, first you have to understand the algorithm to check for prime, basically a number is prime if it can't be fully divided by any number between 2 to (number//2)-1
Now in your question, you couldn't use break anywhere, bcz you first searching for all divisible and then checking prime, better I'm adding a sample code to your problem which is more feasible to find primes
Code
number = int(input("Enter A Number"))
for i in range(2,number//2+1): #See range arguments
if(number%i==0):
print("Not A Prime")
break #Break loop when condition reached
def is_prime(num):
for i in range(2,num):
if (num % i) == 0:
return False
return True
def all_primes(num):
primes = []
for n in range(2,num+1):
if is_prime(n) is True:
primes.append(n)
return primes
num = int(input("Enter upper limit: "))
primes = all_primes(num)
print(primes)
How does it happens...
What understand is if I enter 10
It will be 10%2= 5...the remainder is 0 so it skip to the next one 9%2 = True there is remainder.
It moves to the next one 9%3 remainder is 0 so it skips to 8% ...,then 7 .......but what I dont understand is 7 if it's check until 7%7 ==0 then how did it add 7 as Prime number???
I'm so confused.
Thank you for any comment
but what I dont understand is 7 if it's check until 7%7 ==0
The range function from the following line:
for i in range(2, num):
goes from 2 to num - 1.
So, the range() function doesn't include the last (stop) number in the result.
You got it wrong. If you enter 10, it wouln't check 10%2 and then 9%2...
It would check 10%2, then 10%3, then 10%4... i.e. it would check 10%i, for i ranging from 2 to 9. However, note that execution in is_prime stops as soon as the remainder is 0:
for i in range(2,num):
if (num % i) == 0:
return False
So if num is 10, only 10%2 would be checked, and since it's 0, it would immediately return false.
If num is 9, for example, it would check 9%2. Since the remainder is not 0, it would move up to checking 9%3. The remainder is 0 there, so it would return false in that case.
If num was 7, it would check 7%2. The remainder is not 0 so it checks 7%3, which is also different from 0, and so on. The last check performed would be 7%6, because for i in range(2,num) means that it will iterate with i ranging from 2 to num-1. In this case, is_prime(7) would return true because 7%i, with i ranging from 2 to 6 is different than 0.
when is_prime is called for number 7, the loop will run from 2 to 6 only. Hence 7%7 will never be checked , returning True for such case.
A prime number, by definition, is a number that is divisible only by itself and 1.
Therefore, your function is_prime gets the number you want to check if it is prime, and try to find any other number that can divide it inside the interval [2, num), this interval is implemented using the function range(2,num) inside the for loop.
If it finds any case, i.e., if the if (num % i) == 0 is satisfied, we know that there is a number which divides it, therefore, by definition it is not a prime number.
After checking the whole list, if you cannot find a divisor, we can say that the number is prime, i.e., the return True on your function.
Example:
You want to check 9
(1st step) num = 9, i = 2. 9%2 != 0, we continue in the loop with next value of i.
(2nd step) num = 9, i = 3. 9%3 == 0, we return False. As we know, 9 can divide by 3.
Another example:
You want to check 7
num = 7, i = 2 7%2 != 0, so we continue in the loop with the next value of i
num = 7, i = 3 7%3 != 0, so we continue in the loop with the next value of i
num = 7, i = 4 7%4 != 0, so we continue in the loop with the next value of i
num = 7, i = 5 7%5 != 0, so we continue in the loop with the next value of i
num = 7, i = 6 7%6 != 0, so we continue in the loop with the next value of i
The if was never fulfilled, therefore we reach the end of the loop and
call the next command, which is return True.
Let's consider the two function separately:
def is_prime(num):
for i in range(2,num):
if (num % i) == 0:
return False
return True
This works like this:
let's consider a number num
get a variable i to assume the value 2
evaluate the condition num % i == 0
if the condition is met, then exit from the function and return False
otherwise increment i by 1 and repeat the last two steps until i is equal to num - 1
exit the function and return True
So, this never gets to evaluate 7 % 7: when num is 7 the last value of i is 6.
def all_primes(num):
primes = []
for n in range(2,num+1):
if is_prime(n) is True:
primes.append(n)
return primes
This gets a number num which is the upper limit of the numbers to consider, then:
it creates an empty list named primes
it loops n from 2 until num + 1 excluded (or num included)
if the result of is_prime(n) is True, it appends the number to the list.
finally, return the list in primes.
Finally the main body of the script:
num = int(input("Enter upper limit: "))
primes = all_primes(num)
print(primes)
gets you a string from the keyboard, convert it to int and assign to num, then call all_primes(num) and assign its result to primes and print the list to screen.
So, when you input 10 from the keyboard, it will check the values from 2 to 10 for being prime with is_prime(), and not from 10 and reducing them, as you seems to suggest.
I'm trying to get this program to return all possible multiples of 3 and 5 below 1001 and then add them all together and print it but for some reason these lines of code only seem to be printing one number and that number is the number 2 which is obviously wrong. Can someone point me in the right direction to why this code is grossly wrong?
n = 0
x = n<1001
while (n < 1001):
s = x%3 + x%5
print s
You've got a few mistakes:
x is a boolean type
Your loop never ends
adding values to mimic lists?
Edit
Didn't see the part where you wanted sum, so you could employ a for-in loop or just a simple one like so:
sum = 0
for i in range(1001):
if(i % 3 == 0 or i % 5):
sum += i
print(sum)
(Python 3)
You need to stop while at some point by incrementing n. Here is some code:
nums = []
n = 0
while (n < 1001):
# in here you check for the multiples
# then append using nums.append()
n += 1
This creates a loop and a list that accounts for every number in 0 to 1000. In the body, check for either condition and append to the list, then print out the values in the list.
num is a list where you are going to store all the values that apply, (those numbers who are divisible by 3 and 5, which you calculate with modulo). You append to that list when a condition is met. Here is some code:
nums = []
n = 0
while (n < 1001):
if(n % 3 == 0 or n % 5 ==0):
nums.append(n)
n += 1
print(n) #or for loop for each value
Explanation: a list of numbers called num stores the numbers that are divisible by 3 or 5. The loop starts at zero and goes to 1000, and for all the values that are divisible by 3 or 5, they will be added to the list. Then it prints the list.
Of course there is a simpler approach with a range:
for i in range(1001):
if(i % 3 == 0 or i % 5 == 0):
print(i)
This will print out all the values one by one. It is 1001 because the upper limit is exclusive.
true=1
false=0
so:
x = n<1001
we have x=1 because 0<1001 is true
s = x%3 + x%5
the remainder of 1/3 is 1 and 1/5 is 1
In your code:
1. x=n<1001 - generates a boolean value; on which we can't perform a mathematical operation.
In while loop:
your variable n,x are not changing; they are constant to same value for all the iterations.
Solution 1:
Below code will help you out.
s=0
for i in range(1,1002):
if( i%3 == 0 or i%5 == 0):
s = s + i
print(s)
Solution: 2
There is one more approach you can use.
var = [i for i in range(1,1002) if i%3==0 or i%5 ==0]
print(sum(var))
I'm trying to write some code to compute the thousandth prime number and when I thought I was done I tried to run it but nothing is happening. I don't get errors or anything that should happen according to the code, just literally nothing. I'm running it in windows powershell if that matters. the code is here below. (Python 2.7)
n = 1
all_odd_integers = 2*n+1
prime_number = 2 #cause 3 is the second prime
while prime_number < 1000: #a while loop to get to prime thousand
for i in range (2, (all_odd_integers-1)): #because I want to divide all_odd_integers by all numbers except 1 and itsself and nothing bigger, but bigger than 0
if all_odd_integers % i == 0:
n += 1
print "not a prime" #because, like, if a number can be divided without a reminder it's not a prime
else:
n = n+1
prime_number += 1
print "a prime" #because exactly the opposite of the if-clause, here there is a reminder so prime
if prime_number == 1000:
print "the thousandth prime is %d" (all_odd_integers)
Your code isn't working because you have an infinite while loop, since your for loop isn't even being executed. You almost have the approach right for calculating the primes however.
If you want to print out every prime number as your current code would if it worked, you can much more easily implement something like this :
counter = 1
prime = 3
while counter != 1000:
for x in range(2,prime):
if prime%x == 0:
break
else:
print(prime)
counter += 1
prime += 2
Alternatively, if you only want to print out the thousandth prime I'm sure there are a plethora of more efficient ways, but I would lean towards something like this for simplicity and decent efficiency:
from math import sqrt
counter = 1
prime = 1
while counter < 1000:
prime += 2
for x in range(2,int(sqrt(prime+1)) + 1):
if prime%x == 0:
break
else:
counter += 1
print (prime)
I think you're thinking about this too hard. There are some errors to your code, but really it can all be boiled down to:
counter = 1
n = 2
while True:
n += 1
if all(n % i for i in xrange(2, n)): counter += 1
if counter == 1000: break
print "the thousandth prime is {0}".format(n)
This loops through all numbers between 2 and itself to see if any of them return a 0 remainder when n is divided by them. If none do, it's a prime and counter gets ticked, if not then it goes on to the next number. Once it finds 1000 primes it breaks and prints the thousandth prime is 7919
Some of the things wrong with your code:
all_odd_integers never changes. So when you do for i in range(2, (all_odd_integers-1)) it will never run anything except for i in range(2, 2) which is 0 because range excludes the higher number. all_odd_integers = 2*n+1 is only run once, when all_odd_integers is defined, it doesn't change when n does.
Even if all_odd_integers did update, why would you multiply it by two? Wikipedia has a prime defined as:
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
If n was 3 then all_odd_integers would be 7? Why would 3 need to be divided by 4-6?
Just a note: there is no need to check if prime_number is equal to 1000 at the end since that's why the code block broke.
What if you start with n=2 and prime_number = 3? that way you'll reach the for loop.
Like the other anwserers, the condition in the while loop never changes.
Look at your range() call:
range (2, (all_odd_integers-1))
When you call range, there is a start (2) and a stop (all_odd_integers-1).
range(1,5) generates: 1,2,3,4
Look at all_odd_integers:
all_odd_integers = 2*n+1
2*n+1 means 2*1+1 because n = 1 so 2*n+1 = 3 therefore you are calling range(2,2) which gives [] and then the loop is never executed at all.
EDIT: More things
This function gives you your odd integers.
def odd_integers():
odd_integers = []
for i in xrange(1001):
if i/2 != int(i/2);
odd_integers.append(i)
return odd_integers
Here's your new for:
for i in odd_integers():
The condition in your while loop is always true. prime_number doesn't ever change. Look again at your code
for i in range (2, (all_odd_integers-1)):
What is this supposed to do if n=1 and therefore all_odd_integers-1 = 2?
The code under this loop is never executed.
EDIT:
To loop over odd integers just do this:
for i in xrange(1,1000,2):