Need help with making lines of code to select random rooms. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Need help with making lines of code to select random rooms.

import random room1 = 'hello' room2 = 'hi' room3 = 'bonjour' I am not sure how to select a random room. Can someone make some lines of code showing me how?

8th Nov 2017, 7:03 PM
Hyrum Harris
Hyrum Harris - avatar
7 Answers
+ 11
# Maybe try it like this: import random rooms = ('hello' , 'hi', 'bonjour') print(random.choice(rooms))
8th Nov 2017, 7:10 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 7
@Gami It should go like this, in order to work: import random rooms = ("hello", "hi", "bonjour") randIndex = random.randint(0, len(rooms)-1) print(rooms[randIndex]) # randint is tricky, it has to have 2 arguments start and stop, but the output is start <= output <= stop (mind the *lower than or equal to* for the stop parameter, it's not like randrange, where it is only *lower than* stop)
8th Nov 2017, 7:30 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
@Netkos It definitely would :) I just assumed it's better for beginners to learn picking the adequate data type right away, thus foreseeing what they will actually want to do with the variables they declare. Planning ahead saves you a lot of code repetition, even in a rather-repetition-resistant Python 🐍
8th Nov 2017, 7:18 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 5
If you are using 3.6-, I recommend you the following solution import random rooms = ("hello", "hi", "bonjour") randIndex = random.randint(0, len(rooms)-1) print(rooms[randIndex]) *Then you can add more rooms, or getting rid of unwanted rooms*
8th Nov 2017, 7:23 PM
Gami
Gami - avatar
+ 4
*edit* Kuba's method is much better. :D Admittedly, I'm crap when it comes to Python, but what I posted should work the same. -------------- import random room1 = 'hello' room2 = 'hi' room3 = 'bonjour' randResult = random.randrange(1, 4) if randResult == 1: print(room1) elif randResult == 2: print(room2) elif randResult == 3: print(room3) else: print("Error: Out of range.")
8th Nov 2017, 7:17 PM
AgentSmith
+ 4
@Kuba Agreed completely. You're definitely the 🐍-charmer here. :D
8th Nov 2017, 7:22 PM
AgentSmith
+ 4
@Kuba Yeah thats true! thanks. Edited
19th Nov 2017, 2:07 PM
Gami
Gami - avatar