how to use while loop? - python

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

Related

I'm stuck with a prime number calculator

I'm reading a book about python programming for begginers.
One of it's tasks is to write a prime number calcutator that calculates 'n' prime numbers.
So far I've studied strings, logic gates, while and conditions.
The idea is to make it using only those operators.
I need help because I'm stuck with this code.
Here's what I've done:
odd = 3
number = 2
limit = int(input('How many primes do you need: '))
remnant = number % odd
even_remnant = number % 2
counter = 0
while counter <= limit:
if number == 2:
print('2')
number += 2
elif (number % 2) != 0:
remnant = number % odd
while odd < number:
print('while2')
remnant = number % odd
if (number % odd) != 0 and odd == (number - 1):
print(f'{number}.')
odd = 3
number += 1
counter += 1
break
elif (number % odd) == 0:
break
odd += 2
elif (number % 2) == 0:
number += 1
odd = 3
What do you think?
Thanks everyone.
Put your debugging pants on, we're going in.
First, the code doesn't run as it's written. The variables counter and impar are undefined. First step is to remove syntax errors like that. Looks like we want to start counter at 0 and the line that uses impar isn't necessary so we can delete it.
odd = 3
number = 2
limit = int(input('How many primes do you need: '))
counter = 0
while counter < limit:
if number == 2:
print('2')
number += 2
elif (number % 2) != 0:
while odd < number:
print('while2')
remnant = number % odd
if (number % odd) != 0 and odd == (number - 1):
print(f'{number}.')
odd = 3
number += 1
break
elif (number % odd) == 0:
break
odd += 2
elif (number % 2) == 0:
number += 1
odd = 3
Now the code runs without error, but all it does is print
2
while2
And then fails to terminate.
So we know we enter the while odd < number loop only once and we don't print anything during that loop. If we also print the value of odd and number while we are in there we see odd = 3 and number = 5. Neither of the if conditions are met and the odd += 2 line is hit. Now odd = 5 and the while loop exits without printing 5 even though 5 is prime. If we want to hit our print statement by meeting the condition odd == (number - 1) we better go in steps of 1 when incrementing odd. Let's change to odd += 1 and re-run the code.
Now when I say I need 2 primes it prints
2
5
7
And then prints while2 forever. At least it prints prime numbers! But it skipped 3 and printed too many, and I had to use Ctrl-C to quit the program. Too many primes were printed because the outer loop while counter <= limit: condition was never reached. Inside the loop, we never increase the value of counter. Whenever we print a prime, we need to increase counter.
Also, to make sure we print 3, take a look at the first if condition in the loop.
if number == 2:
print('2')
number += 2 # Oops, we skipped over 3
Let's update this:
if number == 2:
print('2')
print('3')
counter += 2 # Let's count both of these!
number += 2
Also adding counter += 1 after the other print, re-running the code we get
How many primes do you need: 2
2
3
5.
How many primes do you need: 3
2
3
5.
7.
Oops, we are getting one more than we need. This is because when counter == limit we run the while loop one more time. Let's change our while loop condition to while counter < limit:. That change gets us just the right number of primes.
How many primes do you need: 4
2
3
5.
7.
But if we ask for 5
How many primes do you need: 5
2
3
5.
7.
And the program never exits. If we check the values of odd and number, we see that the loops is running with odd=3 and number=9 over and over again.
Reason through the code when odd=3 and number=9. We break out of the while odd < number while loop when we hit this code
elif (number % odd) == 0
break
But we never increase the value of number, so it is still equal to 9 the next time through the loop. Let's update this to
elif (number % odd) == 0
number += 1
break
Now when we re-run the code we get
How many primes do you need: 5
2
3
5.
7.
11.
Huzzah! And it works when asking for more primes as well. Here is the code as it is currently:
odd = 3
number = 2
limit = int(input('How many primes do you need: '))
counter = 0
while counter < limit:
if number == 2:
print('2')
print('3')
counter += 2
number += 2
elif (number % 2) != 0:
while odd < number:
if (number % odd) != 0 and odd == (number - 1):
print(f'{number}.')
odd = 3
number += 1
break
elif (number % odd) == 0:
number += 1
break
odd += 1
elif (number % 2) == 0:
number += 1
odd = 3
Now that we have working code, let's improve it! One of our bugs was that we forgot to increase number by 1 in one case. Notice that no matter how we exit the outer while loop while counter <= limit: we want to increment number. So, instead of doing it in many places, let's move all of those to the end of the while block.
We also set odd=3 whenever exiting the while block. What we want to ensure is that odd=3 at the start of the while loop, so let's move that there. Now there is no more code in the elif (number % 2) == 0: block, so we can remove that line.
number = 2
limit = int(input('How many primes do you need: '))
counter = 0
while counter < limit:
odd = 3
if number == 2:
print('2')
print('3')
counter += 2
elif (number % 2) != 0:
while odd < number:
if (number % odd) != 0 and odd == (number - 1):
print(f'{number}.')
counter += 1
break
elif (number % odd) == 0:
break
odd += 1
number += 1
I think the code is more clear if the while loop ends when the condition is met, rather than on break statements. We want the while loop to end if we find the number is divisible by something, or we run out of numbers to check.
`while number % odd != 0 and odd < number:`
And the only thing we need to do in the while loop is increment odd. Then after the loop, we can check the value of odd to see which condition was met.
number = 2
limit = int(input('How many primes do you need: '))
counter = 0
while counter < limit:
odd = 3
if number == 2:
print('2')
print('3')
counter += 2
elif (number % 2) != 0:
while number % odd != 0 and odd < number:
odd += 1
if odd == number: # No divisor was found!
print(f'{number}.')
counter += 1
number += 1
Notice that we are "hard coding" the divisibility by 2 (number % 2) != 0 and then using the variable odd to check divisibility by everything else. If we start odd at 2 instead of 3, we don't have to do the hard coding.
number = 2
limit = int(input('How many primes do you need: '))
counter = 0
while counter < limit:
odd = 2
if number == 2:
print('2')
print('3')
counter += 2
while number % odd != 0 and odd < number:
odd += 1
if odd == number: # No divisor was found!
print(f'{number}.')
counter += 1
number += 1
When we make this change, we also notice that we find the primes 2 and 3 twice, so we can remove the hard coded version of those:
number = 2
limit = int(input('How many primes do you need: '))
counter = 0
while counter < limit:
odd = 2
while number % odd != 0 and odd < number:
odd += 1
if odd == number: # No divisor was found!
print(f'{number}.')
counter += 1
number += 1
When I try to run this code it tells me that Counter is not set, so right before entering the loop set Counter to 0.
Another problem is that you start by finding 2 in the first case of your loop, this is nice. Here after the loop runs again, now with number set to 4. Because of your += 2 instruction.
It then runs the last elif case. where (number % 2) == 0. here it set number = 5, and odd = 3. But it doesn't print 3. I think you mean to do this.
Now it runs the loop again, and enter the second elif case (number % 2) != 0.
The first line in the elif clause the variable impar is not defined so it will fail.
I can't understand your program but it's good
def is_prime(n):
st = "prime" # being prime status
for i in range(2,n):
if n % i == 0: # if number is prime
st = "not prime"
break;
return st
n = int(input("enter n: "))
pc = 0 # prime conter
c = 1 # counter
while n != pc:
if is_prime(c) == "prime":
print (c)
pc += 1
c += 1
To calculate 'n' number for prime numbers you needn't use so many statements, if you make use of the the arithmetic and logical or bit-wise operators, which you will be learning in the future chapters of the python book you're referring.
I shall help you by editing the code for you.
number = int(input("Enter range: "))
print("Prime numbers:", end=' ')
for n in range(2, number):
for i in range(2, n):
if n % i == 0:
break
else:
print(n, end=' ')

Repeat a process until a condition is reached

I need to create a program in which it allows the user to choose the quantity of perfect combinations that they want to see. A combination is perfect when the number is multiple of 3 and 5. For example if I have input 5 the program will need to start from 0 and once it reaches the number that is perfect shows a "perfect" each time it is perfect
I have been trying to use:
combi = (int(input())
count = 0
for i in range(combi):
if (i % 3 == 0 and i % 5 == 0):
print("Perfect")
I do not know how to make it count since 0 until we have 5 numbers which are perfect
Use the break statement:
combi = (int(input())
count = 0
for i in range(combi):
if (i % 3 == 0 and i % 5 == 0):
print("Perfect")
count += 1
if count == 5:
break

What does 'n' mean in this program (python)?

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

Taking away from nearest 10

Okay, i have made my code so that a user can input 7 numbers and times them by 1 for the odd index numbers and 3 for the even:
num = str(input("Please enter 7 numbers")
length = len(num)
while length < 7 or length ? 7:
num = input("Only enter 7 numbers")
string = ''
for t in range(1,8):
if t % 2 == 0:
string += str(t * 3)
else:
string += str(t) + ' '
print(string)
This works fine, but now i need to add all the numbers up and take it away from the highest 10 so for example, all the numbers add up to 53 i need to take that away from 60 which leaves me 7, that will be my eight number, then after i have got that number i print it out, how do i get it to add the numbers up and the take it away from the highest 10 and output the difference of the two into the numbers i already have?
Thanks
Brad
If you have a number, x, which is equal to 53, then going up should be math.ceil(x) except that math.ceil() rounds for 1. To account for that, we divide by 10, use math.ceil(), and then multiply by 10 again:
import math
rounded_up = math.ceil(x / 10) * 10
result = rounded_up - x
Brad could you clarify your question? Also your above code does not work.
Missing a bracket on the first line and this isn't valid while length < 7 or length ? 7:
I believe this is what you're looking for:
def take_away_from_nearest(number, nearest):
return nearest - (number % nearest)
Usage:
>>> take_away_from_nearest(53, 10)
7
edit:
If I understand you correctly, this would be the entire code:
while True:
# this is just an easy way to keep asking until the input is correct
num = input("Please enter 7 numbers: ")
if len(num) == 7:
break
weird_sum = 0 #here's where we're gonna sum up the numbers; the "eighth number"
for index, character in enumerate(num):
if index % 2 == 0: # index is odd, so count the character thrice
print(3 * int(character))
weird_sum += 3 * int(character)
else: # index is even
print(int(character))
weird_sum += int(character)
print(10 - (weird_sum % 10)) # 10 minus (weird_sum modulo 10)
# and finally, adding them all up and checking whether it ends with 0:
print((10-(weird_sum % 10) + weird_sum) % 10 == 0) # prints True

Numbers without remainder python

I need to print out numbers between 1 and n(n is entered with keyboard) that do not divide by 2, 3 and 5.
I need to use while or for loops and the remainder is gotten with %.
I'm new here and I just don't understand the usage of %?
I tried something like this:
import math
print("Hey. Enter a number.")
entered_number = int(input())
for i in range(1, entered_number):
if i%2 != 0:
print("The number", i, "is ok.")
else:
pass
if i%3 != 0:
print("The number", i, "is ok.")
else:
pass
if i%5 != 0:
print("The number", i, "is ok.")
help?
You need to test for all 3 conditions in one statement, not in 3:
for i in range(1, entered_number):
if i % 2 != 0 and i % 3 != 0 and i % 5 != 0:
print("The number", i, "is ok.")
The and operators here make sure that all three conditions are met before printing.
You are testing each condition in isolation, which means that if the number is, say, 10, you are still printing The number 10 is ok. because it is not divisible by 3. For numbers that are okay, you were printing The number ... is ok. 3 times, as your code tests that it is not divisible by 3 different numbers separately, printing each time.
If something divides by 7 then:
something % 7 == 0
If something divides by 7 and 9 then:
something % 7 == 0 and something % 9 == 0
Conversely, if something divides by 7 or 9 then:
something % 7 == 0 or something % 9 == 0
Something that does not divide by 7 or 9 is given by the expression:
not (something % 7 == 0 or something % 9 == 0)
You don't require the else: pass bits from your code and one if statement with an if-expression that has three %, == bits in it should suffice.
You should probably check the three conditions at the same time:
if i%2 != 0 and i%3 != 0 and i%5 != 0:
print("The number", i, "is ok.")
Otherwise, you would print the same message several times for a single number.
Anyway, for your second question, the% operation is called modulo and it gives you the remainder of a division. For instance, 5%3 = 2 because 5 = 3*1 + 2. And when you check i%2 != 0, you actually check if i can be divided by 2.
print("Hey. Enter a number.")
entered_number = int(input())
for i in range(1, entered_number):
if i%2 != 0 and i%3 !=0 and i%5!=0:
print("The number", i, "is ok.")
a%b returns the remainder when a is divided by b. Example:
>> 5%3
2
What you are doing wrong here is that you are printing after checking a single condition so it will print even if i is divisible by other numbers. For example if i is 3, it will satisfy the first condition and therefore print that the number is ok but it is actually divisible by 3.
I saw you've solved your problem but my answer may worth reading.
This problem is actually doing filtering over a list of numbers 1..n. You can define a base function to test if number x is dividable by number y, and then use this base function to filter the list to get the result.
Here's my version.
import math
from functools import partial
print("Hey. Enter a number.")
entered_number = int(input())
def not_dividable_by(x, y):
return False if x % y == 0 else True
number_list = range(1, entered_number)
for i in [2, 3, 5]:
test_func = partial(not_dividable_by, y=i)
number_list = filter(test_func, number_list)
for number in number_list:
print("%d is OK" % (number,))

Categories

Resources