Learning and practicing of any programming language can be monotonous. Also, only learning can not be the perfect gain of knowledge if we don’t put it into some implementation. Likewise, Python programming language can be interesting but until we don’t use it in some real-life problems. Moreover, doing some projects will ultimately help us to be innovative.
So, in this article, we will discuss five interesting Python projects for beginners. It sounds cool. Isn’t it? But before you go to this article please make sure that you have learned Python tutorial.
The following is the title of projects. Let’s get started.
Simple GUI Graphics
Basically, this is the easiest projects for the beginner with using Python GUI. Here we import the Python Turtle module. So, this module is nothing but like a robot that allow to easily draw intricate shapes and pictures all over the screen. Also, with the methods in turtle one can set the turtle’s position and heading, control its forward and backward movement, specify the type of pen it is holding, etc. Hence, the methods of turtle are mentioned below:
- turtle.reset(): Clears the drawing.
- turtle.color(): To set the colour of the turtle
- pendown(): Draws a line while moving the turtle.
- turtle.forward(): Moves the turtle forward by specified steps.
- turtle.left(): Takes some degrees which you want to rotate to the left.
- turtle.penup(): Does not draw the line while the turtle is moving.
- turtle.update(): Update the position of the turtle.
Here is the code to draw the pattern
import turtle as t
colors=["red", "blue", "yellow", "green", "purple", "orange"]
#t.reset()
t.tracer(0,0)
for i in range(45):
t.color(colors[i%6])
t.pendown()
t.forward(2+i*5)
t.left(45)
t.width(i)
t.penup()
t.update()
The output of this code is will show this screen.
GUI Calculator
Basically, a GUI calculator or graphical user calculator is a calculator which can be displayed on the screen. It is different from the normal calculator code that is used in Python because of its interactive screen. Therefore, it looks like an original calculator.
So, now before coming to the code you should study on layout management using Tkinter Python.
from tkinter import*
cal=Tk()
cal.geometry("410x460")
cal.title("CALCULATOR")
cal.title("CALCULATOR")
callabel = Label(cal,text="CALCULATOR",bg='white',font=("Times",20,'bold'))
callabel.pack(side=TOP)
cal.config(background='light blue')
textin=StringVar()
operator=""
def clickbut(number): #lambda:clickbut(1)
global operator
operator=operator+str(number)
textin.set(operator)
def equlbut():
global operator
addition=str(eval(operator))
textin.set(addition)
operator=''
def equlbut():
global operator
substraction=str(eval(operator))
textin.set(substraction)
operator=''
def equlbut():
global operator
multiplication=str(eval(operator))
textin.set(multiplication)
operator=''
def equlbut():
global operator
division=str(eval(operator))
textin.set(division)
operator=''
def clrbut():
textin.set('')
caltext=Entry(cal,font=("Calibri (Body)",12,'bold'),textvar=textin,width=25,bd=5,bg='light gray')
caltext.pack()
but1=Button(cal,padx=14,pady=14,bd=4,bg='light yellow',command=lambda:clickbut(1),text="1",font=("Calibri (Body)",16,'bold'))
but1.place(x=10,y=100)
but2=Button(cal,padx=14,pady=14,bd=4,bg='light yellow',command=lambda:clickbut(2),text="2",font=("Calibri (Body)",16,'bold'))
but2.place(x=10,y=170)
but3=Button(cal,padx=14,pady=14,bd=4,bg='light yellow',command=lambda:clickbut(3),text="3",font=("Calibri (Body)",16,'bold'))
but3.place(x=10,y=240)
but4=Button(cal,padx=14,pady=14,bd=4,bg='light yellow',command=lambda:clickbut(4),text="4",font=("Calibri (Body)",16,'bold'))
but4.place(x=75,y=100)
but5=Button(cal,padx=14,pady=14,bd=4,bg='light yellow',command=lambda:clickbut(5),text="5",font=("Calibri (Body)",16,'bold'))
but5.place(x=75,y=170)
but6=Button(cal,padx=14,pady=14,bd=4,bg='light yellow',command=lambda:clickbut(6),text="6",font=("Calibri (Body)",16,'bold'))
but6.place(x=75,y=240)
but7=Button(cal,padx=14,pady=14,bd=4,bg='light yellow',command=lambda:clickbut(7),text="7",font=("Calibri (Body)",16,'bold'))
but7.place(x=140,y=100)
but8=Button(cal,padx=14,pady=14,bd=4,bg='light yellow',command=lambda:clickbut(8),text="8",font=("Calibri (Body)",16,'bold'))
but8.place(x=140,y=170)
but9=Button(cal,padx=14,pady=14,bd=4,bg='light yellow',command=lambda:clickbut(9),text="9",font=("Calibri (Body)",16,'bold'))
but9.place(x=140,y=240)
but0=Button(cal,padx=14,pady=14,bd=4,bg='light yellow',command=lambda:clickbut(0),text="0",font=("Calibri (Body)",16,'bold'))
but0.place(x=10,y=310)
butdot=Button(cal,padx=47,pady=14,bd=4,bg='light yellow',command=lambda:clickbut("."),text=".",font=("Calibri (Body)",16,'bold'))
butdot.place(x=75,y=310)
butpl=Button(cal,padx=14,pady=14,bd=4,bg='light yellow',text="+",command=lambda:clickbut("+"),font=("Calibri (Body)",16,'bold'))
butpl.place(x=205,y=100)
butsub=Button(cal,padx=14,pady=14,bd=4,bg='light yellow',text="-",command=lambda:clickbut("-"),font=("Calibri (Body)",16,'bold'))
butsub.place(x=205,y=170)
butml=Button(cal,padx=14,pady=14,bd=4,bg='light yellow',text="*",command=lambda:clickbut("*"),font=("Calibri (Body)",16,'bold'))
butml.place(x=205,y=240)
butdiv=Button(cal,padx=14,pady=14,bd=4,bg='light yellow',text="/",command=lambda:clickbut("/"),font=("Calibri (Body)",16,'bold'))
butdiv.place(x=205,y=310)
butclear=Button(cal,padx=14,pady=119,bd=4,bg='light yellow',text="CE",command=clrbut,font=("Calibri (Body)",16,'bold'))
butclear.place(x=270,y=100)
butequal=Button(cal,padx=151,pady=14,bd=4,bg='light yellow',command=equlbut,text="=",font=("Calibri (Body)",16,'bold'))
butequal.place(x=10,y=380)
cal.mainloop()
So, here is the GUI calculator. It is shown like.
GUI Pygame
Here we come to an interesting GUI application in Python using pygame. Basically, pygame is a python module and after imported it into our python code we can make a number of games from it. In the following, it is one of the famous Python game Sudoku maker. So, before importing pygame, you have to install it inside the conda libraries. So, the steps are here(for windows 7 onwards).
- Firstly, open the anaconda prompt from the search bar. You will see a window like this.
2. Then you type
pip install pygame
You will see that it is installed.
3. After that you can import the pygame module in your code without showing any error.
4. The modules need to install are
import pygame
import time
Basically, you can make your own Sudoku game by applying logic. Now, here is the detail of the code:
import pygame
import time
pygame.font.init()
class Sudoku:
board = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7]
]
def __init__(self, rows, cols, width, height, win):
self.rows = rows
self.cols = cols
self.cubes = [[Cube(self.board[i][j], i, j, width, height) for j in range(cols)] for i in range(rows)]
self.width = width
self.height = height
self.model = None
self.update_model()
self.selected = None
self.win = win
def update_model(self):
self.model = [[self.cubes[i][j].value for j in range(self.cols)] for i in range(self.rows)]
def place(self, val):
row, col = self.selected
if self.cubes[row][col].value == 0:
self.cubes[row][col].set(val)
self.update_model()
if valid(self.model, val, (row,col)) and self.solve():
return True
else:
self.cubes[row][col].set(0)
self.cubes[row][col].set_temp(0)
self.update_model()
return False
def sketch(self, val):
row, col = self.selected
self.cubes[row][col].set_temp(val)
def draw(self):
# Draw Grid Lines
gap = self.width / 9
for i in range(self.rows+1):
if i % 3 == 0 and i != 0:
thick = 4
else:
thick = 1
pygame.draw.line(self.win, (0,0,0), (0, i*gap), (self.width, i*gap), thick)
pygame.draw.line(self.win, (0, 0, 0), (i * gap, 0), (i * gap, self.height), thick)
# Draw Cubes
for i in range(self.rows):
for j in range(self.cols):
self.cubes[i][j].draw(self.win)
def select(self, row, col):
# Reset all other
for i in range(self.rows):
for j in range(self.cols):
self.cubes[i][j].selected = False
self.cubes[row][col].selected = True
self.selected = (row, col)
def clear(self):
row, col = self.selected
if self.cubes[row][col].value == 0:
self.cubes[row][col].set_temp(0)
def click(self, pos):
"""
:param: pos
:return: (row, col)
"""
if pos[0] < self.width and pos[1] < self.height:
gap = self.width / 9
x = pos[0] // gap
y = pos[1] // gap
return (int(y),int(x))
else:
return None
def is_finished(self):
for i in range(self.rows):
for j in range(self.cols):
if self.cubes[i][j].value == 0:
return False
return True
def solve(self):
find = find_empty(self.model)
if not find:
return True
else:
row, col = find
for i in range(1, 10):
if valid(self.model, i, (row, col)):
self.model[row][col] = i
if self.solve():
return True
self.model[row][col] = 0
return False
def solve_gui(self):
find = find_empty(self.model)
if not find:
return True
else:
row, col = find
for i in range(1, 10):
if valid(self.model, i, (row, col)):
self.model[row][col] = i
self.cubes[row][col].set(i)
self.cubes[row][col].draw_change(self.win, True)
self.update_model()
pygame.display.update()
pygame.time.delay(100)
if self.solve_gui():
return True
self.model[row][col] = 0
self.cubes[row][col].set(0)
self.update_model()
self.cubes[row][col].draw_change(self.win, False)
pygame.display.update()
pygame.time.delay(100)
return False
class Cube:
rows = 9
cols = 9
def __init__(self, value, row, col, width, height):
self.value = value
self.temp = 0
self.row = row
self.col = col
self.width = width
self.height = height
self.selected = False
def draw(self, win):
fnt = pygame.font.SysFont("comicsans", 40)
gap = self.width / 9
x = self.col * gap
y = self.row * gap
if self.temp != 0 and self.value == 0:
text = fnt.render(str(self.temp), 1, (128,128,128))
win.blit(text, (x+5, y+5))
elif not(self.value == 0):
text = fnt.render(str(self.value), 1, (0, 0, 0))
win.blit(text, (x + (gap/2 - text.get_width()/2), y + (gap/2 - text.get_height()/2)))
if self.selected:
pygame.draw.rect(win, (255,0,0), (x,y, gap ,gap), 3)
def draw_change(self, win, g=True):
fnt = pygame.font.SysFont("comicsans", 40)
gap = self.width / 9
x = self.col * gap
y = self.row * gap
pygame.draw.rect(win, (255, 255, 255), (x, y, gap, gap), 0)
text = fnt.render(str(self.value), 1, (0, 0, 0))
win.blit(text, (x + (gap / 2 - text.get_width() / 2), y + (gap / 2 - text.get_height() / 2)))
if g:
pygame.draw.rect(win, (0, 255, 0), (x, y, gap, gap), 3)
else:
pygame.draw.rect(win, (255, 0, 0), (x, y, gap, gap), 3)
def set(self, val):
self.value = val
def set_temp(self, val):
self.temp = val
def find_empty(bo):
for i in range(len(bo)):
for j in range(len(bo[0])):
if bo[i][j] == 0:
return (i, j) # row, col
return None
def valid(bo, num, pos):
# Check row
for i in range(len(bo[0])):
if bo[pos[0]][i] == num and pos[1] != i:
return False
# Check column
for i in range(len(bo)):
if bo[i][pos[1]] == num and pos[0] != i:
return False
# Check box
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y*3, box_y*3 + 3):
for j in range(box_x * 3, box_x*3 + 3):
if bo[i][j] == num and (i,j) != pos:
return False
return True
def redraw_window(win, board, time, strikes):
win.fill((255,255,255))
# Draw time
fnt = pygame.font.SysFont("comicsans", 40)
text = fnt.render("Time: " + format_time(time), 1, (0,0,0))
win.blit(text, (540 - 160, 560))
# Draw Strikes
text = fnt.render("X " * strikes, 1, (255, 0, 0))
win.blit(text, (20, 560))
# Draw grid and board
board.draw()
def format_time(secs):
sec = secs%60
minute = secs//60
hour = minute//60
mat = " " + str(minute) + ":" + str(sec)
return mat
def main():
win = pygame.display.set_mode((540,600))
pygame.display.set_caption("Sudoku")
board = Sudoku(9, 9, 540, 540, win)
key = None
run = True
start = time.time()
strikes = 0
while run:
play_time = round(time.time() - start)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
key = 1
if event.key == pygame.K_2:
key = 2
if event.key == pygame.K_3:
key = 3
if event.key == pygame.K_4:
key = 4
if event.key == pygame.K_5:
key = 5
if event.key == pygame.K_6:
key = 6
if event.key == pygame.K_7:
key = 7
if event.key == pygame.K_8:
key = 8
if event.key == pygame.K_9:
key = 9
if event.key == pygame.K_DELETE:
board.clear()
key = None
if event.key == pygame.K_SPACE:
board.solve_gui()
if event.key == pygame.K_RETURN:
i, j = board.selected
if board.cubes[i][j].temp != 0:
if board.place(board.cubes[i][j].temp):
print("Success")
else:
print("Wrong")
strikes += 1
key = None
if board.is_finished():
print("Game over")
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
clicked = board.click(pos)
if clicked:
board.select(clicked[0], clicked[1])
key = None
if board.selected and key != None:
board.sketch(key)
redraw_window(win, board, play_time, strikes)
pygame.display.update()
main()
pygame.quit()
Now, coming to the code analysis part:
- Firstly, the functions used here are:
- init: To input row, column, height, width etc.
- update_model: To update row and column
- place: To place the value of row and column
- sketch
- draw
- select
- clear
- click
- is_finished
- solved
- slove_gui
- draw_change
- set
- set_temp
- find_empty
- valid
- redraw_window
- format_time
- play_time
- Then, the classes are
- Sudoku and
- Cube
Now you can see a new GUI window named Sudoku is visible. In that you can solve the puzzle by typing the number in each blank space and entering it. In addition there, you can see a timer and after each wrong attempt a wrong statement will appear in the console. Likewise, for each right attempt, a right statement will be there. Finally, to solve the puzzle just press spacebar and the Sudoku will auto-fill. The most beautiful thing is that here we use the backtracking approach to auto-fill the sudoku. Backtracking is one of the most popular technique to calculate in the algorithm.
Now, here you can see the video for better understanding.
Mail Sender using Python
Firstly, this project is all about to send a mail from the Python code. After that, we will see that the mail is sent to the recipient. Before coming to the code part we will have to change the mail settings which is given below in some easy steps:
- Firstly, open your mail account setting and then open the security tab.
2. Then, you can find the less secure app access and you make it on.
Now, its all done. We can start coding. The steps to follow to make the code are:
- import smtplib: This library is already installed when you install the Python.
- smtp takes two arguments one is server URL “smtp.gmail.com” and the second argument is port number. The port number is “587” for Gmail.
- starttls() takes the insecure connection and upgrade it to SSL connection.
- mime (Multipurpose Internet Mail Extension) library should be preinstalled. We can install it by typing
pip install email_to
5. The used module are: smtplib, MIMEText and MIMEMultiport
Now, the below below will understand you better.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
server=smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
userofemail='username@gmail.com'
mailpassword='password'
recipientmail='username@gmail.com'
server.login(userofemail,mailpassword)
message=MIMEMultipart()
message["From"]=userofemail
message["To"]=userofemail
message["Subject"]="HAPPY CODING"
message=MIMEText("Hi, this mail is sent from python")
server.sendmail(userofemail,userofemail,message.as_string())
server.quit()
Here, you can see the output like this:
Text extraction from image
Basically, this is a project in which you will write a code for the text extraction from an image. So, before we go into the code analysis part we have to know how an image is extracted using Python code.
Firstly, text extraction is done from an image with image processing. It is called Optical Character Recognition(OCR). In python, the popular character recognition engine is there which is a tesseract. Therefore, in order to install tesseract, you need to follow the step.
- Open the anaconda prompt and then type
pip install tesseract
Now, you can import tesseract in your code.
So, after importing tesseract you need to install the Python Image Library (PIL) to import an image on the code. Hence, to install PIL you need to type
pip install pillow
Now, you can import image from the PIL library
After that, we need to convert the image to text using the method
pytesseract.image_to_string(image)
Here we will get into the code:
import pytesseract
from PIL import Image
image=Image.open('path of the image with extension')
text1=pytesseract.image_to_string(image)
print(text1)
Here is our image:
N.B: The image should not be blur, have any rotation or a background or in other words it should be a clear image. The following is our extracted text: