Increment the variable num by 1 post checking the above condition. (note that this increment will be outside the if statement, take care of the indentation in order to avoid a scenario of infinite loop)
this is the problem statement but I don't know what exactly is indented
I don't know if its correct or not
num = 1
factors=[ ]
while num <= 100:
if (num % 10) == 0 :
factors.append(num)
num += 1
print(factors)
I think this is the answer to your question
num = 1
factors = []
while num <= 100:
if (num % 10) == 0:
factors.append(num)
num += 1
print (factors)
Python uses indentation to indicate nested blocks of code, in this example you have a block of code within your while loop, indicated by the 4 space indentation. You then have an if statement when then also needs it's content indented by another 4 spaces. This would give you the following result:
num = 1
factors = []
while num <= 100:
if (num % 10) == 0:
factors.append(num)
num += 1
print(factors)
Related
I'm writing a program that finds the multiple of a number between 1 and 10. The code currently skips over the if statement and immediately performs the else statement which is an error message even if an "accepted" value is entered. I also need it to repeat the multiples until it gets to 100 or above then it should stop. I tried changing around the ands and ors with no success and swapped the if and while statements around again to no success. The program looks like this:
check3 = False
num = int(input("Enter a number between 1 and 10: "))
if num <= 10 or num >= 1:
while not num <= 100:
num += num
print(num)
else:
print("Not in range. Try again.")
Like multiple people commented, there are a couple of problems.
I will walk you through them and then provide a commented working example.
Code walkthrough
check3 = False
num = int(input("Enter a number between 1 and 10: "))
# This condition can be rewritten without or/and to make it simpler to understand
# Check example below.
# (Also, if you were to write it like this,
# then the if would execute if either condition is true.
# Meaning it would execute if num is -50 because -50 <= 10.)
if num <= 10 or num >= 1:
# This while will run when NOT (number less than 100)
# So the while will only run when number is greater than 100
# You want the opposite of this actually
while not num <= 100:
# If you keep adding num to itself you will not get the multiples
# Example: num = 10
# round 1: num = 10+10 (num is now 20)
# round 2: num = 20+20 (num is now 40)
# etc
num += num
print(num)
# This else is indented at the same level as the while...
# So it will actually trigger when the condition is false.
else:
print("Not in range. Try again.")
So basically what's happening when you run your code is that since num is less than 100, the while will not run and execution will jump to the else.
Working example
num = int(input("Enter a number between 1 and 10: "))
if 1 <= num <= 10:
# it's better to set another variable because if you keep doing num+=num
# for num = 10 you will get num = 10+10 on the first loop (so num is 20 now)
# num = 20 + 20 on the second loop, etc...
multiples = 0
while not multiples >= 100:
multiples += num
print(multiples)
# the else needs to be indented at the same level as the if
else:
print("Not in range. Try again.")
End notes on boolean logic:
A OR B is true if either are true or if both are true.
A AND B is only true if both are true.
In summary, I know 2 is a prime number because it is divisible by 1 and itself but why does it still print 2 if 2%2 = 0 and the range is between 2 and the number you're checking, which in this case is 2. Shouldn't it start at 3?
for num in range (1, 1000):
if num > 1:
for i in range (2, num):
if (num % i ) == 0:
break
else:
print (num)
I expected 3 to be the first output.
2 is printed because for i in range(2, num) performs no iterations when num == 2. This is because the second argument to range() is not included in the list that range() generates. So for the 2 iteration of your outer loop, the equivalent iteration code is:
num = 2
if num > 1:
for i in []:
if (num % i ) == 0:
break
else:
print (num)
which will print 2 since the 'break' line won't be executed.
Python for loops include the first number, but exclude the last number. Because of this, the clause for i in range(2,2) won't actually return any numbers. This is why the number 2 gets printed in your else block.
It also helps to keep your if and else blocks at the same indent level to avoid confusing the computer.
this is an even odd calculator that runs infinitely without any errors. Does anyone know how to fix this? Is it ok for me to call the method with the input from times?
def calc(time):
i = 1
while i <= time:
num = int(input("Enter your number"))
i + 1
x=0
y=0
if (int(num) % 2 == 0):
even = True
print("even")
elif (int(num) % 2 != 0):
odd = True
print("odd")
if (odd == True):
x += 1
elif (even == True):
y += 1
times = int(input("How many numbers will you be putting in this calc?"))
calc(times)
Just a few things you have wrong, the rest are pretty good, explain are in the comments:
All the variables in [x, y , even , odd] are useless at all, so that's why I erased them.
def calc(time):
i = 1
while i <= time:
num = int(input("Enter your number"))
i+=1 # important thing here, to update the value the symbol is +=, not just +
if (int(num) % 2 == 0):
print("even")
else: # there is no need of elif, if the number is not even, by definition, it is odd
print("odd")
times = int(input("How many numbers will you be putting in this calc?"))
calc(times)
you can try it here, and see how do correctly the job :) -> https://repl.it/Nm70/0
Line number 5 should be i = i+1
I'm assuming you have a formatting issue with stackoverflow and not a formatting issue with your actual code. The lines after your while loop need to be indented which I'm assuming you are doing. The problem you have is that you aren't incrementing i. The first line after your input you have i + 1. That does nothing as you aren't assigning it to anything. You have x += 1 and y += 1 later on in your code which increments and assigns. So basically change your i+1 line to be i += 1 or i = i + 1
Everything that you want in the while loop needs to be indented by one "tab" like so:
while i <= time:
#Code goes here
I am supposed to write a program that displays numbers from 100 to 200, ten per line, that are divisible by 5 or 6 but NOT both. This is my code so far. I know it's a basic problem so can you tell me the basic code that I'm missing instead of the "shortcut" steps. Any help is appreciated!
def main():
while (num >= 100) and (num <= 200):
for (num % 5 == 0) or (num % 6 == 0)
print (num)
main()
This is how I would go about it. I would recommend using a for loop over a while loop if you know the range you need. You are less likely to get into an endless loop. The reason for the n variable is since you said you needed 10 numbers per line. The n variable will track how many correct numbers you find so that you know when you have ten results and can use a normal print statement which automatically includes a newline. The second print statement will not add a newline.
n = 0
for i in range(100,201):
if (i%5 == 0 or i%6 == 0) and not (i%5 == 0 and i%6 == 0):
n += 1
if n%10 == 0:
print(i)
else:
print(str(i) + ", ", end="")
You should init every variable using in the code
While (condition) will break when the condition false. Since your condition depends on num, but num is never changed in your code, infinity loop will happen. You need to add num = num + 1 at the end of your loop block.
It's supposed to use if not for for each iterator here. And the condition you used for your problem is wrong to.
Should be like this:
def main():
num = 100
while (num >= 100) and (num <= 200):
if ((num % 5 == 0) or (num % 6 == 0)) and (num % 30 != 0):
print (num)
num = num + 1
main()
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