-1
import math
def roundup(x):
return int(math.ceil(x/10.0)) * 10
w=0
while w == 5:
print("Would you like to *work out* a missing letter in a GTIN-8 code, or *check* a code?")
response = input(":")
if response == 'work out':
print("Input a 7 digit GTIN-8 code and I'll work out the 8th")
c1 = int(input("Enter FIRST number: "))
c2 = int(input("Enter SECOND number: "))
c3 = int(input("Enter THIRD number: "))
c4 = int(input("Enter FOURTH number: "))
c5 = int(input("Enter FIFTH number: "))
c6 = int(input("Enter SIXTH number: "))
c7 = int(input("Enter SEVENTH number: "))
y = (c1*3+c2+c3*3+c4+c5*3+c6+c7*3)
ru2=roundup(y)
GTIN8 = ru2-y
print("Your GTIN8 Code would be: "+str(c1)+str(c2)+str(c3)+str(c4)+str(c5)+str(c6)+str(c7)+str(GTIN8))
print("Wanna work out another?")
if response == 'check':
print("Input a 8 digit GTIN-8 code and I'll check if it's correct")
c1 = int(input("Enter FIRST number: "))
c2 = int(input("Enter SECOND number: "))
c3 = int(input("Enter THIRD number: "))
c4 = int(input("Enter FOURTH number: "))
c5 = int(input("Enter FIFTH number: "))
c6 = int(input("Enter SIXTH number: "))
c7 = int(input("Enter SEVENTH number: "))
c8 = int(input("Enter EIGTH number: "))
y = (c1*3+c2+c3*3+c4+c5*3+c6+c7*3)
ru2=roundup(y)
GTIN8 = ru2-y
if GTIN8 != c8:
print("Nope that product code is incorrect!")
reply=input("Want to know the correct answer to your code? Type yes if so: ")
if reply == 'yes':
print("The correct answer would have been: "+str(GTIN8))
if GTIN8 == c8:
print("That code is correct!")
問題是我已經一次又一次地嘗試使這個代碼更小。我如何重構此代碼以縮短它?
即使通過輸入'response'作爲字符串,以允許用戶一次輸入代碼。
如果你還不知道,這是一個GTIN-8產品代碼的代碼,我知道還有其他各種GTIN-8代碼,但我無法做到,更不用說複製了。
您想要改進的功能代碼可以提交給代碼審查stackexchange –
爲輸入您的7個數字創建一個函數,然後在兩種情況下重用該函數。對於需要第8個輸入的那個,或者保留現在的行,或者讓你的函數使用bool來表示是否需要請求第8個輸入,然後可以返回包含所有值的列表。 –
我建議你在http://codereview.stackexchange.com/上提問 –