## Drawing Rotating Rectangles

Here is another Python turtle example showing how to edit the background color of turtle screen and how to use RGB mode.

This example can give you a good understanding of RGB channels in images.

Here is a simply code that uses requests, json and webbrowser libraries:

``````import turtle
import random

x = 1
SN = turtle.Screen()
SN.bgcolor("gray")
a = turtle.Turtle()
a.speed(100)

i = 0
while x < 256:

r = random.randint(0,255)
g = 100
b = 150

turtle.colormode(255)
a.pencolor(i,g,b)
if x<252:
a.pensize(1)
a.forward(50 + x)
a.right(91.5)

x = x+1
i = (i+1)%255

turtle.done()   ``````

Code below will print a bunch of other information regarding cocktails such as: Instructions and Ingredients and it will also open the cocktail image in a browser.

``````import turtle

a = turtle.Turtle()
for i in range(240):
a.forward(2+i/4)
a.left(30-i/12)

turtle.done()``````

If you need a refresher on Python Turtle, here is a link to our Python Turtle lesson.

## Turtle Turbines

You can draw nice turbines with Python turtle with the codes in this tutorial.

We will explain how you can twist to code to give more flavor to your drawing as well.

``````import turtle

t = turtle.Turtle()

for i in range(10):
t.forward(200)
t.right(120)
t.forward(40)
t.goto(0,0)
t.left(84)

turtle.done()``````

## Turtle Pensize

`pensize()` will let you control the thickness of the pen. Look at the code below:
``````import turtle

t = turtle.Turtle()
t.pensize(5)

for i in range(10):
t.forward(200)
t.right(120)
t.forward(40)
t.goto(0,0)
t.left(84)

turtle.done()``````

## Turtle Colors

Using `color()` you can give your pen a color. Using a list of predefined colors you can loop through the colors with a simple trick. `%` operator will give the remainder from a division.

`colors[i%6]` will make sure colors only takes an index from 1 to 6 so each color gets assigned and then the index goes back to zero when i reaches a multiple of 6.

``````import turtle

colors = ["red", "blue", "green", "gray", "orange", "black"]
a = turtle.Turtle()

for i in range(30):
a.forward(20+i)
a.left(30 - i/1.5)
a.color(colors[i%6])

turtle.done()
``````
``````import turtle

t = turtle.Turtle()
colors = ['red', 'blue', 'orange', 'green', 'black', 'brown']

for i in range(10):
t.color(colors[i%6])
t.forward(200)
t.right(120)
t.forward(40)
t.goto(0,0)
t.left(84)

turtle.done()```
```

## Combining codes

Let’s add a post to our turbine so it can rotate one day.

``````import turtle

t = turtle.Turtle()
colors = ['red', 'blue', 'orange', 'green', 'black', 'brown']
t.pensize(20)

t.goto(0,150)
t.right(90)
t.color('gray')
t.forward(470)

t.pensize(3)

t.penup()
t.goto(0,150)
t.pendown()

for i in range(10):
t.color(colors[i%6])
t.forward(200)
t.right(120)
t.forward(40)
t.goto(0,150)
t.fillcolor("black")
t.left(84)

turtle.done()
```
```
``````import turtle

def turbase(thickness):

t = turtle.Turtle()
t.pensize(thickness)
t.color('lightgray')
t.penup()
t.goto(4,0)
t.pendown()
t.right(90)
t.forward(400)

def turwings(thickness, startingdegree):
t = turtle.Turtle()
t.pensize(thickness)
colors = ['red', 'blue', 'orange', 'green', 'black', 'brown']
t.color("darkblue")
i=30

t.penup()
t.forward(20)
t.pendown()
t.right(startingdegree)
t.forward(300)
t.left(174)
t.forward(300)

t.right(45)
t.forward(300)
t.left(175)
t.forward(300)

t.right(70)
t.forward(300)
t.left(175)
t.forward(300)

t.fillcolor('red')
turbase(20)
turwings(3, 257.5)
turtle.done()
```
```

If you enjoyed this Python turtle lesson, feel free to spread it.

## Turtle Spirals

Drawing with Python Turtles can be a lot of fun! You can draw nice turbines with Python turtle with the codes in this tutorial.

We will explain how you can twist the code to give more flavor to your drawings and practice coding while drawing or vice versa, who knows 🙂

Holy Python is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

``````import turtle

a = turtle.Turtle()

for i in range(100):
a.forward(5+i)
a.right(15)

turtle.done()``````

#### Turtle Step and Direction Adjustment(forward, backward, left, right)

Let’s make the spiral more dense with decreasing the steps ( `a.forward(2+i/4)` and
`a.left(30-i/12)`) and increasing the amount of turns (`for i in range(240):`).

``````import turtle

a = turtle.Turtle()
for i in range(240):
a.forward(2+i/4)
a.left(30-i/12)

turtle.done()``````

#### Smaller Loop(Fibonacci Sequence)

Fibonacci sequence is an interesting number sequence, sometimes referred to as golden ratio, that can be traced in many natural patterns in universe such as flowers, shells, snails, trees, leaves, storms, galaxies and fingerprints.

Here is an attempt to draw on Fibonacci proportions. Not exactly it, but close.

``````a = turtle.Turtle()

for i in range(30):
a.forward(20+i)
a.left(30 - i/1.5)

turtle.done()``````

## Turtle with Colors

You can escape Black & White or Mono-Color drawings by implementing `.color()` method of turtle.

#### Mono-color Turtle Drawing(Only implements one color throughout)

Let’s add some color to our Turtle drawings. `a.color(colors[0])`
``````import turtle

colors = ["red", "blue", "green", "gray", "orange", "black"]
a = turtle.Turtle()

for i in range(30):
a.forward(20+i)
a.left(30 - i/1.5)
a.color(colors[0])

turtle.done()``````

#### Multi-color Turtle Drawing(Navigates through a list of different colors)

Another fun idea is iterating through different colors. This can be easily achieved by defining a set of color and some basic loop iteration with turtle.

Color list is iterated using the help of “Modulus” operator (`%`) in Python. If you’d like to read an extensive article about Python operators including Modulus you can click here.

`a.color(colors[i%6])`

``````import turtle

colors = ["red", "blue", "green", "gray", "orange", "black"]
a = turtle.Turtle()

for i in range(30):
a.forward(20+i)
a.left(30 - i/1.5)
a.color(colors[i%6])

turtle.done()``````

That’s it. What you can do with Python Turtle is up to your imagination, so there is no limit. Try something that’s relevant to you and enjoy practicing!

If you find turtle interesting we have a very extensive tutorial that explains different Python concepts (such as if-else, user functions, user input, operators, data types, loops etc.) through turtle here: Python Turtle Tutorial.

ps: Don’t forget to include `turtle.done()` in the end so your turtle window can be terminated.

pss: We recommend Spyder IDE which comes with Anaconda Open Source All-in-One installation solution. Although it’s an IDE specialized in scientific applications it’s also perfect for Python practice. You can read more about effortless Python Installation here.

## Open Charge Map

Open Charge Map is an open source and free data solution which provides charging station data for electric vehicles. They have a great API showing the POI addresses of charge stations that can be used to locate these stations.

Here is a simply code that uses requests, json libraries:

Here is a simply code that uses requests, json libraries:

``````import requests
import json

params = {"latitude": 40.79, "longitude": -73, "countrycode": "US",
"output": "json", "compact": True, "verbose": False, "maxresults": 20}
f = r'https://api.openchargemap.io/v3/poi/?'
data = requests.get(f, params = params)
a = data.text
a = json.loads(a)

print(a)
for i in a:
try:
print(i)
print(i["AddressInfo"]["StateOrProvince"])
print(i["AddressInfo"]["Title"])
print(i["AddressInfo"]["AddressLine1"])
print(i["AddressInfo"]["Town"])
print(i["AddressInfo"]["Postcode"])
print(i["AddressInfo"]["StateOrProvince"], "\n")
except Exception:
pass``````

Here is an example of the data that’s returned from Open Charge Map API:

Phone: 631-473-1550
Access: Dealership business hours
Website:
Title: Ramp Ford
Address: 4869 Nesconset Hwy
Port Jefferson Station 11776 NY

Phone: 888-758-4389
Access: 24 hours daily
Website: http://www.chargepoint.com/
Title: K&H STATION 1
Address: 66 Southern Blvd
Nesconset 11767 NY

Phone: 888-758-4389
Access: 24 hours daily
Website: http://www.chargepoint.com/
Title: COMPETITION BMW
Address: 599 Jericho Turnpike
Smithtown 11787 NY

Phone: (631) 361-9696
Phone: 516-686-1007
Phone: 866-816-7584
Access: 24 hours daily
Website: http://evconnect.com/
Title: Stony Brook University
Address: 100 Nicolls Rd
Stony Brook 11794 NY

Phone: 888-758-4389

Access: 24 hours daily
Website: http://www.chargepoint.com/
Title: DONALDSONVW
Address: 5700 Sunrise Hwy
Sayville 11782 NY

Phone: 888-758-4389
Access: 24 hours daily
Website: http://www.chargepoint.com/
Title: SCCC
Address: 580-586 College Rd
Farmingville 11738 NY

Phone: 888-758-4389
Access: 24 hours daily
Website: http://www.chargepoint.com/
Title: MIDDLE COUNTRY
Address: 575 Middle Country Rd
Selden 11784 NY

Phone: 631-750-9454
Access: 9am-5pm M-F
Website:
Title: SUNation Solar Systems
Address: 171 Remington Blvd
Ronkonkoma 11779 NY

Here are  more parameters you can use while making a call to Open Charge Map API.

##### SERVICE PARAMETERS:

PARAMETERDESCRIPTIONDEFAULT
outputjson, xml, csv JSON format is recommended as highest fidelityjson
maxresultslimit on max number of results returned100
countrycodeGB, US etc. Single ISO Country Code.(blank)
countryidexact match on a given numeric country id (comma separated list)(blank)
latitudelatitude reference for distance calculation(blank)
longitudelongitude reference for distance calculation(blank)
distancereturn results based on specified distance from specified latitude/longitude(blank)
distanceunitMiles or KMMiles
operatoridexact match on a given EVSE operator id (comma separated list)(blank)
connectiontypeidexact match on a given connection type id (comma separated list)(blank)
levelidexact match on a given charging level (1-3) id (comma separated list)(blank)
minpowerkwminimum output power in kW (this information is not known for many locations)(blank)
usagetypeidexact match on a given usage type id (comma separated list)(blank)
statustypeidexact match on a given status type id (comma separated list)(blank)
dataprovideridexact match on a given data provider id id (comma separated list). Use opendata=true for only OCM provided (“Open”) data.(blank)
modifiedsincePOIs modified since the given date (UTC) e.g. 2016-09-15T09:30(blank)
opendatatrue or false. Set to true to include only Open Data licensed content, false to return only non-open licensed data. By default all available data is returned. You should refer to the license of the original data provider in each case.(blank)
includecommentstrue or false. Set to true to also include user comments and media items (photos) per charging location.false
verbosetrue or false. Set to false to get a smaller result set with null items removed.true
compacttrue or false. Set to true to remove reference data objects from output (just returns IDs for common reference data such as DataProvider etc).false
camelcasetrue or false. Set to true to get a property names in camelCase format.false
callbackspecify the name of the JSONP callback (if required), JSON response type only.(blank)
chargepointidexact match on a given POI id (comma separated list).(blank)

Additionally from v3 of the API onwards you can query using a bounding box, polygon or polyline (for a route etc).

PARAMETERDESCRIPTIONDEFAULT
boundingboxspecify top left and bottom right box corners as: (lat,lng),(lat2,lng2)(blank)
polygonSpecify an encoded polyline for the polygon shape. Polygon will be automatically closed from the last point to the first point.(blank)
polylineencoded polyline, use with distance param to increase search distance along line. Polyline is expanded into a polygon to cover the search distance.(blank)

Open Charge Map is a free, public database that grows with volunteer efforts contributions of the community.

If you’d like to contribute to this project you can do so by contacting them here.

or check out their funding page here.

Source of API: Open Charge Map

If you need a refresher on user defined functions lesson in Python here is a link to our Defining Functions Lesson.

You can see our lesson about try and except statements here.

## Chuck Norries Joke Database

ICNDB is a fun database full of Chuck Norris jokes. If you’re a fan, it’ll be a while before you run out of Chuck Norris jokes again.

According to ICNDB, The phrase ‘break a leg’ was originally coined by Chuck Norris’s co-stars in Walker, Texas Ranger as a good luck charm, indicating that a broken leg might be the worst extent of their injuries. This never proved to be the case.

