Comparison Operator & isnumeric() not compatible? - python

I want to check if whether input is numeric, If it is, Compare the number to another.
I tried to resolve one issue by removing int() conversion. But that would render x > 0 useless.
Tried searching online, But there's no simple resolve.
print("This program prints the sum of a range of numbers from x to y")
print("For example, if x is 10 and y is 50, the program will print the sum of numbers")
print("from 10 to 50")
x = int(input("Please enter the value of x: "))
y = int(input("Please enter the value of y: "))
if x.isnumeric() and y.isnumeric():
if x > 0 and y > 0:
print("Passed")
else:
print("failed")
else:
print("One or more of your inputs are not numeric!")
Got 'int' object has no attribute 'isnumeric' as error
or
'>' not supported between instances of 'str' and 'int'

Your code has a few issues.
str.isnumeric applies to strings, but you are trying to call it on an integer, hence you get the error 'int' object has no attribute 'isnumeric' as error
If you then don't convert x to int, and leave it as str and try to do x > 0 and y > 0, you are comparing string and integer, which is not possible, as well, hence the error '>' not supported between instances of 'str' and 'int'
To resolve this, you can read x and y as a string, and then convert them to int when comparing them to 0 as follows.
print("This program prints the sum of a range of numbers from x to y")
print("For example, if x is 10 and y is 50, the program will print the sum of numbers")
print("from 10 to 50")
#Read x and y as strings
x = input("Please enter the value of x: ")
y = input("Please enter the value of y: ")
#Check if they are numeric
if x.isnumeric() and y.isnumeric():
#Convert them to int to compare them with 0
if int(x) > 0 and int(y) > 0:
print("Passed")
else:
print("failed")
else:
print("One or more of your inputs are not numeric!")
Then your output will look like
This program prints the sum of a range of numbers from x to y
For example, if x is 10 and y is 50, the program will print the sum of numbers
from 10 to 50
Please enter the value of x: 20
Please enter the value of y: 40
Passed
This program prints the sum of a range of numbers from x to y
For example, if x is 10 and y is 50, the program will print the sum of numbers
from 10 to 50
Please enter the value of x: 10
Please enter the value of y: 60
Passed
But hold on, what happened here
This program prints the sum of a range of numbers from x to y
For example, if x is 10 and y is 50, the program will print the sum of numbers
from 10 to 50
Please enter the value of x: -20
Please enter the value of y: -40
One or more of your inputs are not numeric!
Here I will make a note here that this logic won't work for negative integers
as you can see below, isnumeric returns False for negative integers
In [1]: '-20'.isnumeric()
Out[1]: False
Hence a much better approach might be is to try to cast the string as an int, and based on that, check if x is a number or not
print("This program prints the sum of a range of numbers from x to y")
print("For example, if x is 10 and y is 50, the program will print the sum of numbers")
print("from 10 to 50")
#Read x and y as strings
x = input("Please enter the value of x: ")
y = input("Please enter the value of y: ")
def is_number(s):
#If we can cast string to int, it is an int, else it is not
is_number = False
try:
int(s)
is_number = True
except ValueError:
pass
return is_number
#Check if they are numeric
if is_number(x) and is_number(y):
#Convert them to int to compare them with 0
if int(x) > 0 and int(y) > 0:
print("Passed")
else:
print("failed")
else:
print("One or more of your inputs are not numeric!")
Now the code will work for negative integers too
This program prints the sum of a range of numbers from x to y
For example, if x is 10 and y is 50, the program will print the sum of numbers
from 10 to 50
Please enter the value of x: -20
Please enter the value of y: -40
failed
This program prints the sum of a range of numbers from x to y
For example, if x is 10 and y is 50, the program will print the sum of numbers
from 10 to 50
Please enter the value of x: hey
Please enter the value of y: hi
One or more of your inputs are not numeric!

Related

Can't convert string to integer under while loop in python [duplicate]

