能不能帮我解决我的问题,如果它不在列表中或不在同一索引点,请让我输入另一个权重。 谢谢您的帮助。 这是我的代码:
coins = [2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01]
weights = [120, 175, 160, 250, 325, 325, 356, 356]
a = []
found = False
foundd = False
loop = "yes"
bags = 0
ans = "no"
ansb = "no"
coina = 0
while loop == "yes":
name = input("What is your name?")
coin = float(input("What coin is it?"))
weight = float(input("How much does the bag weigh?"))
for x in coins:
if coin == x:
found = True
print("coin right")
if found == False:
print("coin wrong")
if weights.index(weight)==coins.index(coin):
foundd = True
print("weight right")
else:
print("weight wrong")
coina = coina + coin
bags += 1
newList = [name, coin, weight]
a.append (newList)
ans = input("Do you want to see the list with everyones names and amount of coins with weight?(yes?/no)")
ansb = input("Do you want to see amount of bags put in and coin value?(yes/no)")
if ans == "yes":
for i in a:
print(i)
if ansb == "yes":
print(bags,"£",coina)
loop = input("Do you want to enter another coin?(yes/no)")
(忽略它,除非我写更多,否则它不会让我发布。)
答案 0 :(得分:0)
您应该尝试:
coins = [2, 1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01]
weights = [120, 175, 160, 250, 325, 325, 356, 356]
a = []
found = False
foundd = False
loop = "yes"
bags = 0
ans = "no"
ansb = "no"
coina = 0
while loop == "yes":
name = input("What is your name?")
#ask for coin and check if it is in the list...
coin = float(input("What coin is it?"))
try:
coins.index(coin)
except:
print('Coin not in the list...')
coin = float(input("What coin is it?"))
#ask for weight and check if it is in the list...
weight = float(input("How much does the bag weigh?"))
try:
weights.index(weight)
except:
print('Weight not in the list...')
weight = float(input("How much does the bag weigh?"))
for x in coins:
if coin == x:
found = True
print("coin right")
if found == False:
print("coin wrong")
if weights.index(weight)==coins.index(coin):
foundd = True
print("weight right")
else:
print("weight wrong")
[...]
问题是您只能犯一个错误。
我觉得最简单的方法是使用for
循环来实现自己的索引函数。如果找不到该元素,此函数将返回索引或None
。这样,您可以要求用户输入while
的值为None
。
答案 1 :(得分:0)
dicta = {
2: 120, 1: 175, 0.5: 160, 0.2: 250, 0.1: 325, 0.05: 325,0.02: 356, 0.01: 356
}
while True:
name = input("What is your name? ")
coin = 'a'
while coin not in dicta.keys():
try:
coin = float(input("What coin is it ?"))
except ValueError:
print("Not a valid input")
weight = 'a'
while weight not in dicta.values():
try:
weight = float(input("How much does the bag weigh?"))
except ValueError:
print("Not a valid input")
if weight == dicta[coin]:
print("Weight right.")
else:
print("Weight wrong")
I would suggest building off a skeleton like this, also you should look into try, except
and how you are applying them