On 1 July 2016 at 05:08, Elizabeth Weiss <cake...@gmail.com> 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.
This is used for display. The single quotes will be displayed as part of the string. This is so that people notice the commands, for example. >>> print("Enter 'add' to add two numbers") Enter 'add' to add two numbers >>> print("Enter add to add two numbers") Enter add to add two numbers >>> print('Enter "add" to add two numbers') Enter "add" to add two numbers > 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? Look at your current code. The following three lines appear twice (and will appear 4 times if you add multiplication and division): > num1=float(input("Enter a number")) > num2=float(input("Enter another number")) > print("The answer is"+ result) This is code repetition. It’s discouraged, because if you have 4 copies of a longer segment, and you want to change something, you would have to remember to change it in 4 places. In this case, you can avoid code reuse like this: 1. Check if user said 'quit', and if yes, break from the loop. (Ignore invalid input for now) 2. Ask the user for two numbers. 3. Make an if/elif/else structure to calculate the result. 4. Print out the result outside of `if`. Example for 3. and 4.: if user_input == 'add': result = num1 + num2 # no need to call str() if you use commas in print() elif user_input == 'subtract': result = num1 - num2 # other elif clauses go here print("The result is", result) -- Chris Warrick <https://chriswarrick.com/> PGP: 5EAAEA16 -- https://mail.python.org/mailman/listinfo/python-list