首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Gtting输入输入环

Gtting输入输入环
EN

Stack Overflow用户
提问于 2022-05-02 00:04:15
回答 3查看 25关注 0票数 0

我想要在一个循环中获得输入,我想向用户显示他们正在为该循环中的第1、2、3等项输入数据,有人能帮我修复我的代码吗?

代码语言:javascript
复制
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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-05-02 00:17:53

您混淆了f字符串和format调用。它们并不完全一样。这两种方法中的任何一种都能奏效:

代码语言:javascript
复制
laptops_price=input(f"Please enter the price of the {i}laptop: ")
laptops_price=input("Please enter the price of the {}laptop: ".format(i))
票数 0
EN

Stack Overflow用户

发布于 2022-05-02 00:21:18

使用{}而不是{i},而使用for i in range(n)循环--它更方便

另外,我不确定你的确切目的,但是让laptops_prices成为一个列表,然后使用.append()代替

票数 0
EN

Stack Overflow用户

发布于 2022-05-02 00:33:49

好吧,这里有几件事值得考虑:

首先,在我看来,这个问题有点模糊,从某种意义上说,您只需签出代码,使其正常工作,只需做一些小改动。

其次,您可能需要一个序号的dict设置,将笔记本电脑的名称从“1”更改为“1”等,但这是相当微不足道的。

第三,您正在使用的循环的问题。最好是用一个靶场。

所以,

调整后的版本(工作):

代码语言:javascript
复制
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

尽管上述方法有效,但它可能会从一些更改中受益。新版本(工作):

代码语言:javascript
复制
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))

如果你想要一本第一、第二、第三、第四等词典,用这个代替:

代码语言:javascript
复制
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))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72081258

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档