I am working on a program that needs to do the following:
Write a script that asks a user for a number. The script adds 3 to that number. Then multiplies the result by 2, subtracts 4, subtracts twice the original number, adds 3, then prints the result.
Here is my first solution:
#Prompt user for number
number = input("Input a number")
#Print out the solution
print number + 3 * 2 - 4 - (number * 2) + 3
And here is my second solution:
#Prompt user for number
number = input("Input a number ")
#Add 3 to number
print "Let's add 3"
number1 = number + 3
print number1
#Multiply by 2
print "Let's multiply by 2"
number1 = number1 * 2
print number1
#Subtract 4
print "Let's subtract 4"
number1 = number1 - 4
print number1
#Subtract twice the original number
print "Let's subtract the original number twice!"
number2 = number + number
number1 = number1 - number2
print number1
#Add 3
print "...And finally, we add 3"
number1 = number1 + 3
print "Our sum is", number1
Which solution is correct, or are they both incorrect?
I know this is very basic, but I am learning to Program. I thought I would try out 2 different ways of writing this code.
Just add a pair of parentheses to your first version to correct it:
Otherwise,
3 * 2would be evaluated with higher precedence than the additions and subtractions.Note that the output does not depend on the number at all. Simplifying the expression shows that
does the same as the code above.