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
Related
Hello while I was practicing while loop in Python my code was not giving any outputs whatsoever. I am learning python from books only, so it may sound basic: but where is the problem in this code? I was trying to print integers less than 100 which are not divisible by 5.
x=0
while (x<101):
if (x%5==0):
continue
print (x, end=" ")
x=x+1
I was trying to print integers less than 100 which are not divisible by 5
continue goes back to the beginning of the loop, skipping over the rest of the body. This means it skips over x = x + 1. So you keep testing the same value of x.
Instead of a while loop, use a for loop, so the increment isn't in the body that you skip over.
for x in range(100):
if x % 5 == 0:
continue
print(x, end=" ")
If you really want to use while and continue, you can duplicate the code that increments x.
while x < 101:
if x % 5 == 0:
x += 1
continue
print(x, end=" ")
x += 1
Or you could move the increment before the test
while x < 101:
x += 1
if x % 5 == 1:
continue
print(x-1, end=" ")
But notice that this makes it more complicated because you have to subtract 1 when printing to get the value from before the increment.
You should try stepping through your code with a debugger before posting a question here. If you had done this you would have found the problem right away.
Your code gets stuck in an infinite loop. Try this:
x=0
while (x<101):
if (x%5 != 0):
print (x, end=" ")
x=x+1
You got an infinite loop on execution...
when x is 0, it's true, the loop continue on next execution
but x is not incremented. So on the next loop execution, the same result: 0 % 5 == 0 returns true
Solution: increment x before the continue;
so you'll have:
x=0
while (x<101):
if (x%5==0):
x=x+1
continue
print (x, end=" ")
x=x+1
This should be fine !
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.
I'm a absolute beginner, and when I made a function to count the number of even ints on a given list, it didn't went as expected, and I can't see where I'm doing it wrong.
nums = [2,2,4,4,5,6,7,8,9]
def count_even(nums):
for number in nums:
num = 0
if number % 2 == 0:
num += number
return num
else:
continue
The output is:
count_even(nums)
2
It stops on nums[1] for some obscure reason.
Or it just prints the first "2" and adds it, and I don't know how to fix it, yet.
You have three problems here.
You're setting num = 0 every time through the loop, instead of just once at the start. So you're only going to get the very last count that you do.
You're doing num += number, instead of num += 1, so instead of counting the even numbers, you're adding them.
You're doing a return num as soon as the first even number is found, instead of only at the end of the function, after the loop. (And that also means that if there are no even numbers, instead of returning 0, you return None).
While we're at it, you don't need else: continue, because continuing is already what happens by default when you fall off the end of a loop.
Anyway, this means it's not stopping at nums[1], it's stopping at nums[0]—but it's adding 2 instead of 1 there, which makes things confusing. (It's always fun when bugs interact like that. Even more fun when they happen to exactly cancel out for your test case, like if you did nums = [6,2,4,4,5,6,7,8,9] and got back 6 and thought everything was working…)
So:
def count_even(nums):
num = 0
for number in nums:
if number % 2 == 0:
num += 1
return num
Your function stops on nums[1] because the return keyword exits the function and returns num (which is set to 0 + number). If you want to print out the sum of all the even numbers in nums you could move the return statement to the end and take the num = 0 expression out of the for loop (because it will reset to 0 after each iteration), like this:
def count_even(nums):
num = 0
for number in nums:
if number % 2 == 0:
num += number
else:
continue
return num
Also, your else statement is redundant here, so you could simply remove it, leaving you with the following:
def count_even(nums):
num = 0
for number in nums:
if number % 2 == 0:
num += number
return num
And you could simplify that further to:
def count_even(nums):
evens = [number for number in nums if number % 2 == 0]
return sum(evens)
Another solution:
def count_even(nums):
return len([i for i in nums if i % 2 == 0])
There are a couple of problems in your code:
Your num needs be defined outside the loop, so you can count every even number found. If you define it inside the loop, it resets to 0 every iteration.
When you find an even number, you increment it towards the counter num. You need to instead increment num by 1.
You return immediately when a even number is found, this means the function exits on the first even number. You instead want to return the total num at the end.
You have an unnecessary continue in the else block. If a uneven number is found, simply ignore it.
Which these suggestions, you could implement your code like this:
nums = [2,2,4,4,5,6,7,8,9]
def count_even(nums):
num = 0
for number in nums:
if number % 2 == 0:
num += 1
return num
print(count_even(nums))
# 6
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
I'm trying to print the factors of the number 20 in python so it goes:
20
10
5
4
2
1
I realize this is a pretty straightforward question, but I just had a question about some specifics in my attempt. If I say:
def factors(n):
i = n
while i < 0:
if n % i == 0:
print(i)
i-= 1
When I do this it only prints out 20. I figure there's something wrong when I assign i=n and then decremented i, is it also affecting n? How does that work?
Also I realize this could probably be done with a for loop but when I use a for loop I can only figure out how to print the factors backwards so that I get: 1, 2, 5, 10....
Also I need to do this using just iteration. Help?
Note: This isn't a homework question I'm trying to relearn python on my own since it's been a while so I feel pretty silly being stuck on this question :(
while i < 0:
This will be false right from the start, since i starts off positive, presumably. You want:
while i > 0:
In words, you want to "start i off at n, and decrement it while it is still greater than 0, testing for factors at each step".
>>> def factors(n):
... i = n
... while i > 0: # <--
... if n % i == 0:
... print(i)
... i-= 1
...
>>> factors(20)
20
10
5
4
2
1
The while condition should be i > 0 and not i < 0 because it will never satisfy it as i begins in 20 (or more in other cases)
Hope my answer helps!
#The "while True" program allows Python to reject any string or characters
while True:
try:
num = int(input("Enter a number and I'll test it for a prime value: "))
except ValueError:
print("Sorry, I didn't get that.")
continue
else:
break
#The factor of any number contains 1 so 1 is in the list by default.
fact = [1]
#since y is 0 and the next possible factor is 2, x will start from 2.
#num % x allows Python to see if the number is divisible by x
for y in range(num):
x = y + 2
if num % x is 0:
fact.append(x)
#Lastly you can choose to print the list
print("The factors of %s are %s" % (num, fact))