Simple python while loop troubles - python

So Im just wondering why my code below is not functioning as expected,i want it to keep adding odd values to the odd count when given an odd number, likewise with the evens. but no matter what i put, it just adds it to the odd count. suggestions?
odd_value = 0
even_value = 0
x = int(input('enter'))
while x != 0:
if x == 3 or 5 or 7 or 9:
odd_value += x
elif x == 2 or 4 or 6 or 8:
even_value += x
x = int(input('enter'))
print('The sum of the odds is ',odd_value)
print('The sum of the evens is' ,even_value)

You've created an infinite loop. x will never equal to 0, and hence your loop will always keep going. It doesn't have an exit point. You can use a break statement anywhere to get out of the loop when you want.
Also, your logic is wrong:
if x in (3, 5, 7, 9):
odd_value += x
elif x in (2, 4, 6, 8):
even_value += x
or...
if x == 3 or x == 5 or x == 7 or x == 9:
odd_value += x
elif x == 2 or x == 4 or x == 6 or x == 8:
even_value += x
Now it evaluates each individual statement properly, instead of just seeing something that is implicitly True.
Here's why your original statements don't work:
>>> if x == 3 or 5 or 7 or 9:
... print "Oh Darn!"
Oh Darn!
Let's see this in english:
if x is equal to 3 # Nope!
if 5 # That's True so let's go on!
Execute the if code block
Forget the elif code block

Related

is there a way to make the x odd

