Reputation: 7
I don't know why but I've just never found a way around this problem.
My teacher wanted to get our class involved with coding and asked me to create a basic calculator in python. So I quickly typed up:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
def add(x, y):
return x + y
print (num1, "+", num2, "is equal to", add(num1, num2))
Simple stuff, I'll add subtraction and all that.
However, being the grammar nazi I am, I cannot find a way to place a period at the end of that print command.
I've solved it before. My first calculator didn't define functions, it just took the integers, then added them together and assigned them a variable and then printed them. I added periods by using %s and putting the variable at the end of the print command.
Also, while if I try to print the option selected in a tkinter window for example with variable.get() I can't seem to put a period at the end either. The only thing I found only was putting + "." at the end or something along those lines.
Can anyone help me?
Upvotes: 0
Views: 3956
Reputation: 3532
There are a couple of things you can do:
print (str(num1) + "+" + str(num2) + " is equal to " + str(add(num1, num2)) +".")
What this does is to convert the numbers to strings and append them into one big string which is then printe.
Much better is to use use a formatter:
print ("{0} + {1} is equal to {2}.".format(num1, num2, add(num1, num2))
In this example you define a "format" where {n} are replaced by the values passed in the format function. This produces a string that is then printed.
The second way is more elegant and easy to follow in my opinion, so I suggest using that.
Upvotes: 1
Reputation: 12092
Try this:
print ("{} + {} is equal to {}.".format(num1, num2, add(num1, num2)))
This makes use of the format()
method documented here.
Upvotes: 2