简体   繁体   English

如何在任何循环中永久添加变量或字符串(到列表或词典)?

[英]How to permanently add variables or string (to a list or dictionary) in any loop?

I have to write a piece of code for an assessment for my course, the requirement that I am having difficulties completing is storing all of the room names into a list or dictionary straight from a loop. 我必须编写一段代码来评估我的课程,我很难完成的要求是将所有房间名称直接从循环存储到列表或字典中。 I have tried researching it but nothing really helps me do this specifically. 我曾尝试研究它,但没有什么能真正帮助我做到这一点。 As I am quite new to python, I would really appreciate a way to work this out in simpler terms. 由于我对python还是很陌生,所以我真的很希望以更简单的方式解决此问题。

This is my code: 这是我的代码:

print ("+++++++++++++++\nPRICE ESTIMATOR\n+++++++++++++++")

roomnames={}
cnumber = input("Please enter your customer number: ").upper()

dateofestimate = input("Please enter the estimated date (in the format dd/mm/yyyy) : ")

rooms = int(input("Please enter the number of rooms you would like to paint: "))

x = 0 

for i in range (0,rooms):
    x = x+1
    print("\nFOR ROOM:", str(x))
    Rname = input("Please enter a name: ")
    roomnames = {(x):(Rname)}

print(roomnames)

The output I get is like this: 我得到的输出是这样的:

FOR ROOM: 1
Please enter a name: lounge

FOR ROOM: 2
Please enter a name: kitchen

FOR ROOM: 3
Please enter a name: bedroom 1 

FOR ROOM: 4
Please enter a name: bedroom 2

{4: 'bedroom 2'}

I would like to store all of the room names and the room number it corresponds to, to get something like this: 我想存储所有房间名称及其对应的房间号,以得到如下信息:

{1: 'lounge', 2: 'kitchen', 3: 'bedroom 1', 4: 'bedroom 2'}

If there is a simpler way, like using a list I am happy for any advice on that also. 如果有更简单的方法,例如使用列表,我也很乐意为此提供任何建议。

you can use code like this: 您可以使用如下代码:

rooms = int(input("Please enter the number of rooms you would like to paint: "))
roomandname= {i: input("Please enter a name: ") for i in range(rooms)}

some thing like this would work: 这样的事情会起作用:

RoomsNumberAndName.append(x)
Rname = input("Please enter a name: ")
RoomsNumberAndName.append(Rname)

Here is a longer code which checks for valid inputs: 这是更长的代码,用于检查有效输入:

#Let's first find nr (nr of rooms)
valid_nr_rooms = [str(i) for i in range(1,11)] #1-10
while True:
    nr = input("Please enter the number of rooms you would like to paint (1-10): ")
    if nr in valid_nr_rooms:
        nr = int(nr)
        break
    else:
        print("Invalid input")

#Now let's create a the dict
#But we could also use a list if the keys are integers!
rooms = {}
for i in range(nr):
    while True:      
        name = input("Name of the room: ").lower()
        # This checks if string only contains 1 word
        # We could check if there are digits inside the word etc etc
        if len(name.split()) == 1:
            rooms[i] = name
            break
        else:
            print("Invalid input")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM