0% found this document useful (0 votes)
1 views26 pages

Solar System

The document outlines a project to create an interactive model of the solar system using Python dictionaries and the p5 library. It guides users through steps to build the model, including defining planet attributes, drawing orbits, and handling user interactions to display planet information. The project includes coding instructions for Mercury and Venus, along with debugging tips and links to resources.

Uploaded by

caiosandrocel4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views26 pages

Solar System

The document outlines a project to create an interactive model of the solar system using Python dictionaries and the p5 library. It guides users through steps to build the model, including defining planet attributes, drawing orbits, and handling user interactions to display planet information. The project includes coding instructions for Mercury and Venus, along with debugging tips and links to resources.

Uploaded by

caiosandrocel4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Projects

Solar system
Get to know Python dictionaries by creating a
model of the solar system

Step 1 You will make

Take our survey ([Link] to help make our Code Editor


better!

Get to know Python dictionaries by creating a model of the solar system.

The limits of models: Even very advanced models leave out details to make them easier to build and
run. In fact, it’s not possible to make an accurate model of the whole solar system as all the planets
pull on each other because of gravity. The maths to predict exactly where they will go has not been
invented yet as a result.
This model uses the order of the planets, and their speeds and sizes. But, for example, Mercury needs
to be slow enough so you can click on it. So the model makes Mercury faster than the other planets,
but not as fast as it really is.

You will:

Use dictionaries to store and look up data


Load data from a file into dictionaries
Create an animated, interactive, solar system model using the p5 library
Dictionaries: When you make a Python dictionary, it stores things you can look up later. This is a lot
like a normal dictionary. But the Python version can store much more than the meanings of words!
Step 2 Create a dictionary

To start, you’ll collect some information about Mercury


and draw its orbit.

Open the Solar system starter project ([Link]


starter). The Raspberry Pi code editor will open in another browser tab.

If you have a Raspberry Pi account, you can click on the Save button to save a copy to your
Projects library.

Make a dictionary

Python dictionaries let you look up a key and get its value. That could be a word and its meaning, which
are both text. But you could also use a text key (like 'distance') to get a value that’s a number, or anything
else you can store in Python.
Python dictionaries

Find the # load_planets function comment in the starter project. Create the function below the
comment. Inside the function, make a global mercury dictionary. Then, add information about
Mercury to the dictionary.

Key Value
name Mercury
colour Color(165, 42, 42)
size 15
orbit 150
speed 1
info The smallest and fastest planet.

Curly brackets {} are used to start and end the dictionary. A colon : is used to separate the key
and the value(s). A comma , is used to separate each dictionary item.

[Link] — load_planets()

16 # load_planets function
17 def load_planets():
18 global mercury
19
20 mercury = {
21 'name': 'Mercury',
22 'colour': Color(165, 42, 42),
23 'size': 15,
24 'orbit': 150,
25 'speed': 1,
26 'info': 'The smallest and fastest planet.'
27 }

Tip: You can put each key: value pair on its own line. This makes the code easier to read, but be
sure to keep it all inside the curly brackets {}.

Using a dictionary lets you keep all the information about Mercury in one place. This makes it easier to find
it, and change it if you need to.
Call load_planets() in your setup() function.

[Link] — setup()

30 def setup():
31 # Put code to run once here
32 size(400, 400)
33 load_planets()

Draw Mercury’s orbit

Modelling orbits: The real planets’ orbits are not perfect circles — they’re the shape of an ellipse. But
using circles makes the model easier to build!

You can get a value from a dictionary by putting its key in square brackets [], just like getting a list item
by its index. For example, mercury['size'] would get you the matching value 15.

Find the #draw_orbits function comment. Create the draw_orbits() function below it. Then draw
Mercury’s orbit as an ellipse centered in the middle of the model width/2 and height/2. The size
of the ellipse will be mercury['orbit'], which is stored in your dictionary as 150.

Draw an ellipse

[Link] — draw_orbits()

10 # draw_orbits function
11 def draw_orbits():
12 no_fill()
13 stroke(255) # Make it white
14
15 ellipse(width / 2, height / 2, mercury['orbit'],
mercury['orbit'])
Call your draw_orbits() function from your draw() function.

[Link] — draw()

39 def draw():
40 # Put code to run every frame here
41 background(0)
42 no_stroke()
43 draw_sun()
44 draw_orbits()

Test: Run your code and see the orbit of Mercury appear.

Debug: If you see a message about mercury being ‘not defined’:

Check your load_planets() function to be sure that it declares mercury as global


Check that load_planets() is called in setup()

Debug: If the orbit doesn’t appear:

Check that you have called draw_orbits() in your draw() function


Check draw_orbits() to be sure you have used stroke(255) to make the ellipse white

Debug: If the orbit is a filled circle, instead of a ring, check you have no_fill() in your
draw_orbits() function.

Debug: If you get a bad input error, check that you have a : in between the keys and values of
your mercury dictionary, and that each line (except the very last one) has a comma.

Save your project


Step 3 Make Mercury

Now you’ll put Mercury in orbit of the sun.

Draw Mercury

The make_planet() function is written in a separate file that is included as part of the starter project and
imported into [Link] for you to use.

make_planet() uses the colour, orbit, size, and speed of a planet to draw the planet orbiting the sun.

Find the # draw_planets function comment. Create the function below it.

Make variables to store the values needed to draw Mercury. Then call make_planet(), passing it
those values.

Parameters in functions

[Link] — draw_planets()

17 # draw_planets function
18 def draw_planets():
19 colour = mercury['colour']
20 orbit = mercury['orbit']
21 size = mercury['size']
22 speed = mercury['speed']
23
24 make_planet(
25 colour,
26 orbit,
27 size,
28 speed
29 )

Tip: You created your dictionary with one line for each key: value pair. You can do the same
when passing values to a function to make your code easier to read.
Add a call to draw_planets() in the draw() function.

[Link] — draw()

50 def draw():
51 # Put code to run every frame here
52 background(0)
53 no_stroke()
54 draw_sun()
55 draw_orbits()
56 draw_planets()

Test: Run your code and see Mercury in orbit!

Debug: If you get a message about ‘KeyError’, check the spelling of your keys in make_planet().
Make sure the spelling is the same in load_planets(). Whether the letters are UPPER CASE or
lower case is important too.

Debug: If Mercury doesn’t appear:

Check that you are calling draw_planets() in draw()


Make sure that that call is after background(0)

Debug: If Mercury is too big, too slow, or not visible, check that your draw_planets() code is the
same as the example. In particular, check that the keys are in the right order.

Tell users about the planet

Users will click on Mercury and your program will print the information in mercury['info'].

The mouse_pressed() function was included as part of the starter project. It contains code to get the hex
value of a colour a user clicked on. You can use this to tell which planet they have clicked.
Find mouse_pressed() and add an if statement. Have it print Mercury’s name and information
when the user clicks on the planet.

[Link] — mouse_pressed()

60 def mouse_pressed():
61 # Put code to run when the mouse is pressed here
62 pixel_colour = Color(get(mouse_x, mouse_y)).hex # Here
63 the RGB value is converted to Hex so it can be used in a
64 string comparison later
65
66 if pixel_colour == mercury['colour'].hex:
print(mercury['name'])
print(mercury['info'])

When the user clicks on a pixel, the hex colour value of the pixel is retrieved and compared against the
colours of the planets. If the pixel colour is the same as a planet’s colour, information about that planet is
displayed.
Test: Run your code and click on Mercury to see its information print out. If it’s moving too fast,
change the frame_rate value in the run() function to slow the whole model down.

Debug: If nothing happens when you click on Mercury, check your if statement. Make sure it
looks exactly like the example above. Check that you have == and not =.

Debug: If you get a message about ‘KeyError’, check the spelling of your keys ('name' and
'info') in mouse_pressed(). Make sure the spelling is the same in load_planets().

Save your project


Step 4 Make Venus

It’s time for Venus to join Mercury in your model.

Values for other planets are in the [Link] file.

What's in [Link]?

Load the data

Add a global variable for Venus to your load_planets() function:

[Link] — load_planets()

32 # load_planets function
33 def load_planets():
34 global mercury, venus
Below your mercury dictionary, load [Link] to a data variable. Then use the splitlines()
function to split the text string in data into a list. Each line in the string will become an item in
the list.

Read a file with Python

[Link] — load_planets()

35 mercury = {
36 'name': 'Mercury',
37 'colour': Color(165, 42, 42),
38 'size': 15,
39 'orbit': 150,
40 'speed': 1,
41 'info': 'The smallest and fastest planet.'
42 }
43
44 with open('[Link]') as f:
45 data = [Link]()
46 lines = [Link]()

Now you have the data in your program. Next, you’ll make that data into dictionaries, like the one you
made for Mercury. lines[2] has the data for Venus, and lines[3] has the data for Earth.

Split lines[2] at the commas and store it in planet. Then print planet out.

[Link] — load_planets()

44 with open('[Link]') as f:
45 data = [Link]()
46 lines = [Link]()
47
48 planet = lines[2].split(',') # Split Venus' data
49 print(planet)
Test: Try running your code, and look at the list of data it prints out. Notice that the numbers
are inside quotes '. This shows that Python sees them as text strings, instead of numbers it
could do maths with.

Debug: If your planet prints out a list with only one item, then check that you have ',' in the ()
of lines[2].split().

Debug: If you see a message about split being ‘not defined’, check that you have included
lines[2]. before it.

Debug: If you see a message like 'list' object has no attribute 'split', check that you have
included [2] after lines.

Tip: Now that you’ve used it for testing, you can comment-out print(planet) with #.

Load the list of values from planet into a venus dictionary. As you are making the dictionary,
change any numbers from text to numbers. Use int() for whole numbers and float() for
decimals.

[Link] — load_planets()

44 with open('[Link]') as f:
45 data = [Link]()
46 lines = [Link]()
47
48 planet = lines[2].split(',') # Split Venus' data
49 #print(planet)
50 venus = {
51 'name': planet[0],
52 'colour': Color(int(planet[1]), int(planet[2]),
53 int(planet[3])), # Make them numbers
54 'size': int(planet[4]), # int() for whole numbers
55 'orbit': int(planet[5]),
56 'speed': float(planet[6]), # float() for decimals
57 'info': planet[7]
}
Draw the orbit

Go to your draw_orbits() function and add the orbit of Venus.

[Link] — draw_orbits()

10 # draw_orbits function
11 def draw_orbits():
12 no_fill()
13 stroke(255) # Make it white
14
15 ellipse(width / 2, height / 2, mercury['orbit'],
16 mercury['orbit'])
ellipse(width / 2, height / 2, venus['orbit'],
venus['orbit'])

Test: Run your code and see the orbit of Venus appear.

Debug: If you see a message about venus being ‘not defined’, check load_planets(). Make sure
you have declared venus as global.
Draw the planet

Go to your draw_planets() function. Add a make_planet() call, passing it the values for Venus.

Tip: You can copy and paste the code you used to make Mercury to save some time and typing.
Just change all the mentions of mercury to venus in the copy.

Copy and pasting

[Link] — draw_planets()

18 # draw_planets function
19 def draw_planets():
20 colour = mercury['colour']
21 orbit = mercury['orbit']
22 size = mercury['size']
23 speed = mercury['speed']
24
25 make_planet(
26 colour,
27 orbit,
28 size,
29 speed
30 )
31
32 colour = venus['colour']
33 orbit = venus['orbit']
34 size = venus['size']
35 speed = venus['speed']
36
37 make_planet(
38 colour,
39 orbit,
40 size,
41 speed
42 )
Test: Run your code and check that Venus orbits the Sun.

Debug: If you get a message about ‘KeyError’, check the spelling of your keys in make_planet().
Make sure the spelling is the same in load_planets(). Whether the letters are UPPER CASE or
lower case is important too.

Debug: If any planet is too big, too slow, or not visible, check that your draw_planets() code is
the same as the example. In particular, check that the keys are in the right order.

Tell users about Venus

Like Mercury, Venus should print out an interesting fact when it’s clicked on.

In mouse_pressed() add elif statements after the if statement you made for Mercury. Have
these check for Venus’ colour. Then, if there’s a match, print() the right fact.

[Link] — mouse_pressed()

83 def mouse_pressed():
84 # Put code to run when the mouse is pressed here
85 pixel_colour = Color(get(mouse_x, mouse_y)).hex # Here
86 the RGB value is converted to Hex so it can be used in a
87 string comparison later
88
89 if pixel_colour == mercury['colour'].hex:
90 print(mercury['name'])
91 print(mercury['info'])
92 elif pixel_colour == venus['colour'].hex:
print(venus['name'])
print(venus['info'])
Test: Run your code. Click on Venus to see its information print out.

Debug: If nothing happens when you click on Venus, check its elif statement. Make sure it
looks exactly like the example above. Check that you have == and not =.

Save your project


Step 5 Make Earth

Now finish the model by adding the


planet you’re on!

Load the data

Add a global variable for Earth to your load_planets() function:

[Link] — load_planets()

47 # load_planets function
48 def load_planets():
49 global mercury, venus, earth

You already have the data in your program: Earth’s data was loaded into lines when you loaded
[Link].
Below your venus dictionary, split lines[3] and put it in an earth dictionary.

Tip: You can copy and paste the code you used to make the venus dictionary to save you some
time. Then just make small changes — lines[2] to lines[3], and venus to earth.

[Link] — load_planets()

56 with open('[Link]') as f:
57 data = [Link]()
58 lines = [Link]()
59
60 planet = lines[2].split(',')
61 #print(planet)
62 venus = {
63 'name': planet[0],
64 'colour': Color(int(planet[1]), int(planet[2]),
65 int(planet[3])),
66 'size': int(planet[4]),
67 'orbit': int(planet[5]),
68 'speed': float(planet[6]),
69 'info': planet[7]
70 }
71
72 planet = lines[3].split(',')
73 earth = {
74 'name': planet[0],
75 'colour': Color(int(planet[1]), int(planet[2]),
76 int(planet[3])),
77 'size': int(planet[4]),
78 'orbit': int(planet[5]),
79 'speed': float(planet[6]),
'info': planet[7]
}
Draw the orbit

Go to your draw_orbits() function and add the orbit of Earth.

[Link] — draw_orbits()

10 # draw_orbits function
11 def draw_orbits():
12 no_fill()
13 stroke(255) # Make it white
14
15 ellipse(width / 2, height / 2, mercury['orbit'],
16 mercury['orbit'])
17 ellipse(width / 2, height / 2, venus['orbit'],
venus['orbit'])
ellipse(width / 2, height / 2, earth['orbit'],
earth['orbit'])

Test: Run your code and see the orbit of Earth appear.

Debug: If you see a message about earth being ‘not defined’, check load_planets(). Make sure
you have declared earth as global.
Draw Earth

Go to your draw_planets() function. Add a make_planet() call, passing it the values for Earth. Like
with Venus, you can copy and paste code here to save yourself some work.

[Link] — draw_planets()

19 # draw_planets function
20 def draw_planets():
21 colour = mercury['colour']
22 orbit = mercury['orbit']
23 size = mercury['size']
24 speed = mercury['speed']
25
26 make_planet(
27 colour,
28 orbit,
29 size,
30 speed
31 )
32
33 colour = venus['colour']
34 orbit = venus['orbit']
35 size = venus['size']
36 speed = venus['speed']
37
38 make_planet(
39 colour,
40 orbit,
41 size,
42 speed
43 )
44
45 colour = earth['colour']
46 orbit = earth['orbit']
47 size = earth['size']
48 speed = earth['speed']
49
50 make_planet(
51 colour,
52 orbit,
53 size,
54 speed
55 )
Test: Run your code and check that Earth orbits the Sun.

Debug: If you get a message about ‘KeyError’, check the spelling of your keys in make_planet().
Make sure the spelling is the same in load_planets(). Whether the letters are UPPER CASE or
lower case is important too.

Debug: If any planet is too big, too slow, or not visible, check that your draw_planets() code is
the same as the example. In particular, check that the keys are in the right order.

Tell users about Earth

Like Mercury and Venus, Earth should print out an interesting fact when it’s clicked on.
In mouse_pressed() add an elif statement for Earth like the one you made for Venus. Have it
check for Earth’s colour. Then, if there’s a match, print() the right fact.

[Link] — mouse_pressed()

108 def mouse_pressed():


109 # Put code to run when the mouse is pressed here
110 pixel_colour = Color(get(mouse_x, mouse_y)).hex # Here
111 the RGB value is converted to Hex so it can be used in a
112 string comparison later
113
114 if pixel_colour == mercury['colour'].hex:
115 print(mercury['name'])
116 print(mercury['info'])
117 elif pixel_colour == venus['colour'].hex:
118 print(venus['name'])
119 print(venus['info'])
120 elif pixel_colour == earth['colour'].hex:
print(earth['name'])
print(earth['info'])

Test: Run your code. Click on Earth to see its information print out.

Debug: If nothing happens when you click on Earth, check its elif statement. Make sure it looks
exactly like the example above. Check that you have == and not =.

Save your project


Upgrade your project
In this step, add more planets to your model, or change
the ones you have.

Add more planets

The [Link] file has information for the other five planets too. Add as many of them as you want.

To add a planet to your model you will need to:

Add code to load it in load_planets()


Add code to draw its orbit in draw_orbits()
Add code to draw the planet in draw_planets()
Add code to notice when the planet is clicked, and print out its info in mouse_pressed()

Tip: Don’t forget you can copy and paste code!

Increase the size() in your setup() function to make the model large enough to see your new
planets; size(900, 900) will fit them all in.

Make up a planet!

Add an extra planet to the solar system. Create a new global variable with a dictionary for it.
Then, add code to draw it and to print out its info.

Completed project

Save your project


What next?
If you are following the More Python ([Link] path,
you can move on to the Codebreaker ([Link] project.
In that project, you will analyse a graph to crack a hidden code!

If you want to have more fun exploring Python, then you could try out any of these projects ([Link]
[Link]/en/projects?software%5B%5D=python).

Published by Raspberry Pi Foundation ([Link] under a Creative Commons


license ([Link]
View project & license on GitHub ([Link]

Published by Raspberry Pi Foundation ([Link] under a Creative


Commons license ([Link]
View project & license on GitHub ([Link]
em-simulator)

Accessibility ([Link]
Cookies Policy ([Link]
Privacy Policy ([Link]
Translate for us (/en/projects/translating-for-raspberry-pi)

You might also like