how would I go about initiating a 'randomDirection' variable to hold a random value from the directions array, and set the lastDirection variable to an empty array in python?
Here is the code in JavaScript, how can I convert it into Python?
let lastDirection = [], randomDirection;
CodePudding user response:
Assuming you have a directions array then we use the random module to help us choose a random direction in directions. Also, an empty list can be set by initializing a variable to []
.
import random
directions = ['N', 'S', 'W', 'E']
random_direction = random.choice(directions)
last_direction = []
CodePudding user response:
(Note that []
in Python creates a list
, and not an array.)
Your question's title seems to be asking a different question than your question's body, so I'll answer both.
To append an element elem
to a list l
in Python, you could do any of the following (I recommend looking into all three for the educational value):
l = [a]
l.append(a)
l.extend([a])
There are differences between those but each of those would result in l
having a
added as its last element.
To choose a random element from a list called directions
and put it in lastDirection, you could use random.choice (remember to import random
for this):
lastDirection = random.choice(directions)
If you want lastDirection to be an array and to just append directions to it as you go, then you could initialize it like so:
lastDirection = []
And then append elements to it using one of the methods noted above.
CodePudding user response:
Just remove the "let".
CodePudding user response:
In python you dont need to put let,var or const.And you dont need to put ';' at the end of every line of code you write.
lastDirection = ([]), randomDirection