This question already has answers here:
ValueError: invalid literal for int() with base 10: ''
(15 answers)
Closed 2 years ago.
I'm new to python. In this code, I'm trying to ask for numbers repeatedly. When the user enters 0, the program print the average of the numbers exclude 0. I can get the average from this code. However, there's a ValueError,
y = int(input())
ValueError: invalid literal for int() with base 10: ''
I don't understand why this error happens. Is it because of convert variable type under while loop? Can anyone help? Thanks!!
nums=0
i=0
x = int(input())
while x>0:
y = int(input())
i = i + 1
nums = y + nums
if y == 0:
avg = (nums+x)/(i)
print("The average of those numbers is {:.2f}.".format(avg))
This error occurs when you try to input a string of characters, instead of numbers.
E.g:
if you input '', 'string' - These won't work
but if you input '9', '239412' - This will work
It is likely the line y = int(input()) is receiving a string from the user input .
See this example.
>>> while True:
... y = int(input())
... print "Y=",y
...
12
Y= 12
0
Y= 0
"this"
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'this'
Like #Blade said you should give numbers as input. You can do this:
nums=0
i=0
try:
x = int(input())
while x>0:
try:
y = int(input())
i = i + 1
nums = y + nums
if y == 0:
avg = (nums+x)/(i)
print("The average of those numbers is {:.2f}.".format(avg))
except:
print("Input is not a number")
except:
print("Input is not a number")
You got the Value Error because you entered a space( "") which considered as a string but the input should be an integer int
For calculating the average of two numbers you can use this simple code instead : -
def average(x, y):
" Returns the average of two numbers "
return (x+y)/2
x = int(input("Enter a number:\n"))
y = int(input("Enter another number :\n"))
print(average(x, y))

Python expected an indented blockkkk

im relatively new to python and im not really sure how does the indentation for if else works.
Write a Python program that calculates the sum of all the numbers from x to y, where x and y are numbers entered by the user.
print("This program prints the sum of range from x to y. ")
print("For example, if x is 10 and y is 50, the program will print the sum of numbers from 10 to 50. ")
x = int(input("Please enter the value of x: "))
y = int(input("Please enter the value of y: "))
if type(x) == int and type(y) == int:
if x > 0 and y > 0:
if y > x:
sum_of_numbers = []
for counter in range(x , y):
sum_of_numbers.append(x)
x += 1
print("The sum of numbers from {} to {} is {}".format(x,y,sum(sum_of_numbers)))
else:
print("You did not enter a value of y greater than x")
print("Unable to continue.Program terminated.")
exit()
else:
print("One or more inputs is not greater than zero")
print("Unable to continue.Program terminated.")
exit()
else:
print("One or more inputs is not numeric!")
print("Unable to continue.Program terminated.")
exit()
if type(x) == int and type(y) == int:
if x > 0 and y > 0: # indented 1
if y > x: # indented 3
sum_of_numbers = [] # indented 4
You need to have consistent indentation, preferably four spaces for each indent, as per PEP8.
Without that, the Python compiler (or you as well, really) can't tell how your code is meant to be structured.

Converting an empty string input to float

I made a code like this to find the arithmetical mean for numbers the user has typed in but for some reason the program couldn't convert string to float in the end. What should I change?
print("I'm going to find the arithmetical mean! \n")
jnr = 0; sum = 0
negative = "-"
while True:
x = input(f"Type in {jnr}. nr. (To end press Enter): ")
if negative not in x:
jnr += 1
elif negative in x:
pass
elif x == "": break
sum = sum + float(x)
print("Aritmethmetical mean for these numbers is: "+str(round(sum/(jnr-1), 2)))
I got his Error :
Traceback (most recent call last): File
"C:\Users\siims\Desktop\Koolitööd\individuaalne proge.py", line 11, in
sum = sum + float(x) ValueError: could not convert string to
float
As I said in my comment the error comes from the fact that calling float(x) when the user uses Enter result in the error. The easiest way to fix your code without changing everything is by checking first if the input is "". That way you will not be trying to convert an empty string to float.
print("I'm going to find the arithmetical mean! \n")
jnr = 0;
sum = 0
negative = "-"
while True:
x = input(f"Type in {jnr}. nr. (To end press Enter): ")
if x == "":
break
elif negative not in x:
jnr += 1
sum = sum + float(x)
print("Aritmethmetical mean for these numbers is: "+str(round(sum/(jnr-1), 2)))
You're trying to convert a string to a float but it is an invalid string if you are using the string for that purpose. I would just continue asking until the user gives the right input, like this:
def float_input(s):
while True:
try:
x = input(s)
except ValueError:
print('Invalid input. Try again.')
else:
break
return x
Then, instead of input, use float_input in your code.
An updated version of your code :
print("I'm going to find the arithmetical mean! \n")
jnr = 0; sum = 0
while True:
x = int(input())
if x>1:
jnr += 1
elif x<1:
pass
if x == 0:
break
sum += float(x)
print(sum)
print("Aritmethmetical mean for these numbers is: {}".format(sum/jnr))
output:
I'm going to find the arithmetical mean!
9
9
9
9
9
0
Aritmethmetical mean for these numbers is: 9.0
Pythonic way:
You can find mean by:
print("I'm going to find the arithmetical mean! \n")
inp=[int(i) for i in input().split()]
print(sum(inp)/len(inp))
output:
I'm going to find the arithmetical mean!
9 9 9 9 9
9.0

