+ 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?
7 Antworten
+ 11
# Maybe try it like this:
import random
rooms = ('hello'
, 'hi', 'bonjour')
print(random.choice(rooms))
+ 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)
+ 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 🐍
+ 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*
+ 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.")
+ 4
@Kuba Agreed completely. You're definitely the 🐍-charmer here. :D
+ 4
@Kuba Yeah thats true! thanks. Edited