Jayden
Jayden

Reputation: 107

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.

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.

Upvotes: 2

Views: 254

Answers (3)

Anton vBR
Anton vBR

Reputation: 18916

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")

Upvotes: 1

Amir Naimi
Amir Naimi

Reputation: 143

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)}

Upvotes: 3

Danii-Sh
Danii-Sh

Reputation: 455

some thing like this would work:

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

Upvotes: 1

Related Questions