# How to Draw Rectangles and Squares Using Python Turtle

Python’s turtle package can be used to draw various shapes on a canvas. Turtle allows the programmer to move a pen in a specified direction by specifying its heading and distance. Turtle has no built-in primitive for drawing a rectangle or square. However it is easy to create a function to draw a rectangle(or square) in turtle.

The following python program defines a custom function for drawing rectangles using turtle. Note that the centre of the turtle canvas is at 0,0. Hence if you draw just a dot at (0,0) it will be at the centre of the drawing canvas. The function draw_rectangle() requires the co-ordinates of the top left of the rectangle. You also need to specify width, height, thickness and color of the rectangle.

The following example draws a blue rectangle which is 200 pixels in width and 100 pixels in height. We have specified the top left of the rectangle as (-100,50) to position the rectangle at the centre of the canvas. The rectangle drawn has a thickness of 5 pixels.

```import turtle
turtle.setup(500,500)
board = turtle.Turtle()

# draws a rectangle given top left position of a rectangle
def draw_rectangle(board,x,y,width,height,size,color):
board.pencolor(color)
board.pensize(size)

board.up()
board.goto(x,y)
board.down()
# draw top
board.forward(width)
# draw right
board.right(90)
board.forward(height)
# draw bottom
board.right(90)
board.forward(width)
# draw left
board.right(90)
board.forward(height)
board.end_fill()

# in turtle, the centre of the canvas is 0,0
# hence we position the rectangle in the center
# note that we need to pass the top left co-ordinates of rectangle
# draws rectangle with 200 pixels in width and 100 pixels in height
draw_rectangle(board,-100,50,200,100,5,"blue")
turtle.done()
```

The following the sample output from the program, Following python program is a different version which also allows us to specify a fill color for the rectangle. The example is identical to the previous one except that we use a different color to fill the rectangle.

```import turtle
turtle.setup(500,500)
board = turtle.Turtle()

# draws a rectangle given top left position of a rectangle
def draw_filled_rectangle(board,x,y,width,height,size,color,fill):
board.fillcolor(fill)
board.pencolor(color)
board.pensize(size)

board.begin_fill()
board.up()
board.goto(x,y)
board.down()
# draw top
board.forward(width)
# draw right
board.right(90)
board.forward(height)
# draw bottom
board.right(90)
board.forward(width)
# draw left
board.right(90)
board.forward(height)
board.end_fill()

# in turtle, the centre of the canvas is 0,0
# hence we position the rectangle in the center
# note that we need to pass the top left co-ordinates of rectangle
# draws rectangle with 200 pixels in width and 100 pixels in height
# also specifies the rectangle color and the fill color
draw_filled_rectangle(board,-100,50,200,100,5,"blue","green")
turtle.done()
```

The following the sample output from the program showing a filled rectangle, The following program uses looping to draw a two dimensional matrix of identical black squares. Note that we are using black as fill color and white as the stroke color for the rectangles.

```import turtle
turtle.setup(500,500)
board = turtle.Turtle()

# draws a rectangle given top left position of a rectangle
def draw_filled_rectangle(board,x,y,width,height,size,color,fill):
board.fillcolor(fill)
board.pencolor(color)
board.pensize(size)

board.begin_fill()
board.up()
board.goto(x,y)
board.down()
# draw top
board.forward(width)
# draw right
board.right(90)
board.forward(height)
# draw bottom
board.right(90)
board.forward(width)
# draw left
board.right(90)
board.forward(height)
board.end_fill()

# draw a 7x7 matrix of black squares
for x in range(1,8):
for y in range(1,8):
draw_filled_rectangle(board,-200+x*20,y*20,20,20,2,"white","black")

turtle.done()
```

The following the sample output of 7×7 matrix of black squares from the python turtle program, # How to Draw Circles Using Python Turtle

Python contains an interesting drawing module called Turtle. This module is available as part of the standard python distribution. Turtle consists of a number of graphics operations modelled after pen drawing. In this article I will show you how we can use the turtle commands to draw circle based shapes.

## How to Draw a Simple Circle Using Python Turtle

The following python script creates a simple circle with default color at the center of the turtle canvas. We have defined the turtle canvas with a width of 800 pixels and a height of 600 pixels. We then draw a circle of radius 100 pixels in the middle of the canvas. Note that the bottom of the circle is placed in the middle of the canvas.

```import turtle

turtle.setup(800,600)
board = turtle.Turtle()

board.penup()
board.setpos(0,0)
board.pendown()
board.circle(100)

turtle.done()
```

## How to Draw a Face Using Python Turtle

The following python script draws the shape of a face using the turtle commands. We have organized the code in functions so that each section of the drawing is separate. Note that we are resetting the direction of the pen after drawing part of a circle in the draw_lip functions.

