math with input() | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

math with input()

Hello! :) How can I make math with an input()? I've tried to do a calculator like this: first_digit = input() second_digit = input() print(first_digit+second_digit) But the output is wrongly, like: #Example first_digit = 2 second_digit = 4 Prints 24, not the sum of them. ♥️ I'm way too beginner, but your answer surely will help me in the future!

17th Dec 2023, 5:03 AM
Victor
Victor - avatar
2 Answers
+ 9
Hey, input feature takes the value as a string. Try this code first_digit = int(input()) second_digit = int(input()) print(first_digit + second_digit) For any other issues, feel free to reach out
17th Dec 2023, 5:09 AM
卂ㄚㄩ丂卄
卂ㄚㄩ丂卄 - avatar
+ 4
Hi, the previous answer is correct, but here's an explanation as to why. All input() functions will save the input given as a string, even if it is an integer or float which is entered. If you add two strings together, they will join together to form one long string. To work with inputs as integers, you can convert the data at source by including the int() function AROUND the input function and save the numbers as integers that will then do as you expect. Note: if you do this, and the user enters anything other than a number it will crash. If they enter a decimal such as 12.7, it will round down to the nearest whole number and save 12. A float() conversion should be used if decimal points are expected.
17th Dec 2023, 7:05 PM
StuartH
StuartH - avatar