Here is a simply code that uses requests and json libraries:

Below code will fetch a single random joke:

``````import requests
import json

def chuck():

f = r"http://api.icndb.com/jokes/random"
data = requests.get(f)
tt = json.loads(data.text)

print(tt["value"]["joke"])

chuck()``````

Below code will fetch 5 random jokes:

``````import requests
import json

def chuck():

f = r"http://api.icndb.com/jokes/random/5"
data = requests.get(f)
tt = json.loads(data.text)

print(tt["value"]["joke"])

chuck()``````

Source of API: The Internet Chuck Norris Database

If you need a refresher on user defined functions lesson in Python here is a link to our Defining Functions Lesson.

## Official Jokes Database

Official Joke API is a great source for fun and creative jokes. Here is a simply code that uses requests, json and webbrowser libraries:

``````import requests
import json

def jokes(f):

data = requests.get(f)
tt = json.loads(data.text)
return tt

f = r"https://official-joke-api.appspot.com/random_ten"
a = jokes(f)

for i in (a):
print(i["type"])
print(i["setup"])
print(i["punchline"], "\n")``````
• general
What did Michael Jackson name his denim store?
Billy Jeans!
• general
Who did the wizard marry?
His ghoul-friend
• general
What happens to a frog’s car when it breaks down?
It gets toad away
• general
What’s blue and not very heavy?
Light blue.
• general
Did you hear that David lost his ID in prague?
Now we just have to call him Dav.
• programming
Why do Java programmers wear glasses?
Because they don’t C#
• general
How did Darth Vader know what Luke was getting for Christmas?
He felt his presents.
• general
What do you call a dad that has fallen through the ice?
A Popsicle.
• general
How do you make holy water?
You boil the hell out of it.
• general
Which side of the chicken has more feathers?
The outside.

Here is the code for 1 random joke only:

``````import requests
import json

def jokes(f):

data = requests.get(f)
tt = json.loads(data.text)
return tt

f = r"https://official-joke-api.appspot.com/random_joke"
a = jokes(f)

for i in (a):
print(i["type"])
print(i["setup"])
print(i["punchline"], "\n")``````

general
What’s the best thing about elevator jokes?
They work on so many levels.

Finally, this api also works with joke categories, here are some of the categories you can try:

• general
• programming
• knock-knock
``````import requests
import json

def jokes(f):

data = requests.get(f)
tt = json.loads(data.text)
return tt

f = r"https://official-joke-api.appspot.com/jokes/programming/random"
a = jokes(f)

for i in (a):
print(i["type"])
print(i["setup"])
print(i["punchline"], "\n")``````

programming
A SQL query walks into a bar, walks up to two tables and asks…
‘Can I join you?’

Source of API: Official Joke API

If you need a refresher on user defined functions lesson in Python here is a link to our Defining Functions Lesson.

## The Cocktail Database

TheCocktailDB has a very impressive cocktail selection you can use for fun or commercial purposes. They offer abundance of information regarding different types of cocktails and you can filter cocktails based on, ingredient, name, type, glass type, alcoholic vs non-alcoholic, etc.

Their cocktail photos are also a delight to the eye. With the help of webbrowser library we can then open these links right from the python terminal.

Here is a simply code that uses requests, json and webbrowser libraries:

``````import requests
import json
import webbrowser
def cocktails():
f = r"https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita"
data = requests.get(f)
tt = json.loads(data.text)
#webbrowser.open(tt["url"])

for i in (tt["drinks"]):
print(i, "\n")
print(len(tt["drinks"]))
cocktails()
``````

Source: The Cocktail DB

Code below will print a bunch of other information regarding cocktails such as: Instructions and Ingredients and it will also open the cocktail image in a browser.

``````import requests
import json
import webbrowser
def cocktails():
f = r"https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita"
data = requests.get(f)
tt = json.loads(data.text)

for i in (tt["drinks"]):
print(i["strDrink"], "\n")
print(i["strInstructions"], "\n")
print(i["strInstructionsDE"], "\n")

print(i["strIngredient1"])
print(i["strIngredient2"])
print(i["strIngredient3"])
print(i["strIngredient4"])
url = i["strDrinkThumb"]
webbrowser.open(url)
cocktails()
``````

