【发布时间】:2016-10-11 18:30:23
【问题描述】:
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!")
问题是我一次又一次地尝试让这段代码更小。
即使将“响应”作为字符串输入,也可以让用户一次性输入代码。
如果您还不知道,这是 GTIN-8 产品代码的代码,我知道还有其他各种 GTIN-8 代码,但我就是做不到,更不用说复制了。
【问题讨论】:
-
你想要改进的功能代码可以提交到代码审查stackexchange
-
创建一个输入 7 个数字的函数,然后在这两种情况下重复使用该函数。对于需要第 8 个输入的那个,要么保留你现在拥有的行,要么让你的函数接受一个布尔值,表示它是否需要输入 8。然后你可以返回一个包含所有值的列表。跨度>
标签: python-3.x reduction