I have been trying to make a simple code with python in which it takes an input 'n' and outputs the numbers from 1 to n
for each multiple of 3, print Solo instead of the number
for each multiple of 5, print Learn instead of the number
for numbers which are multiples of both 3 and 5, output SoloLearn
I want to code it in a way that the logic will skip the even numbers and can only be applied to odd numbers in the range
this is my code below
n = int(input())
for x in range(1, n):
if x % 3 == 0 and x % 5 == 0:
print("SoloLearn")
elif x % 3 == 0:
print("Solo")
elif x % 5 == 0:
print("Learn")
else:
print(x)
Add a continue clause at the top of your loop:
if x % 2 == 0:
continue
For more details, read the docs.
The simplest/fastest/smallest amount of changes you need to make is to just alter the range function to give you exactly what you want.
n = int(input())
for x in range(1, n + 1 , 2):
if x % 3 == 0 and x % 5 == 0:
print("SoloLearn")
elif x % 3 == 0:
print("Solo")
elif x % 5 == 0:
print("Learn")
else:
print(x)
I added n+1 not to satisfy your question, but because I think as written your code was not correct -> for example run these two snippets and see what I mean. If you didn't want n to be part of the range than your code is correct without the n+1.
print("no +1")
for i in range(1,11,2):
print(i)
print("\n\nwith + 1"
for i in range(1,11+1,1):
print(i)
Convert the 'for' loop to 'while' loop . Since we are starting with 1 , adding 2 in each iteration , makes the loop run only for odd numbers.
n = int(input())
x=1
while x<n:
if x % 3 == 0 and x % 5 == 0:
print(x ,"SoloLearn")
elif x % 3 == 0:
print(x, "Solo")
elif x % 5 == 0:
print(x, "Learn")
else:
print(x)
x=x+2

If/Else Program wont print index

I am writing a program that will print a list of numbers 1:n. However, every number divisible by 2 should be replaced with 'x' and every number divisible by 3 should be replaced with 'y'. Lastly, every number both divisible by 2 and 3 should be replaced with 'xy'. This is my code so far, I can get the function to print the correct result with my input. But it wont print the entire list of numbers. Instead I am just getting the end result (x,y, or xy) for the given input. Here is my code thus far with the output.
def replace(n):
for i in range(n):
print(i)
if n%2== 0 and n%3 == 0:
return 'xy'
elif n%2==0:
return 'y'
elif n%3 == 0:
return 'x'
else:
print(i)
replace(12)
This is my output:
0
'xy'
I would like the output to be something like:
1
x
y
x
5
xy
7
x
y
x
11
xy
Any advice would be appreciated, you guys rock!
Your code has multiple errors:
At line 4, you print(i) - this means that each number will be printed
At lines 6, 9 and 12 you are using the n variable instead of i in the modulo operation
You want to check for numbers [1, n], but your loop checks for [0, 11]
You return instead of printing - the return keyword will stop the function's execution (and thus the loop) and return the value you specified. In case you are confused, consider the following example:
def get_number():
return 5
print("This will never print, as the function has already returned")
number = get_number() # number now equals 5, since it was returned
get_number() # 5 still gets returned, but is never assigned to a variable
Here is the code that gives the output that you mention above:
def replace(n):
for i in range(1, n + 1):
if i%2 == 0 and i%3 == 0:
print('xy')
elif i%2 == 0:
print('x')
elif i%3 == 0:
print('y')
else:
print(i)
replace(12)

Python: print even numbers including 0

Given a program that outputs all the numbers from 0 to 10, I must print only the even numbers. I'm using this code:
x = 0
while x <= 10:
x += 1
if x % 2 == 0:
print(x)
The output shows numbers from 2 to 10, excluding 0, which I need to include.
How can I print even numbers from 0 to 10?
Thanks!
** Note: I'm a beginner, so any explanation is extremely helpful.
x = 0
while x <= 10:
if x % 2 == 0:
print(x)
x += 1 # increment x AFTER the if statement, otherwise you never check if 0%2 == 0
You could also use a for-loop to simplify things further:
for x in range(11):
if x%2 == 0:
print(x)
As others have said, the problem is that you're incrementing x before you check if it's even, so you increment from 0 to 1 before printing.
But there's no need for the test, you can just loop over the even numbers:
for x in range(0, 11, 2):
print(x)
The third argument to range() is the steps, and stepping by 2 just returns even numbers.
Increment x after the if block.
hmmm....can you ask quiz questions on here? anyhow, I think the small edit to the order of operations in your loop should do it?
x = 0
while x <= 10:
if x % 2 == 0:
print(x)
x += 1
This can be esaily done with the for loop:
for i in range(11):
if i % 2 == 0:
print(i)
and that's all it takes, 3 lines :)
Its fine!
x = 0
while x <= 10:
if x % 2 == 0:
print(x)
x += 1
A slightly different slant on a on-liner ... just for fun.
print(*(i for i in range(0, 11, 2)))
>>> 0 2 4 6 8 10

Python prime number generator prints out every number

I made this prime number generator but it just prints every number (1, 2, 3...).
I am aware that there are other questions about this but I don't understand any of them. Here is what I have so far:
x = 1
y = 1
while x >= y:
if x % y == 0:
print(x)
x = x + 1
y = 1
else:
y = y + 1
y = 1
From your question, I think, it would be better try this way :
n = 10
i = 2
while i < n :
prime = 1 # reset the `prime` variable before the inner loop
for a in range(2, i):
if i%a == 0:
prime = 0
break
if prime:
print (i)
i += 1
Output :
2
3
5
7
There's something called a rubber ducky test where you explain your code, step by step, to a rubber duck. It forces you to walk through every step and you'll often find the error. In this case, think about what y is when you do x%y. You'll see that y=1 the first time this is called. So it will iterate through the loop incrementing x by 1 and y will remain set it 1. And x%y when y=1 will always be...

How to make list double every other term, and add 2 digit numbers?

numbers = raw_input("Enter numbers: ")
numbers = [numbers]
numbers = list(numbers[0])
numbers = [int(x) for x in numbers]
numbers[::2] = [2*x for x in numbers[::2]]
for x in numbers: #code stops working as i want here
if x == 10:
x = 1
elif x == 12:
x = 3
elif x == 14:
x = 5
elif x == 16:
x = 7
elif x == 18:
x = 9
print(numbers)
Basically I want it to take the numbers I give it, put it into a list, split that list, change all elements in the list to integers, and for every other element in the list, double it, and (here's where it stops working) take the possible 2 digit numbers from doubling 5, 6, 7, 8, or 9 and add the digits.
I think the for, if, and elif statements are right but I think their bodies are wrong. What do I do to change x if it's not like a variable? (x = 1)
Or am I doing the last step all wrong? Thanks.
The assignment x = 1 is simply rebinding the name x to the value 1. This does not modify the contents of numbers.
If you want to change a value contained in a list you must explicitly do so by using:
numbers[index] = value
For example:
for i, x in enumerate(numbers):
if x >= 10: # not actually required: 0<= x < 10 implies x%10 == x and x//10 == 0
numbers[i] = x%10 + x//10
Note that if you have a two digit number then x % 10 is equal to the first digit while x // 10 (integer division/quotient) is equal to the second digit.
In fact you could even do:
numbers[i] = sum(divmod(x, 10))
You can not change the variable indicating an item in a collection due to loop scope. Try this instead:
for i, x in enumerate(numbers):
numbers[i] = sum(map(int, str(x)))
def f(x):
if x in (10, 12, 14, 16, 18):
return x-9
else return x
Instead of the loop at the end,
numbers = [f(n) for n in numbers]
Of course, you can put the definition of f in the list comprehension, but it starts looking a bit cramped.

Categories

Resources