2024-03-29 11:12:32 发布
网友
如何创建一个循环来提示输入项目列表,每次提示都会更改。你知道吗
例如“输入你的第一项”然后“输入你的第二项”等等。。。(或1档、2档)
我需要将所有项添加到数组中:
items = [] for i in range(5): item = input("Input your first thing: ") items.append(item) print (items)
为什么不使用字符串格式?类似于
>>> for i in range(5): items.append(input("Enter item at position {}: ".format(i)))
稍微修改代码:
names = {1: "first", 2: "second", 3: "third" # and so on... } items = [] for i in range(5): item = input("Input your {} thing: ".format(names[i+1]) items.append(item) print(items)
或更一般的版本:
def getordinal(n): 如果str(n)[-2:]in(“11”,“12”,“13”): return“{}th”.format(n) elif str(n)[-1]=“1”: return“{}st”.format(n) elif str(n)[-1]=“2”: return“{}nd”.format(n) elif str(n)[-1]=“3”: return“{}rd”.format(n) 其他: return“{}th”.format(n)
或者更简洁的定义:
def getord(n): s=str(n) return s+("th" if s[-2:] in ("11","12","13") else ((["st","nd","rd"]+ ["th" for i in range(7)]) [int(s[-1])-1]))
使用提示列表:
prompts = ('first', 'second', 'third', 'fourth', 'fifth') items = [] for prompt in prompts: item = input("Input your {} thing: ".format(prompt)) items.append(item)
为什么不使用字符串格式?类似于
稍微修改代码:
或更一般的版本:
def getordinal(n): 如果str(n)[-2:]in(“11”,“12”,“13”): return“{}th”.format(n) elif str(n)[-1]=“1”: return“{}st”.format(n) elif str(n)[-1]=“2”: return“{}nd”.format(n) elif str(n)[-1]=“3”: return“{}rd”.format(n) 其他: return“{}th”.format(n)
或者更简洁的定义:
使用提示列表:
相关问题 更多 >
编程相关推荐