Archive
Python project: Drawing with Python – Flower
Python: Draw Flower
Drawing with Python
In this post i tried to draw another flower using arcs of circles, i get a simple one and i guess with more sizes we can do more complex shape.
You can play with the code and change the numbers, size and rotation degree and let’s see what we will have.
t = turtle.Turtle()
t.hideturtle()
t.pendown()
for x in range (30):
t.circle(60,70)
if x %3==0:
t.circle (10,90)

Python Project: Binary Search
Python: Binary Search
Binary Search
Definition:
Binary Search is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array.
In this code we are writing a Python code to find the target in a sorted given array and get its position without using any python math packages.
The case: We have an Array (arr=[2,3,5,6,8,10,11,13,15,16,19]) our target is 13, so we want the position of 13.
We are setting the first position as (pos_s=0) and the end position as (pos_e= the length of the array -1) and we will use recursive function.
Recursive Function: is a computer function or procedure that calling it self
The Code:
arr=[2,3,5,6,8,10,11,13,15,16,19]
target=11
pos_s =0
pos_e=int(len(arr)-1)
midarr =0
def bsearch(arr,target,pos_s,pos_e):
midarr=(pos_s+pos_e)/2
if arr[midarr] < target:
pos_s = midarr +1
bsearch(arr,target,pos_s,pos_e)
elif arr[midarr] > target:
pos_e = midarr -1
bsearch(arr,target,pos_s,pos_e)
elif arr[midarr] == target:
print(‘The target was: ‘,target, ‘ The key of our target is: ‘,midarr)
return
print(arr)
# Call the functin
bsearch(arr,target,pos_s,pos_e)
Python Project: Armstrong Numbers
Python: Armstrong Numbers
Check for Armstrong number in a range
In our last post (‘Check if a Number is Armstrong‘) we wrote a codes to check a given number and see whether it is an Armstrong or Not.
Today, we want to go through a set of numbers and see how many Armstrong numbers are there.
Before calling the ‘armstrong_in_range()’ and just to keep the code as less as we can, I assume the two numbers has the same number of digits, also I am getting the power (p) and the range numbers (n1, n2) out-side of this function and passing all as variables.
def armstrong_in_range(p,n1,n2):
my_sum = 0
count = 0
for num in range (n1,n2):
tot=num
for arm in range(p):
my_sum = my_sum + ((num % 10)**p)
num = num // 10
if my_sum == tot:
print(‘\nThe number {} is Armstrong.’.format(tot))
my_sum=0
count = count +1
else:
my_sum=0
print(‘\nWe have {} armstrong number(s)’.format(count))
Python Project: IF N an Armstrong
Python: Armstrong Numbers
Check if a Number is Armstrong
In late nineties, I was programming using Pascal Language and I was very passionate to convert some mathematical syntax into codes to fine the result, although some of them were very easy; but the goal was to write the codes.
Today, we are attempted to write a code in Python to check whether a number is an Armstrong or Not. First let’s ask:what is Armstrong number?Answer: If we assume we have a number (num = 371), 371 is an Armstrong because the sum of each digits to the power of (number of the digits) will be the same. That’s mean 371 is a three digits so the power (p=3) so:
3**3 = 27
7**3 = 343
1**3 = 1
then (27+343+1) = 371. … So 371 is an Armstrong Number.
In wikipedia:
Armstrong also known as a pluperfect digital invariant (PPDI) or the Narcissistic number is a number that: the sum of its own digits each raised to the power of the number of digits equal to the number its self.
# Function to check whether a number is Armstrong or Not.
def is_it_armstrong(num):
p= len(str(num)) # First: we get the power of the number
my_sum=0
tot=num
for x in range (p) :
my_sum=my_sum+((num%10)**p)
num=num//10
if my_sum == tot:
print(‘\nThe number {} is Armstrong.’.format(tot))
else :
print(‘\nThe number {} is NOT Armstrong.’.format(tot))
Python Project: Drawing with Python – Flower 2
Python: Draw Flower
Drawing with Python
In a previous post, we use the t.forward(size) & t.left(x) to draw something looks-like flower petal. That post (See it Here) is drawing (8) petals facing left side to complete a flower shape… So can we improve it? Can we make it looks better?..
OK, I work on it and divide the code into two functions, one will draw a petal facing left side and another to draw a petal facing right side, each petals will be close to each other and touching or almost touching each’s head. Bellow I am posting the codes, and an image for the result.
You can play with the code and change the numbers, size and rotation degree and let’s see what we will have.
#To draw a flower using turtel and circle function
import turtle
# Here is some setting for the turtel
t = turtle.Turtle()
t.color(‘black’)
t.hideturtle()
t.speed(9)
t.left(0)
t.penup
size=10
#Draw petal facing left side
def petal_l():
t.pendown()
for x in range (40):
t.forward(size)
t.left(x)
t.penup()
#Draw petal facing right side
def petal_r():
t.pendown()
for x in range (40):
t.forward(size)
t.right(x)
t.penup()
left_d=-15
# To draw 5 petals
for pet in range (5):
petal_l ()
t.goto(0,0)
t.left(50)
petal_r ()
t.goto(0,0)
t.left(22)
t.penup
The Code:![]() |
The Result![]() |
Python Drawing flower
Python: Draw Flower
Drawing with Python
In this post I am using some codes to draw mathematical shapes that looks like flower.
To do this we need to import turtle library, then using circle function to complete our work. You may play around with the numbers and figure out what will happen.
#python #code
import turtle
t = turtle.Turtle()
t.hideturtle()
t.pendown()
for x in range (30):
t.circle(60,70)
if x % 2 == 0:
t.circle(10,70)
Python : Expenditure App
Expenditure Application
Add new Entry
Today we will work on the “Add New Entry” function, this is first function on our menu. (Read Expenditure App Menu here)
We will call the function def add_entry(): and will give the user the prompt to enter “Date” and “Amount” then we will write them to our json file.
Just to be as less codes as we can, I am not adding any validations here also not coding the try .. except. So I am assuming the entered data will be in correct way.
def add_entry():
my_date = input(‘Enter the date as dd/mm/yyyy: ‘)
my_amount = input(‘Enter the Amount: ‘)
new_data = {“date”: my_date, “amount”: int(my_amount)}
# Here we adding the new data to the file
ff = open(“expen_dat.json”, “a”)
ff.seek(0, 2) # goto the end of the file.
ff.truncate(ff.tell() – 3) # from end of the file erase last 3 char.
ff.write(‘,\n’)
ff.write(json.dumps(new_data))
ff.write(‘\n]}’)
ff.close()
If you add the “User input choice” in your code this function will be on choice “1” as here.
if choice == ‘1’:add_entry()
choice = the_menu()
if choice == ‘2’:
….
Follow me on Twitter..
Table of posts regarding the Expenditure App..
| Title | Description | Post Link |
| The Case | Talking about the case study of the application | Click to Read |
| leveling the Ground | Talking about: Requirement, folder structure, data file json, sample data and .py file and other assumptions | Click to Read |
| The Menu | Talking about: The application menu function | Click to Read |
| User input ‘choice’: | Talking about: The user input and the if statement to run the desired function | Click to Read |
| Loading and testing the Data | Talking about: Loading the data from json file and print it on the screen. | Click to Read |
| Add New Entry | Talking about: The “Add New Entry” function | |
Here is the code shot..
|
Here is the output screen..
|
Python Project: Drawing with Python – Flower 1
Python: Draw Flower
Drawing with Python
One of my favorite areas is drawing, and when its come to programming languages, one of the first thing i look after is the commands that let me draw lines and shapes.
In python, we have to import a library to help us in this task, here in this short code block I am using codes to draw a flower shape. We can improve the idea later but i want the first version to be as simple as i can. So lets see the code.
# We have to import this library
import turtle
# Here are some setting
t = turtle.Turtle()
t.shape(“point”)
t.color(‘black’)
t.speed(9)
t.left(0)
t.penup
size=10
#This function to draw one petal
def petal():
t.pendown()
for x in range (40):
t.forward(size)
t.left(x)
t.penup()
left_d=-15
for pet in range (8):
petal()
t.goto(0,0)
t.left(-15)
———————————————–
Python : Expenditure App
Expenditure Application
Loading and testing the Data:
In this post we will load the data from json file and print it to the screen, also will use one of our functions called “get_year_total” to get the sum amount in a given year.
First we assume the our file.json is there in the same directory of the Expenditure.py file (read previous post here) so our code will upload the data in a variable named “data” and we will print the file to our screen, this line of code (print to screen) is there in our coding process and should be removed from the last version of our application.
# This function will load the json file data into var data and return it back so we can use it
def get_all():
with open(‘expen_data.json’) as f:
data = json.load(f)
return data
# This function will take a year from the user input and return the total of amount we expend in that year.
def get_year_total(my_year):
tot=0
for my_date in data[‘expenditure’]:
if my_year in my_date[‘date’]:
tot=tot+int(my_date[‘amount’])
return tot
data = get_all() # Load the file in to data
print(data)
# Ask the user to Enter a year.
my_year=input(‘Enter a year as yyyy: ‘)
# pass the year to the get_year_total function
total=get_year_total(my_year)
# print the total
print(total)
If every thing goes fine, you should see the data on your screen and a prompt will ask you to enter a year, at this point we are not doing any try … except block to our code so we assume that we are entering a good/right inputs. I am attaching images for the code and output screens.
Table of posts regarding the Expenditure App..
| Title | Description | Post Link |
| The Case | Talking about the case study of the application | Click to Read |
| leveling the Ground | Talking about: Requirement, folder structure, data file json, sample data and .py file and other assumptions | Click to Read |
| The Menu | Talking about: The application menu function | Click to Read |
| User input ‘choice’: | Talking about: The user input and the if statement to run the desired function | Click to Read |
Here is the code shot..
|
Here is the output screen..
|
Python code: Date Validation
Python: Date Validation
As in any application there is lots of functions and procedures helping the application, some of these functions are directly related to the menu bar other are there just to work on back ground to perform a task and return something that another function need to complete an action.
Here is a python code to ask the user to input a date and check if the date is in the format we want to be.
I am new in python so maybe there is a code or a function to perform this, so if any one can help in this.
#python code: Date Validation
def valid_date():
my_date=input(‘Enter the date as dd/mm/yyyy :’)
try:
d,m,y=(my_date.split(‘/’))
if len(d)==1: d=’0’+d
if len(m)==1: m=’0’+m
if len(y)==2: y=’20’+y
if int(d)>31: print(‘Day must be less then 31’), brake
if int(m)>12: print(‘Mounth must be less then 12’), brake
my_date=d+’/’+m+’/’+y
return my_date
except:
print(‘Enter a valid date.’)
return ‘false’
vd=valid_date()
if vd == ‘false’ : valid_date()
else:
print(‘OK’, vd)