```import turtle
turtle.setup(800,600)
board = turtle.Turtle()

def draw_face():
board.penup()
board.setpos(0,0)
board.pendown()
board.circle(100)

def draw_left_eye():
board.penup()
board.setpos(-50,100)
board.pendown()
board.circle(25)

def draw_right_eye():
board.penup()
board.setpos(50,100)
board.pendown()
board.circle(25)

def draw_right_lip():
board.penup()
board.setpos(0,25)
board.pendown()
board.circle(100,45)

def draw_left_lip():
board.penup()
board.setpos(0,25)
board.pendown()
board.circle(100,-45)

draw_face()
draw_left_eye()
draw_right_eye()
draw_left_lip()
draw_right_lip()

board.penup()
board.setpos(400,400)
turtle.done()
```

## How to Draw Tangent Circles Using Python Turtle

The following python program creates tangent circles at the middle of the canvas. We use a loop to generate the circles and for each iteration we just change the radius of the circle.

```import turtle
turtle.setup(800,600)
board = turtle.Turtle()

for i in range(1,20):
board.circle(i*10)

turtle.done()
```

## How to Draw Concentric Circles Using Python Turtle

The following python program creates concentric circles at the middle of the canvas. We use a loop to generate the circles and for each iteration we change the y location and the radius of the circle.

```import turtle
turtle.setup(800,600)
board = turtle.Turtle()

for i in range(1,20):
board.circle(i*10)
board.penup()
board.sety(-i*10)
board.pendown()

turtle.done()
```

## How to Draw Olympics Logo Using Python Turtle

The following python program creates the olympics logo using the the turtle package. It also demonstrates the use of pen color and pen size in drawing shapes.

```import turtle
turtle.setup(800,600)
board = turtle.Turtle()

circle_positions = [(-120,0,"blue"), (0,0,"black"), (120,0,"red"),
(-60,-60,"yellow"), (60,-60,"green")]

for pos in circle_positions:
board.penup()
board.setpos(pos,pos)
board.pencolor(pos)
board.pensize(5)
board.pendown()
board.circle(50)

turtle.done()
```

# How to Create Canvas Animation Using Tkinter

Tkinter is one of the most popular GUI toolkits available for python. It is available as part of the standard python installation. Hence you can use this package without installing any additional modules. Tkinter is a powerful GUI library and you can use it to build full fledged user interfaces or build simple desktop games.

This article contains a step by step guide on building an animation using the python tkinter package. We will be using canvas object of the tkinter package to draw our animation. Note that the following program requires python 3.6 or above.

The following python program creates a simple animation showing the movement of a ball across the screen. Following are the steps in the program,

• Create and display main window of the application
• Create and attach the canvas to the main window. We will be drawing to this canvas
• Draw and animate a circle (our ball) inside the canvas

Let us start by importing tkinter and time modules. We will use time module to introduce a delay for drawing successive screens of the animation,

```import tkinter
import time
```

Let us now create a set of variables for our animation demo. This defines the size of our gaming canvas, speed of the ball, size of the ball and where we want our ball to start moving from.

```# width of the animation window
animation_window_width=800
# height of the animation window
animation_window_height=600
# initial x position of the ball
animation_ball_start_xpos = 50
# initial y position of the ball
animation_ball_start_ypos = 50
# the pixel movement of ball for each iteration
animation_ball_min_movement = 5
# delay between successive frames in seconds
animation_refresh_seconds = 0.01
```

The following function creates the application window with the specified title and dimensions,

```# The main window of the animation
def create_animation_window():
window = tkinter.Tk()
window.title("Tkinter Animation Demo")
# Uses python 3.6+ string interpolation
window.geometry(f'{animation_window_width}x{animation_window_height}')
return window
```

We then create a function to create the animation canvas and attach it to the main window,

```# Create a canvas for animation and add it to main window
def create_animation_canvas(window):
canvas = tkinter.Canvas(window)
canvas.configure(bg="black")
canvas.pack(fill="both", expand=True)
return canvas
```

Let us now create a function to create and animate a circle in an infinite loop. We use the create_oval method to create a circle(ball) with specified radius and draw it on canvas. We move the ball until it reaches a boundary and then we reverse the direction of the ball. Note the use of move method of canvas which lets us move a drawing in the canvas to another location. Also note the use of python array unpacking to get the location of the ball.

```# Create and animate ball in an infinite loop
def animate_ball(window, canvas,xinc,yinc):
fill="blue", outline="white", width=4)
while True:
canvas.move(ball,xinc,yinc)
window.update()
time.sleep(animation_refresh_seconds)
ball_pos = canvas.coords(ball)
# unpack array to variables
xl,yl,xr,yr = ball_pos
if xl < abs(xinc) or xr > animation_window_width-abs(xinc):
xinc = -xinc
if yl < abs(yinc) or yr > animation_window_height-abs(yinc):
yinc = -yinc
```

Finally let us call all the functions in order to run our animation,

```# The actual execution starts here
animation_window = create_animation_window()
animation_canvas = create_animation_canvas(animation_window)
animate_ball(animation_window,animation_canvas, animation_ball_min_movement, animation_ball_min_movement)
```

Full code of the python animation demo using tkinter is given below. This can be easily extended to a bat and ball game if you know event handling in tkinter. Save the following code in “tkinter-draw-demo.py” file and then run the command “python3 tkinter-draw-demo.py” to see the animation.

