Creating a calculator

Michael Torrie torriem at gmail.com
Thu Jun 30 23:38:16 EDT 2016


On 06/30/2016 09:08 PM, Elizabeth Weiss wrote:
> while True:
> 	print("Options:")
> 	print("Enter 'add' to add two numbers")
> 	print("Enter 'subtract' to subtract two numbers")
> 	print("Enter 'multiply' to multiply two numbers")
> 	print("Enter 'divide' to divide two numbers")
> 	print("Enter 'quit' to end the program")
> 	user_input=input(":")
> 	if user_input=="quit":
> 		break
> 	elif user_input=="add":
> 		num1=float(input("Enter a number"))
> 		num2=float(input("Enter another number"))
> 		result=str(num1+num2)
> 		print("The answer is"+ result)
> 	elif user_input=="subtract":
> 		num1=float(input("Enter a number"))
> 		num2=float(input("Enter another number"))
> 		result=str(num1-num2)
> 		print("The answer is"+result)
> 
> Two questions:
> 1. Why do I need to put ' ' around the words add, subtract, multiply, quit, etc. when it is already in quotes in print()? When the calculator asks me which option I would like to choose I do not write 'add'- I only write add. 

I think those extra quotes are just to make the output stand out when
it's printed to the screen so that the user knows that the word in
quotes is the special word they will need to type in.  It's much like
how things are quoted in literature.

Since the string is already inside of double quotes, the inner single
quotes simply get printed.  And if you wanted to print real double
quotes to the screen, you can surround the string with single quotes.
Either works, depending on which quote character you want to actually
print to the screen.

Here's examples using the interactive python prompt:
>>> print ('He said, "How are you?"')
He said, "How are you?"
>>> print ("In British books one might say, 'How are you?'")
In British books one might say, 'How are you?'

Hope this helps.

> 
> 2. The program I am using to help me learn python mentions that the output line could be put outside the if statements to omit repetition of code. What does this mean and how would I write the code differently according to this?

It means that since each of the elif blocks does something that needs to
be printed out, and if it's being printed out the same way by each, then
you can just stick it at the end of the if processing block so that it
always runs regardless of which elif block did the computation.  Though
in your code example this isn't strictly true, since if the input was
not "add" or "subtract" then there is no result to print.  At least if
the code you posted was complete.


More information about the Python-list mailing list