I have a young friend of mine who is starting to learn Python in school and asked me to give him a little assignment. I am in no way a teacher nor a Python expert, but I accepted.
At first I thought it would be fun to start with a bit of parsing for the operation's input, like:
Enter your operation : 3+3
But it seemed a bit overwhelming for him so we agreed to separate it in three parts (first number, operand and second number).
I did a little correction but I find it clumsy and the point of the exercise is to show him some good practices.
So here is my code:
calculate = True
while calculate:
try:
number1 = float(input("Enter the first number : "))
except ValueError:
print("Incorrect value")
exit()
symbol = input("Enter the operation symbol (+,-,/,*,%) : ")
try:
number2 = float(input("Enter the second number : "))
except ValueError:
print("Incorrect value")
exit()
operande = ["+", "-", "*", "/", "%"]
resSentence = "Result of operation \"{} {} {}\" is :".format(number1, symbol, number2)
if symbol not in operande:
print("Incorrect symbol")
elif symbol == "+":
print(resSentence, number1 + number2)
elif symbol == "-":
print(resSentence, number1 - number2)
elif symbol == "*":
print(resSentence, number1 * number2)
elif symbol == "/":
print(resSentence, number1 / number2)
elif symbol == "%":
print(resSentence, number1 % number2)
restart = input("Do you want to do another calcul (Y/n) ? ")
while restart.lower() != "y" and restart.lower() != "n":
print(restart.lower(), restart.lower(), restart.lower()=="n")
restart = input("Please, enter \"y\" to continue or \"n\" to exit the program : ")
if restart.lower() == "n":
calculate = False
I would have wanted to do a loop when number1
or number2
is not a valid float
until the user enter a valid value, but I did not found a clean way to do it. I would gladly accept advices about this (even though I know this is not a question for this Stack Exchange, a good Pythonic way for doing this would be cool :) ).