Can someone tell me why this recursive method with raw_input is not returning? [duplicate]

This question already has answers here:
How does Python 2 compare string and int? Why do lists compare as greater than numbers, and tuples greater than lists?
(2 answers)
Closed 6 years ago.
Here is the statement:
def recursive(y):
if y < 10:
return y
else:
z = raw_input("Please enter a number: ")
recursive(z)
x = raw_input("Please enter a number: ")
t = recursive(x)
print t
Whenever I run this, if I enter a number equal to or above 10, it prompts me to enter a number again. If I enter a number less than 10, it still tells me to enter a number; however, if I enter less than 10, shouldn't the if y < 10 be true and it will return that number?
You have 2 issues:
You do not return the result of your call
You do not cast your raw_input (which is a string) as an int.
Here's the corrected version:
def recursive(y):
if y < 10:
return y
else:
z = raw_input("Please enter a number: ")
return recursive(int(z))
as always because you are nto returning in your else branch ...
def recursive(y):
if float(y) < 10: # also you need to make this a number
return y
else:
z = raw_input("Please enter a number: ")
return recursive(z) #this is almost always the problem with these questions

Checking non-negative even integer in Python

I'm new to programming and currently learning Python. I would like to write a program that :
request user to input a non-negative even integer.
request the user to input again if not fulfil non-negative even integer.
N = input("Please enter an non-negative even integer: ") #request user to input
And the criteria checking code is:
N == int(N) #it is integer
N % 2 == 0 #it is even number
N >=0 # it is non-negative number
But how should I combine them?
since the question is tagged python-2.7, use raw_input instead of input (which is used in python-3.x).
Use str.isdigit to check if a string is an positive integer, int(N) would raise ValueError if the input couldn't be converted into integer.
Use a while loop to request user input if condition not fulfilled, break when you get a valid input.
e.g.,
while True:
N = raw_input("Please enter an non-negative even integer: ") #request user to input
if N.isdigit(): # accepts a string of positive integer, filter out floats, negative ints
N = int(N)
if N % 2 == 0: #no need to test N>=0 here
break
print 'Your input is: ', N
You can use the and operator:
while True:
s = input("Please enter an non-negative even integer: ")
# Use raw_input instead of input in Python 2
try:
N = int(s)
except ValueError:
continue # Not an integer, try again
if N % 2 == 0 and N >= 0:
break # Abort the infinite loop
Compared to other versions presented here, I prefer to loop without using the break keyboard. You can loop until the number entered is positive AND even, with an initial value set to -1:
n = -1
while n < 0 or n % 2 != 0:
try:
n = int(input("Please enter an non-negative even integer: "))
except ValueError:
print("Please enter a integer value")
print("Ok, %s is even" % n)
Just another solution:
>>> def non_neg(n):
... try:
... if n & 1 == 0 and n > 0:
... return 'Even Positive Number'
... except:
... pass
... return 'Wrong Number'
...
>>> for i in [-1,-2,2,3,4,0.5,'a']:
... print i, non_neg(i)
...
-1 Wrong Number
-2 Wrong Number
2 Even Positive Number
3 Wrong Number
4 Even Positive Number
0.5 Wrong Number
a Wrong Number
>>>
code for fun:
result=[ x for x in [input("Please enter a number:")] if isinstance(x,int) and x>0 and x%2 ==0]
Excuting this list comprehension ,will get you an empty list if occurs any illegal key-in like 0.1, 'abc',999.
code for best practice:
There is quite popular to take all validation expression into lambda for python, for example, like django so :
isPositiveEvenNum=lambda x: x if isinstance(x,int) and x>0 and x%2 ==0 else None
while not isPositiveEvenNum(input("please enter a number:")):
print "None Positive Even Number!"
this can also be writen as
isPositiveEvenNum=lambda x: (isinstance(x,int) and x>0 and x%2 ==0) or False
while not isPositiveEvenNum(input("please enter a number:")):
print "None Positive Even Number!"
to solve the input and raw_input difference between 2.x and 3.x:
import sys
eval_input =lambda str: input(str) if sys.version_info<(3,0,0) else eval(input(str))
then just call eval_input

Categories

Resources