Let’s see how two perform a very common and simple task when learning a programming language: adding two numbers.
In python the code for adding two numbers is very straightfoward.
Adding numbers directly
first_number = 32
second_number = 8
total = first_number + second_number
print(total)
#output: 40
In this example above I’m declaring two variables, first_number
and second_number
, each with a number assigned to them, both int
types in this case.
Then I use the +
sign to perform the sum and assign the result to the total
variable.
Finally, the code uses the print()
method to display the total.
The example below is very similar to the one before, the only difference is that I’m using float
types here.
first_number = 31.4
second_number = 7.6
total = first_number + second_number
print(total)
#output: 39
Adding using the input from the user
This last example uses the input()
builtin function to capture the input from the user.
Notice that the input is always captured as string, so you have to typecast the values to correctly add them.
In this case, I’m using int()
to typecast the input to int
.
first_number = input('Enter the first value: ')
second_number = input('Enter the second value: ')
total = int(first_number) + int(second_number)
print(total)
Here is an example of an interaction with the program running.
Enter the first value: 32
Enter the seconde value: 10
42
If you want to learn more about type casting, python data types and taking user inputs, I recommend these other posts: