Algorithm for Addition of Two Numbers in PythonWe must understand the basic prerequisites of Python before understanding the algorithm for adding two numbers in Python. This includes:
Input: We take input from users while programming or performing any operation. We take input using the input( ) function. Syntax: Output: The output is the result after the operations performed on the inputs. We use the print( ) function to display the output. Syntax: value is the output to be printed. Data Types: Data types are the type of data which is stored in a variable. There are different data types in Python, including int, float, str, list, tuple, etc. Operators: The operators are the symbols used to perform operations on the input variables. There are different types of operators in Python, including arithmetic, assignment, comparison, logical operators, etc. For adding two numbers, we will use the + operator Now, let's see a simple algorithm to add two numbers in Python. Algorithm:
Example: Code: Output: Sum : 109 Explanation: We take two variables, n1 and n2, and assign values to them. Then, using the + operator, we print the sum of both numbers. Adding Two Numbers with User InputWe will take the inputs from the user, add the numbers and print the output. Algorithm:
Example: Code: Output: Enter number 1 : 233 Enter number 2 : 112 Sum : 345 Explanation: We have declared two variables, n1 and n2. Using the input( ) function, we take from the user. Then, we added the numbers using the + operator and stored the value in another variable, Sum. With the help of the print( ) function, we printed the output. Adding two numbers by defining a functionWe will define a function for adding the numbers and returning the output. Algorithm:
Example: Code: Output: Sum : 187 Explanation: We made a function sum_num( ) with parameters n1 and n2. Then, using a third variable, we added both the numbers and then printed the output. Then, we made an object to call the function, which takes the values and prints the sum of the numbers. Adding two numbers using the add( ) methodWe will use the add( ) method of the operator library to add two numbers. Algorithm:
Example: Code: Output: Sum : 59 Explanation: We have imported the operator library. Then, initialised two variables and added the numbers using the operator.add( ) method. Then, we printed the output. Next TopicDecimal-to-binary-algorithm-in-python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India