It's a very basic doubt in Python in getting user input, does Python takes any input as string and to use it for calculation we have to change it to integer or what? In the following code:
a = raw_input("Enter the first no:")
b = raw_input("Enter the second no:")
c = a + b
d = a - b
p = a * b
print "sum =", c
print "difference = ", d
print "product = ", p
Python gives following error:
Enter the first no:2
Enter the second no:4
Traceback (most recent call last):
File "C:\Python27\CTE Python Practise\SumDiffProduct.py", line 7, in <module>
d=a-b
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Can someone tell please why am I getting this error?
Yes, every input is string. But just try:
a = int(a)
b = int(b)
before your code.
But be aware of the fact, that user can pass any string he likes with raw_input. The safe method is try/except block.
try:
a = int(a)
b = int(b)
except ValueError:
raise Exception("Please, insert a number") #or any other handling
So it could be like:
try:
a = int(a)
b = int(b)
except ValueError:
raise Exception("Please, insert a number") #or any other handling
c=a+b
d=a-b
p=a*b
print "sum =", c
print "difference = ", d
print "product = ", p
From the documentaion:
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
Yes, you are correct thinking you need to change the input from string to integer.
Replace a = raw_input("Enter the first no: ") with a = int(raw_input("Enter the first no: ")).
Note that this will raise a ValueError if the input given is not an integer. See this for how to handle exceptions like this (or use isnumeric() for checking if a string is a number).
Also, beware that you although you might find that replacing raw_input with input might work, it is a bad and unsafe method because in Python 2.x it evaluates the input (although in Python 3.x raw_input is replaced with input).
Example code could therefore be:
try:
a = int(raw_input("Enter the first no: "))
b = int(raw_input("Enter the second no: "))
except ValueError:
a = default_value1
b = default_value2
print "Invalid input"
c = a+b
d = a-b
p = a*b
print "sum = ", c
print "difference = ", d
print "product = ", p
a = input("Enter integer 1: ")
b = input("Enter integer 2: ")
c=a+b
d=a-b
p=a*b
print "sum =", c
print "difference = ", d
print "product = ", p
Just use input() and you will get the right results. raw_input take input as String.
And one more i Would Like to Add..
why to use 3 extra variables ?
Just try:
print "Sum =", a + b
print "Difference = ", a - b
print "Product = ", a * b
Don't make the Code complex.
raw_input() stores the inputted string from user as a "string format" after stripping the trailing new line character (when you hit enter). You are using mathematical operations on string format that's why getting these errors, first cast your input string into some int variable by using a = int(a) and b = int(b) then apply these operations.
Related
I have to make a program using while that:
Will ask for user to put 2 integer numbers
and give back the addition and multiplication
of those 2.
Will check if the numbers are integers.
Will close if the user uses the word stop.
I have made 1 and 2 but am stuck on 3. Here is what I wrote:
while True:
try:
x = int(input("Give an integer for x"))
c = int(input("Give an integer for c"))
if x=="stop":
break
except:
print(" Try again and use an integer please ")
continue
t = x + c
f = x * c
print("the result is:", t, f)
Your code isn't working because you are starting off by defining x as an integer, and for it to equal "stop", it needs to be a string.
What you therefore want to do is allow x to be input as a string, and then convert it to an integer if it isn't stop:
while True:
try:
x = input("Give an integer for x")
if x=="stop":
break
else:
x = int(x)
c = int(input("Give an integer for c"))
except:
print(" Try again and use an integer please ")
continue
t = x + c
f = x * c
print("the result is:", t, f)
Just a slight change is required (and you can be slightly more structured using else in your try block.
You need to input the first value as a string so that you can first test it for "stop" and only then try to convert it to an integer:
while True:
try:
inp = input("Give an integer for x: ")
if inp == "stop":
break
x = int(inp)
c = int(input("Give an integer for c: "))
except:
print("Try again and use an integer please!")
else:
t = x + c
f = x * c
print("the results are", t, f)
I have also fixed up some spacing issues (i.e. extra spaces and missing spaces in your strings).
To print strings with math addition numbers in Python, what is the correct way doing something like:
# Read two inputs from users
a = input("Enter your First Number")
b = input("Enter your Second Number")
# perform type conversion
a = int(a)
b = int(b)
print (f"Result: {a}+{b}")
Output:
Enter your First Number10
Enter your Second Number10
Result: 10+10
Desired output: Result: 20
Your current format string Result: {a}+{b} prints out a and b individually as Result: 10+10 and doesn't perform the addition.
To achieve that, you need to change the f-string to f"Result: {a+b}" so that the addition happens within the formatting curly braces and the result gets printed
print (f"Result: {a+b}")
The output will be
Result: 20
a = input("Enter your First Number")
b = input("Enter your Second Number")
# perform type conversion
a = int(a)
b = int(b)
print (f"Result: {a + b}")
You should change
print (f"Result: {a} + {b}")
to
print (f"Result: {a + b}")
# Read two inputs from users
a = int(input("Enter your First Number"))
b = int(input("Enter your Second Number"))
print ("Result: {}".format(a+b))
I'm new to this forum and new to python after c++.
I have a problem with a python calculator. When I run it and I do it with + for example : 10 + 5 gives 105, but I wanted to get 15.
Other operations don't even work (I get an error).
print("\nCalculator In Python")
print("\nChose The Operation :")
print("\na)+\n\nb)-\n\nc)/\n\nd)*")
answer = input("\n\n: ")
result = int
if answer == 'a':
a = input("\n\nFirst Number : ")
b = input("\n\nSecond Number : ")
print(a, "+", b, "=", a+b)
elif answer == 'b':
a = input("\n\nFirst Number : ")
b = input("\n\nSecond Number : ")
print(a, "-", b, "=", a-b)
elif answer == 'c':
a = input("\n\nFirst Number : ")
b = input("\n\nSecond Number : ")
print(a, "/", b, "=", a/b)
elif answer == 'd':
a = input("\n\nFirst Number : ")
b = input("\n\nSecond Number : ")
print(a, "*", b, "=", a*a)
a+b is actually '10'+'5', which is '105'. This is happening because
input() gives a string. So you need to convert it to a number first.
float(input())
Additionally, to ensure the user gives only valid numbers, you can use:
while True:
a = input('\nGive a:')
try:
a = float(a)
break
except ValueError:
print('Try again.')
The 'input' functions return a string that contains "10" and "5". Conducting a + operator on two strings concatenates them (i.e. "10" + "5" = "105").
If you convert the input to an float or integer you'll get the result you're looking for:
>>> a = "5" + "5"
>>> a
'55'
>>>
>>> b = float("5") + float("5")
>>> b
10.0
Python is setting your input to strings.
You could check this with the "type(a)" function.
You would need to convert the input to either a float or integer.
integer = int(a)
FloatingPoint = float(a)
I've just started studying Python, and I'm an absolute newbie.
I'm starting to learn about functions, and I wrote this simple script:
def add(a,b):
return a + b
print "The first number you want to add?"
a = raw_input("First no: ")
print "What's the second number you want to add?"
b = raw_input("Second no: ")
result = add(a, b)
print "The result is: %r." % result
The script runs OK, but the result won't be a sum. I.e: if I enter 5 for 'a', and 6 for 'b', the result will not be '11', but 56. As in:
The first number you want to add?
First no: 5
What's the second number you want to add?
Second no: 6
The result is: '56'.
Any help would be appreciated.
raw_input returns string, you need to convert it to int
def add(a,b):
return a + b
print "The first number you want to add?"
a = int(raw_input("First no: "))
print "What's the second number you want to add?"
b = int(raw_input("Second no: "))
result = add(a, b)
print "The result is: %r." % result
Output:
The first number you want to add?
First no: 5
What's the second number you want to add?
Second no: 6
The result is: 11.
You need to convert the strings to ints to add them, otherwise + will just perform string concatenation since raw_input returns raw input (a string):
result = add(int(a), int(b))
You need to cast a and b to integer.
def add(a, b):
return int(a) + int(b)
This is because raw_input() returns a string and + operator has been overloaded for strings to perform string concatenation. Try.
def add(a,b):
return int(a) + int(b)
print "The first number you want to add?"
a = raw_input("First no: ")
print "What's the second number you want to add?"
b = raw_input("Second no: ")
result = add(a, b)
print "The result is: %r." % result
The resultant output is as follows.
>>>
The first number you want to add?
First no: 5
What's the second number you want to add?
Second no: 6
The result is: 11
Converting the string inputs to int, uses the + operator to add the results instead of concatenating them.
.
**
**>raw_input always returns string. You need to convert the strings to int/float datatype to add them, otherwise addition will perform string concatenation.
You can check the type of the variables yourself : print(type(a), type(b))
Simply tweak your function**
**
def add(a, b):
return int(a) + int(b)
OR
def add(a, b):
return float(a) + float(b)
how to write python code to ask user to input a number, return the int of the number, and if user input a str, for example "One", return a error message like "please input a int number"? How could I do that?
Also I have to check if the number is odd or not, so i m not sure if I can do it with try and except.I dunno how to add that in my code.
Thanks.
def getnum():
errormessage="Please input a odd number"
asknum=raw_input("Please input a number: ")
num=int(asknum)
if num%2!=0: #return num if it is odd number
print num
else:
print errormessage
return getnum()
getnum()
try:
a = int(raw_input("Enter an integer: "))
print a # or do anything else with "a"
except ValueError:
print "Please enter an integer."
EDIT In response to the OP's comment:
try:
a = int(raw_input("Enter an integer: "))
if a % 2 == 1:
print "Integer is odd" # or do anything else
else:
print "Integer is even" # or do anything else
except ValueError:
print "Please enter an integer."
Note that using raw_input() will store the variable as a string, if you want to store it automatically as an int, use input().
This is for Python versions before 3.
There are various ways you could try it.
One way is
userinput = raw_input()
if not all(x in string.digits for x in userinput):
print 'Please enter an int number'
but that's a little weak on the verification - it just checks that all the input characters are digits.
Or you could try
userinput = raw_input()
try:
asint = int(userinput)
except ValueError:
print 'Please enter an int number'
but that uses try/except for something that should be a simple if/else.
s = input()
try:
return int(s)
except:
return 'Error'
Use the isdigit() function for string objects.
Returns true if number else false.
You can do what you wanted using the other answers mentioned.
For some extra information,the type of a variable in python can be obtained by using the type()
>>> a = 1
>>> type(a)
<type 'int'>
>>> b = 'str'
<type 'str'>
you can check a variable's type by
>>> if type(a) == int:
... print 'a is integer'
...
a is integer