I tried to make just add print(a b) and I only got what it equals I don't know what to do I can't find it or look for it online.
CodePudding user response:
You are mixing up printing a string vs. printing an expression.
Printing a string like print('hello world')
will print the literal message because you've indicated it's a string with quotes.
However, if you provide an expression like print(a b)
, it will evaluate that expression (calculate the math) and then print the string representation of that evaluation.
Now, what you want is actually a mix of both, you want to print a string that has certain parts replaced with an expression. This can be done by "adding" strings and expressions together like so:
print(a ' ' b '=' (a b))
Notice the difference between
without quotes and ' '
with quotes. The first is the addition operator, the second is the literal plus character. Let's break down how the print statement parses this. Let's say we have a = 5
and b = 3
. First, we evaluate all the expressions:
print(5 ' ' 3 '=' 8)
Now, we have to add a combination of numbers with strings. The
operator acts differently depending on context, but here it will simply convert everything into a string and then "add" them together like letters or words. Now it becomes something like:
print('5' ' ' '3' '=' '8')
Notice how each number is now a string by the surrounding quotes. This parses to:
print('5 3=8')
which prints the literal 5 3=8
CodePudding user response:
You mean like that:
a = int(input("Give me a number man: "))
b = int(input("Give me another number: "))
print(f'print({a} {b}) = {a b}')
print(f'print({a} - {b}) = {a - b}')
print(f'print({a} * {b}) = {a * b}')
print(f'print({a} // {b}) = {a // b}')
print("Look at all those maths!")
Output
Give me a number man: 3
Give me another number: 2
print(3 2) = 5
print(3 - 2) = 1
print(3 * 2) = 6
print(3 // 2) = 1
Look at all those maths!