Source: The Cocktail DB

Code below will open all the cocktail images in your browser. Be careful as there might be too many images to open at once.

``````import requests
import json
import webbrowser
def cocktails():
f = r"https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=Gin"
data = requests.get(f)
tt = json.loads(data.text)
print(tt)

for i in (tt["drinks"]):
try:
url = i["strDrinkThumb"]
webbrowser.open(url)
print(i, "\n")
print(i["strDrink"], "\n")
except Exception:
pass
cocktails()
``````

TheCocktailDB is generous to allow access to their impressive cocktail database for educational and small scale personal use (via experimental API key: 1). For anything futher, you can support them through their Patreon Page here and get a legit API key.

For instance, if you’d like to create an app based on their Cocktail API, they got different options depending on the scale of your usage intention of their API.

Source of API: TheCocktailDB

If you need a refresher on user defined functions lesson in Python here is a link to our Defining Functions Lesson.

## Nasa - Space Image of the Day

Random.dog is a fun API that will show you random links of cute dog pictures and videos. They have a really fun selection of media. With the help of webbrowser library we can then open these links right from the python terminal.

Here is a simply code that uses requests, json and webbrowser libraries harmoniously.

Code below will turn up Nasa Astronomy pic; print its title and then open it in your browser.

``````import requests
import json
import webbrowser
def nasapic():

f = r"https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&count=1"
data = requests.get(f)
tt = json.loads(data.text)

print(tt[0]["title"])
webbrowser.open(tt[0]["url"])
nasapic()``````

Here is an example making use of params parameter in requests.get method.

By typing all the parameters inside a dictionary and calling it with params parameter makes everything more manageable and tidy.

``````import requests
import json
import webbrowser

def nasapic():

params = {"api_key": "DEMO_KEY", "hd": True, "count" : 1}
f = r"https://api.nasa.gov/planetary/apod?"
data = requests.get(f, params = params)
tt = json.loads(data.text)

print(tt[0]["title"])
webbrowser.open(tt[0]["url"])
nasapic()``````

If you need a refresher on user defined functions lesson in Python here is a link to our Defining Functions Lesson.

Source of API: Github.com/nasa/apod-api

You can find more NASA APIs here.

Source: Nasa

Nasa has a collection of very interesting deep space images and they are definitely worth exploring.

## UK Police Data

UK Police has a great API that’s full of crime and police information. You can filter the data based on regions, cities, neighborhoods, coordinates, officer names, crime category etc. inside the United Kingdom. With the help of webbrowser library we can then open these links right from the python terminal.

Here is a simply code that uses requests, json and webbrowser libraries harmoniously.

``````import webbrowser
import requests
import json

f = r'https://data.police.uk/api/forces'
j = r'https://data.police.uk/api/city-of-london/neighbourhoods'
data = requests.get(j)
a = data.text
a = json.loads(a)

for i in a: print(i)

f = r'https://data.police.uk/api/forces'
j = r'https://data.police.uk/api/city-of-london/neighbourhoods'
f2 = r"https://data.police.uk/api/crimes-street/all-crime?lat=53.414226&lng=-2.923026&date=2019-08"
data = requests.get(f2)
a = data.text
a = json.loads(a)
print(a)

for i in a:
print(i["outcome_status"])
print(i["category"])``````

If you need a refresher on user defined functions lesson in Python here is a link to our Defining Functions Lesson.

Source of API: UK Police Data

## Special Numbers

Numbersapi is a great API full of fun facts about numbers and dates. With the help of webbrowser library we can then open these links right from the python terminal.

Here is a simply code that uses requests, json and webbrowser libraries.

``````http://numbersapi.com

>>> f = r"http://numbersapi.com/42"
>>> data = requests.get(f)
>>> data.text

You can use random to get random results
Also you can use 4 categories (it will default to trivia if not mentioned)
>>> f = r"http://numbersapi.com/random?json"
>>> f = r"http://numbersapi.com/random/date?json"
>>> f = r"http://numbersapi.com/random/year?json"
>>> f = r"http://numbersapi.com/random/math?json"``````

If you need a refresher on user defined functions lesson in Python here is a link to our Defining Functions Lesson.

Source of API: NumbersAPI