前提・実現したいこと
関数を使ったコードの短縮。
pythonの学習を始めたのですが書いたコードを関数を使って短くしたいと思ってもどうやればいいのか検討がつきません。どこで関数を使ったらいいか、などアドバイスを頂けたら幸いです。また、どこか改善点があればそれも教えていただけたらと思います。
該当のソースコード
python3
1ソースコード 2```a=0 3b=0.05 4c=0.07 5d=0.12 6another = "y" 7 8taxa = 0 9taxb = 0 10taxc = 0 11taxd = 0 12 13totala = 0 14totalb = 0 15totalc = 0 16totald = 0 17stpt = 0 18while another == "y": 19 item_number = int(input("Please enter a Item Number:")) 20 q = int(input("Please enter quantity:")) 21 p = float(input("Please enter the price:")) 22 if item_number in range (100,200): 23 totala = totala + p*q 24 taxa = totala * a 25 total = totala + totalb + totalc + totald 26 tax = taxa + taxb + taxc + taxd 27 stpt = tax + total 28 print("Subtotal before Tax:$ %7.2f" %(total), 29 "Total tax:$ %7.2f" %(tax), 30 "Subtotal plus Tax:$ %7.2f" %(stpt)) 31 another = input('Do you have another item?' + '(Enter y for yes, n for end):') 32 elif item_number in range (200,300): 33 totalb = totalb + p*q 34 taxb = totalb * b 35 total = totala + totalb + totalc + totald 36 tax = taxa + taxb + taxc + taxd 37 stpt = tax + total 38 print("Subtotal before Tax:$ %7.2f" %(total), 39 "Total tax:$ %7.2f" %(tax), 40 "Subtotal plus Tax:$ %7.2f" %(stpt)) 41 another = input('Do you have another item?' + '(Enter y for yes, n for end):') 42 elif item_number in range (300,400): 43 totalc = totalc + p*q 44 taxc = totalc * c 45 total = totala + totalb + totalc + totald 46 tax = taxa + taxb + taxc + taxd 47 stpt = tax + total 48 print("Subtotal before Tax:$ %7.2f" %(total), 49 "Total tax:$ %7.2f" %(tax), 50 "Subtotal plus Tax:$ %7.2f" %(stpt)) 51 another = input('Do you have another item?' + '(Enter y for yes, n for end):') 52 elif item_number in range (400,500): 53 totald = totald + p*q 54 taxd = totald * d 55 total = totala + totalb + totalc + totald 56 tax = taxa + taxb + taxc + taxd 57 stpt = tax + total 58 print("Subtotal before Tax:$ %7.2f" %(total), 59 "Total tax:$ %7.2f" %(tax), 60 "Subtotal plus Tax:$ %7.2f" %(stpt)) 61 another = input('Do you have another item?' + '(Enter y for yes, n for end):') 62 else: 63 print("Invaild Item Number") 64 another = input('Do you have another item?' + '(Enter y for yes, n for end):') 65print ("Total before Tax:$ %7.2f" %(total), 66 "Total tax:$ %7.2f" %(tax), 67 "Total plus Tax:$ %7.2f" %(stpt)) 68print ('end')
とりあえず質問文の編集を開いて、<code>みたいなボタンを押して出てくるものでコードをくくってください(あと「ここに言語を入力」を「python」に書き換える)。今の表示だとインデントも見えないし、読めないです
回答1件
あなたの回答
tips
プレビュー