Mike
Mike

Reputation: 77

How to add multiple elements in the python input?

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?

Upvotes: 0

Views: 415

Answers (3)

vighnesh153
vighnesh153

Reputation: 5388

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")

Upvotes: 2

KaiserKatze
KaiserKatze

Reputation: 1569

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

Upvotes: 0

Kishor
Kishor

Reputation: 7

Replace with this

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

Upvotes: 0

Related Questions