```import tkinter
import time

# width of the animation window
animation_window_width=800
# height of the animation window
animation_window_height=600
# initial x position of the ball
animation_ball_start_xpos = 50
# initial y position of the ball
animation_ball_start_ypos = 50
# the pixel movement of ball for each iteration
animation_ball_min_movement = 5
# delay between successive frames in seconds
animation_refresh_seconds = 0.01

# The main window of the animation
def create_animation_window():
window = tkinter.Tk()
window.title("Tkinter Animation Demo")
# Uses python 3.6+ string interpolation
window.geometry(f'{animation_window_width}x{animation_window_height}')
return window

# Create a canvas for animation and add it to main window
def create_animation_canvas(window):
canvas = tkinter.Canvas(window)
canvas.configure(bg="black")
canvas.pack(fill="both", expand=True)
return canvas

# Create and animate ball in an infinite loop
def animate_ball(window, canvas,xinc,yinc):
fill="blue", outline="white", width=4)
while True:
canvas.move(ball,xinc,yinc)
window.update()
time.sleep(animation_refresh_seconds)
ball_pos = canvas.coords(ball)
# unpack array to variables
xl,yl,xr,yr = ball_pos
if xl < abs(xinc) or xr > animation_window_width-abs(xinc):
xinc = -xinc
if yl < abs(yinc) or yr > animation_window_height-abs(yinc):
yinc = -yinc

# The actual execution starts here
animation_window = create_animation_window()
animation_canvas = create_animation_canvas(animation_window)
animate_ball(animation_window,animation_canvas, animation_ball_min_movement, animation_ball_min_movement)
```

Python has a very powerful library called requests for initiating http requests programmatically. You can use requests for downloading files hosted over http protocol. Run the following command to install requests python library. This assumes that you already have python 3 installed on your system.

pip3 install requests

You may need to prefix the above command with sudo if you get permission error in your linux system.

The following python 3 program downloads a given url to a local file. The following example assumes that the url contains the name of the file at the end and uses it as the name for the locally saved file.

```import requests

# assumes that the last segment after the / represents the file name
# if the url is http://abc.com/xyz/file.txt, the file name will be file.txt
file_name_start_pos = url.rfind("/") + 1
file_name = url[file_name_start_pos:]

r = requests.get(url, stream=True)
if r.status_code == requests.codes.ok:
with open(file_name, 'wb') as f:
for data in r:
f.write(data)

# the file name at the end is used as the local file name
```

After running the above program, you will find a file named “posts” in the same folder where you have the script saved.

The following python 3 program downloads a list of urls to a list of local files. However the download may take sometime since it is executed sequentially.

```import requests

# assumes that the last segment after the / represents the file name
# if url is abc/xyz/file.txt, the file name will be file.txt
file_name_start_pos = url.rfind("/") + 1
file_name = url[file_name_start_pos:]

r = requests.get(url, stream=True)
if r.status_code == requests.codes.ok:
with open(file_name, 'wb') as f:
for data in r:
f.write(data)

# the file name at the end is used as the local file name
```

```import requests

# assumes that the last segment after the / represents the file name
# if url is abc/xyz/file.txt, the file name will be file.txt
file_name_start_pos = url.rfind("/") + 1
file_name = url[file_name_start_pos:]

r = requests.get(url, stream=True)
if r.status_code == requests.codes.ok:
with open(file_name, 'wb') as f:
for data in r:
f.write(data)
return url

urls = ["https://jsonplaceholder.typicode.com/posts",
"https://jsonplaceholder.typicode.com/photos",
"https://jsonplaceholder.typicode.com/todos",
"https://jsonplaceholder.typicode.com/albums"
]

# Run 5 multiple threads. Each call will take the next element in urls list
for r in results:
print(r)
```

# How to Run Like Queries in MongoDB

When working with textual data in mongodb, you may want to fetch documents with partial match on a field. You can use the \$regex operator in mongodb for running like queries. By default, the like query using \$regex is case sensitive.

Assume that you have collection in your mongodb containing names of the countries. A sample document from the countries collection is given below,

```{
"countryName" : "United States",
"isoCode" : "US",
"countryCode" : "1"
}
```

The following mongodb query fetches all documents where countryName contains “rab” anywhere. This query is the SQL equivalent of “%rab%”.

```db.getCollection('countries').find({'countryName': {'\$regex': 'rab'}})
```

The above query returns documents for “United Arab Emirates” and “Saudi Arabia”. But if you replace “rab” with “RAB”, not document is returned. For doing a case-insensitive search, you need to use the \$options for \$regex as given below.

```db.getCollection('countries').find({'countryName': {'\$regex': 'RAB', '\$options':'i'}})
```

The above query returns documents for “United Arab Emirates” and “Saudi Arabia” by doing a case-insensitive search.

Run the following query if you want to retrieve all the countries where the name starts with “In” by doing a case-insensitive search.

```db.getCollection('countries').find({'countryName': {'\$regex': '^In', '\$options':'i'}})
```

Run the following query to retrieve all the countries where the name ends with “tes” by doing a case-insensitive search.

```db.getCollection('countries').find({'countryName': {'\$regex': "tes\$"
, '\$options':'i'}})
```