Archive
Python Project: Is it a Prime
Python: Prime Number
Is it Prime
In a simple way, a Prime number is a number that cannot be made by multiplying other numbers. So 4 is Not Prime because we can say that 4 = 2 x 2, 6 is Not Prime because it can be produced by multiplying 3 x 2; but 5 Is Prime because we can’t find any integer numbers that can produce 5.
Numbers such as 1, 3, 5, 7, 11, 13 … all are Prime Numbers.
This function will ask the user to write a number then we will examine it to see whether it is a prime or not.
The Code:
num=int(input(“Enter a number: “))
def is_prime(num):
result=”Prime”
for t in range (2,num):
if num%t==0 :
result=”Not Prime”
break
return result
print num,’is’,is_prime(num)
Python Project: Pluralise a Word
Python: Pluralise a Word
Loop through a dictionary and pluralise a word
One of Python Exercises on @PyBites codechalleng is to loop through a given dictionary of people and the number of games they’ve won then print out the users name and how many games they’ve won in the following format: “sara has won n games” and pluralise the word game to suit the number of games won.
we assume the dictionary is games_won = dict={‘sara’:0, ‘bob’:1, ‘tim’:5, ‘julian’:3, ‘jim’:1}
The Code:
games_won ={‘sara’:0, ‘bob’:1, ‘tim’:5, ‘julian’:3, ‘jim’:1}
def print_game_stats(games_won):
for key,val in games_won.items():
print(“{} has won {}{p}”.format(key, val,p=” game” if val ==1 else ” games” ))
print_game_stats(games_won)
Python Project: Sum N Numbers
Python: Sum N Numbers
Bites of Python exercises
I found this Python Exercises on the at PyBites codechalleng and i love the idea of solving problems and this will let me learn more, so thanks guys @pybites.
So this time the challenge is to Write a function that can sum up N numbers. The function should receive a list of N numbers, If no argument is provided, return sum of numbers 1..100.
I hope i did this right, here is my function; the result seems to be fine i am still learning so … sorry if i misunderstood.
def sum_up(my_nums=range(1,100)):
total=0
print”The List of number/s “,my_nums
for x in range (len(my_nums)):
total=total+int(my_nums[x])
print”Total is:”,total
print(“This function will sum up a given list of numbers.\nWhen you finish typping the numbers just press “”Enter””\nIf you did not enter any numbers i will assume the list is [1,100]”)
#Get the list from the user
n=input(“Type the numbers:”)
#In case the user enter some spaces in his number, we should remove it
the_n=n.replace(” “, “”)
#Here we are calling the functin
sum_up() if the_n ==”” else sum_up(the_n)

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..
|












