【问题标题】:How do you allow only inputs from a list? (python vending machine)你如何只允许来自列表的输入? (蟒蛇自动售货机)
【发布时间】:2015-10-03 04:52:01
【问题描述】:

我需要为一台只接受某些硬币的自动售货机编码

“它将允许您输入 1p、2p、5p、10p、20p、50p 和 1.00 英镑,但它会拒绝 2.00 英镑的硬币”

我有一个列表,里面有浮点值:

coins = ["0.01","0.02","0.05","0.10","0.20","0.50","1"]

这些是硬币,我希望用户输入

coin = float(input())

在这之后我有

def balance():
     coin = float(input("Please enter your coins."))
     if coin not in coins:
            print("Incorrect coin amount! Please remember we don't accept 2 pound coins!")

     else:
        print("Correct coin amount. The coins have been added to your balance")
        fb = fb + coin

我无法让它工作,因为它只会打印“硬币数量不正确!请记住我们不接受 2 磅硬币!”。 在此之后,我已经在这里尝试了这个解决方案:Python Coding - Vending machine - How to get the user to only enter certain coins? 我认为这意味着我需要更改我的 float(input()) 并且所有内容都浮动为 int,因此将 0.01 (1p) 更改为 1。但是,当我这样做时,我仍然得到了

'int' object has no attribute 'split'

在这段代码中使用时

dict = {"KitKat":"80p", "Coca-Cola":"85p", "DairyMilk":"80p","Walkers Crisps":"90p"}
coins = ["1","2","5","10","20","50","100"]

def balance():
    inp = int(input("Please enter your coins. Please enter in pence, for example 1 pound = 100"))
    if any(int(coin) not in value for coin in inp.split()):
        print("Machine doesn't accept these coins")


else:
    print("Correct coin amount. The coins have been added to your balance")
    fb = fb + coin


def items():
    print (" 1. KitKat:" , dict['KitKat'])
    print (" 2. Coca-Cola:", dict['Coca-Cola'])
    print (" 3. Dairy Milk:", dict["DairyMilk"])
    print (" 4. Walkers Crisps:", dict["Walkers Crisps"])
snack = 1 # need a while loop, ignore
fb = 0.00
balance()
print("Your full balance is",fb)

【问题讨论】:

标签: python python-3.x


【解决方案1】:

我建议您将英镑转换为便士,这样您就不必进行浮点数学运算,并且只要在显示值时转换回来即可。您也可以为此使用decimal 模块,但我们暂时不要过多参与。您的最终问题似乎是您正在比较不同类型的值,以及1 != "1"。让我们先排序。

coins = [1, 2, 5, 10, 20, 50, 100]  # pence
coin_in = int(input("Enter amount (in pence): "))

if coin_in not in coins:
    # incorrect input, handle it

【讨论】:

  • 还不如用一套硬币
  • @PadraicCunningham 是的,只是不想在他们仍在试图弄清楚他们已经学过什么的时候向他们扔任何新东西。一组 set([1, 2, 5, 10, 20, 50, 100])(或 {1, 2, 5, 10, 20, 50, 100})将是完美的数据类型,但我怀疑 OP 是否已经了解它们
  • 学习效率永远不要太早;)我认为集合是学习的重要内容,它们通常是二次运行时和线性运行时之间的区别。
  • @AdamSmith 正确,我还没有学过套装,也没有学过这个作业中的大部分内容。因此,如果我将硬币 = [] 更改为硬币 ([]),它会是一个更好的脚本吗?感谢您的帮助,工作完美,但必须修复一些我以某种方式产生的错误:)
  • @user3670603 语法为set([1, 2, 5, ...])。或者您可以使用文字表示法,它看起来像没有值的字典,只有键 {1, 2, 5, ...}。事实上,将集合视为没有值的字典是很有意义的。两者都是无序的,都有非常快的 (O(1)) 查找,并且都不支持重复(你不能像 [1, 1, 1, 1] 那样做 {1, 1, 1, 1}
猜你喜欢
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多