Home > Net >  Getting output of "print("Sum is :", int(a) int(b)) as tuple
Getting output of "print("Sum is :", int(a) int(b)) as tuple

Time:12-30

Code :

num1 = input("Enter first no. : ")
num2 = input("Enter Second no. :")
print("Sum is:", int(num1)   int(num2))

Output:

Enter first no. : 2
Enter Second no. :2
('Sum is:', 4)

Why I am getting inverted commas with "Sum is" and () in the output?

CodePudding user response:

The parentheses in the output indicate that the value being printed is a tuple.

In Python, a tuple is an immutable sequence type that can contain elements of different data types. Tuples are represented by round parentheses ().

In the code you provided, the value being printed by the print() function is a tuple containing two elements: a string ("Sum is:") and the sum of num1 and num2. The print() function separates the elements of the tuple by a space and encloses them in parentheses by default.

If you don't want the parentheses to be included in the output, you can try the following code:

num1 = input("Enter first no. : ")
num2 = input("Enter Second no. :")
print("Sum is: "   str(int(num1)   int(num2)))

This code will print the sum of num1 and num2 as a string, by concatenating the string "Sum is: " with the result of the sum using the operator. The str() function is used to convert the sum to a string so that it can be concatenated with the string.

Alternatively, you can use string formatting to print the sum without the parentheses:

num1 = input("Enter first no. : ")
num2 = input("Enter Second no. :")
print("Sum is: {}".format(int(num1)   int(num2)))

This code uses the format() method of the string object to insert the sum of num1 and num2 into the string "Sum is: {}". The {} placeholder is replaced with the value of the sum. The format() method returns a new string with the placeholder replaced with the value, which is then printed by the print() function.

CodePudding user response:

you are getting 'Sum is:' because it is printing as a string variable. Think about it this way: up in your code, you have print("Sum is:", int(num1) int(num2)). Since Python is an object based language, we essentially are printing three objects/variables here:

Your text string that says "Sum is:", your num1 variable, and your num2 variable.

When Python prints out a combination of different data type variables (in this case string and integer data types), the printed objects are usually separated by commas, and strings are enclosed by single quotation marks. It's just the syntax! Hope this helps. Happy coding.

  • Related