我想要在一个循环中获得输入,我想向用户显示他们正在为该循环中的第1、2、3等项输入数据,有人能帮我修复我的代码吗?
n=int(input("Pleaseenter the number of laptops: "))
i=0
while i!=n:
laptops_price=input("Please enter the price of the {i}laptop: ".format(i))
i+=1发布于 2022-05-02 00:17:53
您混淆了f字符串和format调用。它们并不完全一样。这两种方法中的任何一种都能奏效:
laptops_price=input(f"Please enter the price of the {i}laptop: ")
laptops_price=input("Please enter the price of the {}laptop: ".format(i))发布于 2022-05-02 00:21:18
使用{}而不是{i},而使用for i in range(n)循环--它更方便
另外,我不确定你的确切目的,但是让laptops_prices成为一个列表,然后使用.append()代替
发布于 2022-05-02 00:33:49
好吧,这里有几件事值得考虑:
首先,在我看来,这个问题有点模糊,从某种意义上说,您只需签出代码,使其正常工作,只需做一些小改动。
其次,您可能需要一个序号的dict设置,将笔记本电脑的名称从“1”更改为“1”等,但这是相当微不足道的。
第三,您正在使用的循环的问题。最好是用一个靶场。
所以,
调整后的版本(工作):
n=int(input("Please enter the number of laptops: "))
i=0
while i!=n:
laptops_price=input("Please enter the price of laptop "+str(i)+": ".format(i))
i+=1尽管上述方法有效,但它可能会从一些更改中受益。新版本(工作):
n=int(input("Please enter the number of laptops: "))
for i in range(n):
laptops_price=input("Please enter the price of laptop "+str(i+1)+": ".format(i))如果你想要一本第一、第二、第三、第四等词典,用这个代替:
n=int(input("Please enter the number of laptops: "))
for i in range(n):
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4])
laptops_price=input("Please enter the price the "+ordinal(i+1)+" laptop: ".format(i))https://stackoverflow.com/questions/72081258
复制相似问题