我最近在Matlab上的一些課程(主要側重於使用數學計算和繪圖)之後開始使用Python 3,我仍然是一個初學者。 但是我認爲創建一個計算器來計算可以隨Pokemon中的可用糖果進化的口袋妖怪的數量去使用Tkinter的GUI會很有趣。該程序工作正常,並給出了很好的結果。但是,我試圖改進我的編碼,並且此代碼包含大量嵌套的if和while語句,以及其他廣泛的變量和參數使用。我想知道如何改進這個代碼,使之更「pythonic」,或者如果這是創建一個像這樣的程序的正確方法。 預先感謝您在Python中使用大量嵌套語句時改進代碼
from tkinter import *
from tkinter import messagebox
def EvolveCalc():
title = "Pokemon evolve calculator"
Poke = var.get()
Candies_total = Candies.get()
PAmount = Poke_amount.get()
if Poke == 'Pokemon':
messagebox.showinfo(title,
"Please select a Pokemon from the dropdown menu")
elif not PAmount.isdigit():
messagebox.showinfo(title, "Please only enter numbers")
elif not Candies_total.isdigit():
messagebox.showinfo(title, "Please only enter numbers")
else:
Candies_total = int(Candies.get())
PAmount = int(Poke_amount.get())
Evolve = int((Candies_total - 1)/(Pokedex[Poke] - 1))
Candies_needed = (PAmount * (Pokedex[Poke] - 1)) + 1
if PAmount < Evolve:
n = 0
while Candies_needed <= Candies_total:
n = n + 1
PAmount = PAmount + 1
Candies_needed = ((PAmount) * (Pokedex[Poke] - 1)) + 1
Candies_total = Candies_total + 3
Evolve2 = int((Candies_total - 1)/(Pokedex[Poke] - 1))
String1 = '''You have enough candies too evolve {0} {1},
but you only have {2} {1} in storage and thus can only
evolve {2} {1} If you catch {3} more {1} you can now
evolve {4} {1}.'''
messagebox.showinfo(title, String1.format(Evolve, Poke,
Poke_amount.get(),
n, Evolve2))
else:
m = 0
while Candies_total <= Candies_needed:
m = m + 1
PAmount = PAmount - 1
Candies_needed = ((PAmount) * (Pokedex[Poke] - 1)) + 1
Candies_total = Candies_total + 1
Evolve2 = int((Candies_total - 1)/(Pokedex[Poke] - 1))
String2 = 'Transfer {0} {1} so you can evolve a total of {2} {1}.'
messagebox.showinfo(title, String2.format(m, Poke, Evolve2))
root = Tk()
Pokedex = {'pidgey': 12,
'caterpie': 12,
'weedle': 12
}
root.title("Pokemon evolve calculator")
var = StringVar(root)
var.set('Pokemon')
choices = Pokedex.keys()
Pokemon = OptionMenu(root, var, *choices)
Pokemon.grid(column=0, row=1)
L1 = Label(root, text='Candies')
L1.grid(column=1, row=0)
Candies = Entry(root)
Candies.grid(column=1, row=1)
L2 = Label(root, text='Pokemon amount in storage')
L2.grid(column=2, row=0)
Poke_amount = Entry(root)
Poke_amount.grid(column=2, row=1)
Calculate = Button(root, text='Calculate', command=EvolveCalc)
Calculate.grid(column=1, row=2)
root.mainloop()
這個問題可能更適合[code rev iew stack exchange](https://codereview.stackexchange.com/) –