0
x1 = 1
x2 = 2
ans=int(input(x1, "+", x2, "="))

if (ans==(x1+x2)):
   print("Correct")
else:
   print("Incorrect")

I have this code which is supposed to tell the user to input a value for what they think is the correct answer for x1 + x2 , however when I run the code, the input part is giving me an error. Is there something I am doing wrong?

3
  • ans=int(input('{} + {} ='.format(x1, x2))) Commented Sep 30, 2018 at 5:41
  • 2
    Or: int(input(f'{x1} + {x2} = ')). Commented Sep 30, 2018 at 5:42
  • 1
    What error are you getting? Please see this. Commented Sep 30, 2018 at 5:48

3 Answers 3

2

Input takes only 1 parameter. By using comma, you are passing 4. So, just convert them into a single string by using '+' operator instead of ','.

x1 = 1
x2 = 2

ans = int(input(str(x1) + "+" + str(x2) + "="))
# As string concatenation is an expensive operation, the following
# might be an optimal approach for acheiving the same result. 

ans = int(input("".join(str(x1), "+", str(x2), "=")))
# But in this scenario, it doesn't matter because the number of strings 
# being concatenated and the length of them are both small. So, it won't 
# make much difference. 

# Also now, Python3.5+ supports `f-strings`. So, you can do something like
ans = int(input(f"{x1} + {x2} = "))

if (ans == (x1 + x2)):
   print("Correct")
else:
   print("Incorrect")
Sign up to request clarification or add additional context in comments.

3 Comments

How is a coma important here?
+ is not the recommended way to build a string.
Agreed! Updated the answer with other (more optimized) approaches as well.
0

Replace with this

if(ans==(input("Enter x1")+input("Enter x2"))):

Comments

0

Answer:

Replace

ans=int(input(x1, "+", x2, "="))

with

ans = int(input("".join(map(str, [x1, "+", x2, "="]))))

Reference:

  1. input
  2. str
  3. map
  4. str.join

1 Comment

This maybe a GREAT answer. But why not explain WHY?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.