基本的なPython計算機
私には、学校でPythonを学び始めている若い友人がいて、彼にちょっとした課題を与えるように頼まれました。私は決して教師でもPythonの専門家でもありませんが、受け入れました。
最初は、次のように、操作の入力を少し解析することから始めるのが楽しいと思いました。
Enter your operation : 3+3
しかし、彼にとっては少し圧倒されたように見えたので、3つの部分(最初の数字、オペランド、2番目の数字)に分けることに同意しました。
私は少し修正しましたが、それは不器用であり、演習のポイントは彼にいくつかの良い習慣を示すことです。
だからここに私のコードがあります:
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
私は時にループをやってみたかっただろうnumber1か、number2有効でないfloatユーザが有効な値を入力するまで、私はそれを行うにはきれいな方法が見つかりませんでした。私はこれについてのアドバイスを喜んで受け入れます(これがこのStack Exchangeの質問ではないことはわかっていますが、これを行うための優れたPythonの方法はクールです:))。
回答
より多くの機能を使用する
あなたは関数を持っていますが、calculate()それが単に計算する以上のことをしているのを見れば、これはあなたのコードを不当に不格好に見せます。しかし、非常に単純な解決策があります。より多くの関数を使用してください。メインループが次のようになったらどうなりますか
while True:
number1,number2,operand = take_input()
result = calculate(number1,number2,operand)
print(f"Answer : {numebr1} {operand} {number2} = {result}")
if input("Do you want to play again? (y/n): ").lower() == 'n':
break
これにより、プログラムの保守が容易になります。
continue エラーが発生したとき
try:
number1 = float(input("Enter the first number : "))
except ValueError:
print("Incorrect value")
exit()
ユーザーが無効な入力を入力すると、プログラムが終了するのはなぜですか?彼にもう一度チャンスを与えるxD
一貫したインデントを維持する
try:
number2 = float(input("Enter the second number : "))
except ValueError:
print("Incorrect value")
exit()
4以前にスペースを使用したことがあるため、一貫したインデントを維持するようにしてください。8後で使用する理由はありません。後でコードを読む人を混乱させる可能性があります。
コードロジック1
このサンプル入力を考えてみましょう
Enter the first number : 1
Enter the operation symbol (+,-,/,*,%) : I like python
Enter the second number : 2
Incorrect symbol
明らかに、それsymbolは間違っています。入力中に間違えたことがわかるために、なぜ2番目の番号を入力する必要があったのsymbolですか?シンボルが間違っているとすぐにわかるはずだったので、修正できました。
if symbol not in operandsステートメントを移動して、入力のすぐ隣に配置します。
eval
Pythonでの評価
これは、約10〜15行のコードを1つに変換するため、プログラムの最大の改善になります。
eval()式は、それが実行され、法的なPythonの文である場合、この関数は、指定された式を評価します。
おなじみですね、基本的には単純な表現を評価しているのではないでしょうか。
を使用するevalと、計算部分は次のようになります。
result = eval(f"{number1}{operand}{number2}")
例、 number1 = 5,number2 = 10, operand = '+'
これが基本的に起こっていることです
result = eval("5+10")
最後の
これが改善されたコードです
def take_input():
err_msg = "Invalid input"
operands = ['+','-','*','/','%']
try:
num1 = float(input("Enter number 1: "))
except Exception:
print(err_msg)
return take_input()
try:
num2 = float(input("Enter number 2: "))
except Exception:
print(err_msg)
return take_input()
print("Operands: " + ', '.join(x for x in operands))
try:
operand = input("Enter operand: ")
except Exception:
print(err_msg)
return take_input()
if operand not in operands:
print(err_msg)
return take_input()
return num1,num2,operand
def calculate(num1,num2,operand):
return eval(f"{num1}{operand}{num2}")
def mainloop():
while True:
num1,num2,operand = take_input()
result = calculate(num1,num2,operand)
print(f"Answer: {result}")
if input("Do you want to play again? (y/n): ").lower() == 'n':
break
mainloop()
これはコードの代替手段であり、少し複雑ですが、読みやすくなっています。私はなんとかループのことをすることができましたが、それに従うのはちょっと難しいです。ごめんなさい。
running = True
# Break Things up into functions each function does one single thing
def calculate(inputOne, operand, inputTwo):
"""
Calculates inputOne operand and inputTwo
"""
if operand == "+":
return inputOne + inputTwo
elif operand == "-":
return inputOne - inputTwo
elif operand == "*":
return inputOne * inputTwo
elif operand == "/":
return inputOne / inputTwo
elif operand == "%":
return inputOne % inputTwo
def askInput():
"""
Asks for a number until a number is given checks if each one is valid
"""
isValid = [False, False, False] # none of the numbers are validated yet
number1, symbol, number2 = ["", "", ""]
# Here is a good implementation of the loop, it is kind of complex though
while True:
try:
if not isValid[0]: # Asks for number1 if it is not valid
number1 = int(input("Enter the first number : "))
isValid[0] = True
if not isValid[1]: # This is added functionality because there was a loophole in your program
symbol = input("Enter the operation symbol (+,-,/,*,%) : ") # use tuples whenever possible
supportedOperands = ("+", "-", "/", "*", "%")
if symbol not in supportedOperands:
raise ValueError
isValid[1] = True
if not isValid[2]: # Asks for number2 if it is not valid
number2 = int(input("Enter the second number : "))
isValid[2] = True
break
except ValueError:
continue # this just restarts the whole thing
return number1, symbol, number2
def continueApp():
"""
Checks if the input to restart is valid
"""
restart = input("Do You want to do another calculation (Y/n) ? ").lower()
while True:
if restart == "y":
return True
elif restart == "n":
return False
else:
restart = input("Please, enter \"y\" to continue or \"n\" to exit the program : ").lower()
while running:
numberOne, operand, numberTwo = askInput()
answer = calculate(numberOne, operand, numberTwo)
resSentence = f"Result of operation {numberOne} {operand} {numberTwo} is : {answer}"
print(resSentence)
if continueApp():
pass
else:
running = False
exit()
チップ:
物事を機能に分割する:
関数は、関数が実行可能なコードのためだけのコンテナでなければならやるONEをのみとONEの機能上のものよりこちら。
コードにコメントしてみてください。読みやすく、編集しやすくなります。
この機能
def calc():
x = 1
y = 12
return (((x+y)/x)**y)+(3*x+4*y) # Please don't write like this in any case
説明や何が起こっているのかではるかに良いでしょう
def calc():
"""
Accepts: Nothing
Does: Adds X and Y, then divides it by X to the power of Y
then it adds it to X multiplied by three and 4 multiplied by Y
Returns: integer (the result of Does) ^^^^^
"""
x = 1
y = 12
return ((x+y)/x**y)+(3*x+4*y) # Again, please don't write code like this
f文字列を使用します(これにはPython 3.6以降が必要です)
f文字列はこのように使用されます
value = "12"
print(f"Number {value} is an example of an f string")
# Versus
print("Number {} is an example of an f string".format(value))
コードの間隔を空けるようにしてください
私を信じてください、これはあなたのコードを読みやすくそして理解しやすくします。
def calc():
"""
Accepts: Nothing
Does: Adds X and Y, then divides it by X to the power of Y
then it adds it to X multiplied by three and 4 multiplied by Y
Returns: integer (the result of Does) ^^^^^
"""
x = 1
y = 12
ans = (x + y) / (x ** y)
ans += (3 * x) + (4 * y) # just adds ans to the right side of the operator
return ans