Python: .count() doesn't count - python

I'm writing a simple program that takes user input and prints the number of even, odd and zeros.
The program doesn't yield any errors but it seems to skip line 5 and 15
I want to count and display the zeroes in the numbers list
numbers = input("Numbers seperated by space:").split()
print("Numbers:" + str(numbers))
zero = numbers.count(0)
even = 0
odd = 0
for i in numbers:
if int(i) % 2 == 0:
even += 1
else:
odd += 1
even = even - zero
print("Even:" + str(even))
print("Odd:" + str(odd))
print("Zero:" + str(zero))

Youre code isnt working because inputs in Python are strings. So when you enter a number like 5, Python turns it into "5". So to make your code work change .count(0) to .count("0")
numbers = input("Numbers seperated by space:").split()
print("Numbers:" + str(numbers))
zero = numbers.count("0")
even = 0
odd = 0
for i in numbers:
if int(i) % 2 == 0:
even += 1
else:
odd += 1
even = even - zero
print("Even:" + str(even))
print("Odd:" + str(odd))
print("Zero:" + str(zero))
Output:
Numbers seperated by space:
5 0 0 2
Numbers:['5', '0', '0', '2']
Even:1
Odd:1
Zero:2
If you are sure that only numbers are the input you could also do
numbers = [int(elem) for elem in input("Numbers seperated by space:").split()]
zero = numbers.count(0)

When counting evens, zeros may get added so I would check for this condition first
numbers = input("Numbers separated by space:").split()
print("Numbers:" + str(numbers))
zero = 0
even = 0
odd = 0
for i in numbers:
if int(i) == 0:
zero += 1
elif int(i) % 2 == 0:
even += 1
else:
odd += 1
# using f-string to format output instead
print(f"Even: {even}")
print(f"Odd: {odd}")
print(f"Zero: {zero}")

numbers = input("Numbers separated by space:").split()
zero = numbers.count("0")
even = 0
odd = 0
for i in numbers:
if int(i) % 2 == 0 and i != '0':
even +=1
elif int(i) %2 !=0 and i != '0':
odd +=1
print("Even:" + str(even))
print("Odd:" + str(odd))
print("Zero:" + str(zero))

Related

How do I keep a loop going with a variable that changes in every loop

