I have the following simple python code, which checks the user input.
while True:
num = raw_input("Enter the number :")
if (num >= 1 and num <= 5):
break
else:
print "Error! Enter again :"
When I give as input 0 or numbers greater than 5 it works correctly, but then I try to give an input from 1 to 5 and the program still goes to the else part. Could you help me to find my error?
num is a string, not a number. You need to convert the return value of raw_input into a number first with int():
>>> n = raw_input('Type stuff: ')
Type stuff: 123
>>> type(n)
<type 'str'>
>>> n
'123'
>>> int(n)
123
>>> type(int(n))
<type 'int'>
You need to cast it to int -
num = int(raw_input("Enter the number :"))
As raw_input read line and converts it to string .
Related
New to Python and can't figure out what's wrong with the code below.
a = input('input a number: ')
if int(a) >=0:
print(a)
else:
print(-a)
When enter -2, the output should be 2.
However, I got a error code:
TypeError: bad operand type for unary-:"str' on print(-a)
Can anyone help? Thanks.
try:
a = int(input('input a number: '))
if a >=0:
print(a)
else:
print(-a)
or
a = int(input('input a number: '))
print abs(a)
a = input('input a number: ')
#a at this point is a string, not an integer
if int(a) >=0:
print(a)
#you are printing a string, it just happen to look the same as an integer
else:
print(-int(a))
#you could do - to an integer, not a string
In case you are dealing with a string:
replace int with str
print(str(a))
I've just started with Python (3.x), and while it is fairly easy to pick up, I'm trying to learn how to work with lists.
I've written a small program which asks for the amount of numbers to input, then asks for the numbers. Where I'm scratching my head a little is here;
t += numList[int(i)]
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
I'm sure it's obvious to someone else. I thought that lists used an integer index? And that referencing that index would return the contents?
(I have a C++ background, so I'm finding that some things don't work how I thought they would).
Full program here;
runLoop = True
numList = []
def avg():
t = 0
i = 0
while i < len(numList):
t += numList[i]
i += 1
print (" total is " + str(t))
while runLoop == True:
maxLen = int(input("Average Calculator : "
"Enter the amount of number "
"to calculate for"))
while len(numList) < maxLen:
numList.append(input("Enter number : "))
avg()
if input("Would you like to run again? (y/n) ") == "n":
quit()
Type casting:
Type casting is missing in following statement
numList.append(input("Enter number : "))
e.g. Use input() method for python 3.x
>>> a = raw_input("Enter number:")
Enter number:2
>>> type(a)
<type 'str'>
>>> b = int(a)
>>> type(b)
<type 'int'>
>>>
Add Integer type variable with Integer type variable: This will raise exception at t += numList[i] statement because we are adding integer variable with string variable, it is not allowed.
e.g.
>>> 1 + "1"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
No need to check length of list in while loop while i < len(numList):. We can iterate directly on list.
e.g.
>> numList = [1,4,10]
>>> total = 0
>>> for i in numList:
... total += i
...
>>> print total
15
>>>
Inbuilt sum() function: We can use inbuilt function sum() to get from list.
e.g.
>>> numList = [1,4,10]
>>> sum(numList)
15
>>>
Exception handling: It is good programming to handle exception on user input. Use exception handling during type casting. If user enters any non integer number and we are type casting that non integer string into integer that time python interpreter raise ValueError.
e.g.
>>> try:
... a = int(raw_input("Enter Number:"))
... except ValueError:
... print "Wrong number. Enters only digit."
...
Enter Number:e
Wrong number. Enters only digit.
Thanks to Vivik for the answer.
I have now adjusted my simple program and solved the issue I had; code as follows.
runLoop = True
numList = []
def avg(workList):
t = sum(workList)
print ("Average is " + str(t/len(workList)) )
print ("Total is " + str(t) )
while runLoop == True:
maxLen = int(input("Average Calculator : "
"Enter the amount of number "
"to calculate for : "))
while len(numList) < maxLen:
numList.append(int(input("Enter number : ")))
avg(numList)
if input("Would you like to run again? (y/n) ") == "n":
quit()
I can see that I could quite easily shorten it down to;
runLoop = True
numList = []
while runLoop == True:
maxLen = int(input("Average Calculator: Enter the amount of number to calculate for : "))
while len(numList) < maxLen:
numList.append(int(input("Enter number : ")))
print ("Average is " + str(sum(numList)/len(numList)) )
print ("Total is " + str(sum(numList)) )
if input("Would you like to run again? (y/n) ") == "n":
quit()
But, the point of my little !/pointless exercise was to explore the relationships of lists, input to lists, and printing lists.
Cheers!
I'm trying to write a program that asks the user for 4 integers and prints the largest odd number that was entered. Here is the code:
a = raw_input("Enter an int: ")
b = raw_input("Enter an int: ")
c = raw_input("Enter an int: ")
d = raw_input("Enter an int: ")
numbers = [a, b, c, d]
odd_numbers = []
print numbers
for i in numbers:
if i%2!=0:
odd_numbers.append(i)
else:
print "This is not an odd number."
for nums in odd_numbers:
max_num = max(odd_numbers)
print max_num
And here is the error that I'm receiving:
line 10, in <module>
if i%2!=0:
TypeError: not all arguments converted during string formatting
What am I doing wrong ?
raw_input() returns a string. As a result, numbers list becomes a list of strings. % operation behavior depends on the variable type, in case of string it is a string formatting operation:
>>> s = "3"
>>> s % 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
In case of int, it gives you a division remainder:
>>> n = 3
>>> n % 2
1
You need to convert all the inputs to int:
a = int(raw_input("Enter an int: "))
b = int(raw_input("Enter an int: "))
c = int(raw_input("Enter an int: "))
d = int(raw_input("Enter an int: "))
To avoid having a redundant code, you can simplify filling the numbers list using list comprehension:
numbers = [int(raw_input("Enter an int: ")) for _ in xrange(4)]
Because You are input is string convert it into int
>>> a =raw_input("Enter an int: ")
Enter an int: 10
>>> type(a)
<type 'str'>
Try This :
a =int(raw_input("Enter an int: "))
b = int(raw_input("Enter an int: "))
c = int(raw_input("Enter an int: "))
d = int(raw_input("Enter an int: "))
OR
for i in numbers:
if int(i)%2!=0:
odd_numbers.append(i)
Your Output Should be look like this :
>>>
Enter an int: 10
Enter an int: 20
Enter an int: 20
Enter an int: 50
[10, 20, 20, 50]
This is not an odd number.
This is not an odd number.
This is not an odd number.
This is not an odd number.
raw_input will return you a string. So, each element in numbers are string like
numbers = ["1", "2", "3", "4"]
When you try i%2, python evaluates % as the string formatting operator but could not find any place-holder in the string for formatting and raise error. So you must parse your input to int
a = int(raw_input("Enter an int: "))
Or you can use input, which will evaluate your input to proper type (int in your case)
a = input("Enter an int: ")
But using input is not recommended if you are not experienced with it and eval as it states in the docs:
Equivalent to eval(raw_input(prompt)).
This function does not catch user errors. If the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation.
If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.
Consider using the raw_input() function for general input from users.
You input strings but you need to do calculations with ints.
I you do print type(a) for instance you will see that you actually got a string as input. The way to parse it to an int is to use the built in function int().
a = raw_input("Enter an int: ")
b = raw_input("Enter an int: ")
c = raw_input("Enter an int: ")
d = raw_input("Enter an int: ")
numbers = [a, b, c, d]
odd_numbers = []
print numbers
for i in numbers:
value = int(i)
if value%2!=0:
odd_numbers.append(value)
else:
print "This is not an odd number."
for nums in odd_numbers:
max_num = max(odd_numbers)
print max_num
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
I think I'm calculating the conversion from an integer to a binary number wrong. I entered the integer 6 and got back the binary number 0, which is definitely wrong. Can you guys help out? Here's the new code.
def ConvertNtoBinary(n):
binaryStr = ''
if n < 0:
print('Value is a negative integer')
if n == 0:
print('Binary value of 0 is 0')
else:
if n > 0:
binaryStr = str(n % 2) + binaryStr
n = n > 1
return binaryStr
def main():
n = int(input('Enter a positive integer please: '))
binaryNumber = ConvertNtoBinary(n)
print('n converted to a binary number is: ',binaryNumber)
main()
You forgot to call raw_input(). Right now you try to convert your prompt message to an integer which cannot work.
n = int(raw_input('Enter a positive integer please: '))
Of course a try..except around that line would be a good idea:
try:
n = int(raw_input('Enter a positive integer please: '))
except ValueError:
n = 0 # you could also exit instead of using a default value
In n = int('Enter a positive integer please: '), you are trying to make an int out of the string 'Enter a positive...'. I would assume you forgot your raw_input(). You could either do
n = int(raw_input('Enter a positive integer please: '))
or
n = raw_input('Enter a positive integer please: ')
n = int(n)
You can't cast a arbitratry string literal to an int. I think what you mean to do is call a prompt method of some sort that takes input from the user.