Data variables
So, here's *one* answer.
import random
y0 = 50
x0 = 50
if random.random() < 0.5:
y0 += 1
else:
y0 -= 1
print(y0)
Did you get anything similar? A few things to point out...
Firstly, with coding, there is no definitive right answer. There are plenty of wrong answers, but also plenty of right answers. For example, here's a different one:
import random
y0, x0 = 50, 50
rand = random.random()
if rand < 0.5:
y0 = y0 + 1
else:
y0 = y0 - 1
print(y0)
Now some differences are *better* than others (the above creates an extra variable "rand
", so is less efficient, but many
are mainly stylistic (there's very little difference between "y0 = y0 + 1
" and "y0 += 1
"). It doesn't make sense to
ask if code is "right" or not; the question is rather "does it work?" and "does it work well?". The latter comes with reading and
practice; for now, anything the works is a massive achievement, so the question to concentrate on (once it runs) is "how do I test it is working?"
Secondly, note how the code above is laid out: blank lines are used to break the code into logical units. Unlike indents, which have meaning in Python, blank lines are ignored by the interpreter, and can be used to make the code more readable. Readable code is extremely important, both when you're working with others and when you're likely to re-visit your code later. Using sensible variable names and plenty of blank lines are critical to readability. What we've forgotten in the above is comments! Let's add these in now:
import random
# Set up variables.
y0 = 50
x0 = 50
# Random walk one step.
if random.random() < 0.5:
y0 += 1
else:
y0 -= 1
print(y0)
Thirdly, note that random.random()
is a function that we've imported with the random
module, which is part of the standard library:
random.random()
means "the random()
function within (".
") the random
module". random.random()
is
really useful. It generates a random floating point number within the range zero to just less than one – the
documentation rather unhelpfully uses
interval notation to descibe this as
a "semi-open range [0.0, 1.0)". You can multiply it by 100 to generate a float between 0 and just less than 100. There's
also a random.randint(start,end)
function that will generate int values between start
and end
(inclusive, strangely), for example random.randint(0,9)
will generate
numbers between and including zero and 9.
Ok, so we've been ignoring x0
while discussing all that. Can you add in the code to move x0
as well?
In thinking through how to change x0
, think about whether or not we can use the y0
code to do both jobs?