So I'm new to coding and I'm struggling with the following exercise
So we start with a random number and we have to count the even numbers and the odd numbers. With this, we make a second number that starts with the amount of the even numbers, amount of the odd numbers, and the amount of numbers in total. We should continue this until the number 123 is reached.
For example:
number = 567421 --> odd numbers = 3 , even numbers = 3 , total numbers = 6 --> new number = 336 -->...
I had an idea to write it like this:
number = input()
evennumbers = ''
oddnumbers = ''
a = len(number)
while number != '123':
for i in str(number):
if int(i) % 2 == 0:
evennumbers += i
else:
oddnumbers += i
b = len(evennumbers)
c = len(oddnumbers)
number = input(print(f"{b}{c}{a}"))
But I have no idea how to keep this loop going with the variable 'number' until 123 is reached
You need your variable initialization to be inside the while loop, and remove the input(print(... on the final line.
number = '567421'
while number != '123':
print(number)
evennumbers = ''
oddnumbers = ''
a = len(number)
for i in str(number):
if int(i) % 2 == 0:
evennumbers += i
else:
oddnumbers += i
b = len(evennumbers)
c = len(oddnumbers)
number = f"{b}{c}{a}"
You could simplify like this:
while number != '123':
print(number)
total = len(number)
odds = sum(int(digit) % 2 for digit in number)
evens = total - odds
number = f"{evens}{odds}{total}"

How can I retain zero in python for calculation?

So I supposed to verify if the input number is a UPC number or not. I have to allowed leading zeros and accounted it in the calculation.
Here is my current code, it works for all number except number has leading zeros:
Condition for UPC code valid:
Calculate the sum of multiplying odd digit index by 3 and even digit index by 1 of the input number.
Calculate the sum we just did modulo 10, get result digit.
If the resulting digit is between 1 and 9 then subtract result digit from 10. If the result digit is 0, add 0 to the to the base number to get the completed number.
def UPC_code(num):
sum_digit = 0
index = 0
num_temp = str(num)[:-1]
len_nt = len(num_temp)
for digit in num_temp:
if (index + 1) % 2 != 0: # If number position is odd
sum_digit += int(digit) * 3 # Sum = digit * 3
if index < len_nt: # Increase index till end
index += 1
elif (index + 1) % 2 == 0: # If number position is even
sum_digit += int(digit) * 1 # Sum = digit * 1
if index < len_nt:
index += 1
# print(sum_digit)
res_digit = sum_digit % 10
if 1 <= res_digit <= 9:
res_digit = 10 - res_digit # Res digit meet condition = 10 - res digit
if res_digit == num % 10:
return True
elif res_digit != num % 10:
return False
else:
print("Something went wrong")
# End UPC_code()
Call UPC_code()
import code_check.py as cc
num = str(input())
num_int = int(num)
if cc.UPC_code(num_int) is True and num_int != 0:
print(num, "valid UPC code.")
else:
print("Not valid")
Expected input:
042100005264
Expected output:
042100005264 valid UPC code
Actual output:
Not valid
it works for all number except number has leading zeros
As you have doubtless discovered, python does not allow you to write 0700. Historically that would have meant 0o700, or 448, which is likely not what you want anyhow...
In this case the solution is simple. If you need to handle numbers like 00007878979345, handle strings.
Thus refactor your code to take a string. As a bonus, int("000008") is 8, so when you need the number as a number you don't even have to do anything.

Finding even numbers with while as

I'm doing this assignment:
Write a program that prints all even numbers less than the input
number using the while loop.
The input format:
The maximum number N that varies from 1 to 200.
The output format:
All even numbers less than N in ascending order. Each number must be
on a separate line.
N = int(input())
i = 0
while 200 >= N >= 1:
i += 1
if i % 2 == 0 and N > i:
print(i)
and its output like:
10 # this is my input
2
4
6
8
but there is an error about time exceed.
The simple code would be:
import math
N = int(input(""))
print("1. " + str(N))
num = 1
while num < math.ceil(N/2):
print (str(num) + ". " + str(num * 2))
num += 1
The problem is that the while loop never stops
while 200 >= N >= 1 In this case because you never change the value of N the condition will always be true. Maybe you can do something more like this:
N = int(input())
if N > 0 and N <= 200:
i = 0
while i < N:
i += 2
print(i)
else
print("The input can only be a number from 1 to 200")

In Python, how do I print only the final answer in a while loop when adding values between 1 and 20

So this is what I've got. The output is every answer leading up to the final outcome of Odd = 100 and Even = 110. I was hoping someone could maybe suggest what I could do to only print the final answers rather than the whole list of iterations.
Thanks a million x
#inputs
odd = 0
even = 0
counter = 0
# calculations for even numbers
while counter <= 20 and counter % 2 == 0:
even = even + counter
print("The sum of the EVEN numbers between 1 and 20 is", even)
counter += 1
# calculations for odd numbers
if counter <= 20 and counter % 2 != 0:
odd = odd + counter
print("The sum of the ODD numbers between 1 and 20 is", odd)
counter += 1
use the print statement after incrementing the counter, outside the while loop
#inputs
odd = 0
even = 0
counter = 0
# calculations for even numbers
while counter <= 20 and counter % 2 == 0:
even = even + counter
counter += 1
# calculations for odd numbers
if counter <= 20 and counter % 2 != 0:
odd = odd + counter
counter += 1
print("The sum of the ODD numbers between 1 and 20 is", odd)
print("The sum of the EVEN numbers between 1 and 20 is", even)
Something like this should work; note the print statement is outside the while loop and the arithmetic is being done on odd and even using the if statement to determine which is to be added. Hope this makes sense
odd = 0
even = 0
counter = 0
while counter <= 20:
if counter % 2 == 0:
even += counter
elif counter % 2 != 0:
odd += counter
counter += 1
print("Sum of odd numbers is: {}, sum of even numbers is: {}".format(odd, even))

sum of the product of even positioned digits

I have attempted this problem like this :
a = input("Enter number : ")
s = 3
w = 1
while a>0:
digit=a%10
if n%2 == 0:
p = p*digit
else:
s = s+digit
a=a/10
n=n+1
print "The sum is",s
it works perfectly for even no of digits but for odd no of digits like for 234 it shows the sum as 6 and product 3
No explicit loop:
import operator
from functools import reduce # in Python 3 reduce is part of functools
a = input("Enter number : ")
lst = [int(digit) for digit in a]
add = sum(lst[1::2])
mul = reduce(operator.mul, lst[::2],1)
print("add =",add,"mul =",mul,"result =",add+mul)
Producing:
Enter number : 234
add = 3 mul = 8 result = 11
You have to start with n = 0 for this to work
a = int(input("Enter number"))
s = 0
p = 1
n = 0
while a>0:
digit=a%10
if n%2 == 0:
p *= digit
else:
s += digit
a /= 10
n += 1
print "The sum is",s
print "Product is",p
Easy mistake to make about the numbering. The first item of any string, list or array is always index 0. For example, be careful in future to take away 1 from the value returned from len(list) if you are iterating through a list's items with a for loop e.g.
for x in range(len(list)-1):
#your code using list[x]
Here's the mathematical version:
n = input('Enter a number: ')
digits = []
while n > 0:
digits.append(n%10)
n //= 10
s = 0
p = 1
i = 0
for digit in reversed(digits):
if i%2 == 0:
s += digit
else:
p *= digit
i += 1
print 'Sum of even digits:', s
print 'Product of odd digits:', p
print 'Answer:', s+p
I have tried to make this as simple as possible for you.
Here's a function that does the same thing:
def foo(n):
s = 0
p = 1
for i, digit in enumerate(str(n)):
if i%2 == 0:
s += digit
else:
p *= digit
return s+p
def foo(num):
lst = [int(digit) for digit in str(num)]
mul, add = 1, 0
for idx, val in enumerate(lst):
if not idx % 2:
mul *= val
else:
add += val
return add, mul
And using it:
>>> foo(1234)
(6, 3)
>>> foo(234)
(3, 8)
This function will take an integer or a string representation of an integer and split it into a list of ints. It will then use enumerate to iterate over the list and preform the required operations. It returns a 2 element tuple.

Categories