Archive

Archive for the ‘Python’ Category

Python: Sorting Algorithm (3. Merge Sort)

June 3, 2021 3 comments

Learning : Python coding, Math, Algorithm,
Subject: Writing Merge Sorting Algorithm in Python

[NOTE: To keep the code as simple as we can, We WILL NOT ADD any user input Varevecations. Assuming that our user will Enter the right inputs.]

Sorting Algorithm is a way to sort a given list/Array of numbers, there are several sorting Algorithm as follow:
Type of Sorting Algorithm
1. Quick Sort. [Click Here]
2. Bubble Sort. [Click Here]
3. Merge Sort. [Click Here]
4. Insertion Sort. [Click Here]
5. Selection Sort. [Click Here]
6. Heap Sort. [Click Here]
7. Radix Sort. [Click Here]
8. Bucket Sort. [Click Here]

Here in this post we will write a function to take a given list and sort it then pass it back. We assume the user will enter a serial of numbers, that he want to sort, our function will sort it and print out the original numbers and the sorted one.

Merge Sort: Steps of Merge Sorting Algorithm are:

1. If the Array has 1 Element then return it.
2. If the givin Array has more than 1 Element then we Divide it into 2 Parts.
Left = from Element 0 T0 Element len(arr)//2
and Right = from Element len(arr)//2 To Element len(arr). And we keep repeating step 2 for each part.
3. Once we have All parts divided we tart merge them in a sorted order.

Coding: In this Post we will write the Function for Main-Mnu, another one to collect the Array [Not Sorted] Elements from the user, then we will write the Main Function, here we will have One to Divide the Array into parts and One to Merge the Element together again. And as we done with Quick & Bubble Sort projects we will have one Fast-Run Function and another one with Details Step-By-Step run to show the Algorithm.

NOTE: All the Code will be Available in the Download Page.

Let’s start with the Main-menu to list down three option were the user will select one among them, the menu options are: 1. Merge Sort Algorithm – Fast Run. & 2. Merge Sort Algorithm – Step By Step and the last one is 3. Exit.
Here is the code.

python code project main menu by Ali Radwani merge sort Algorithm

I will Not post the code for collecting the Array Element from the user [Find it in the .py file for this project]. Here is the code for merge_sort_divider Function, it takes two arguments the Array and the user_selection, so if the user selection is 2 (2. Merge Sort Algorithm – Step By Step) We will print-out the Dividing Steps and some other Text. [We are using If Statement to print-out Text lines]. Here is the Code ..

ali radwani python code merge sort algorithm



Now for merging function, for merging function we will have two copies, one as Fast-Run and another for Details to print-out the running Steps, this will make the Fast-Run Function short and easy to follow-up. So, here is the Fast-Run Function code for merge the two part of array returned from the merge_sort_divider. Here is the Code ..

Run time screen ..

ali radwani python code merge sort algorithm



End of Merge Sorting Algorithm.

To Download my Python code (.py) files Click-Here



Follow me on Twitter..

By: Ali Radwani

Python: Sorting Algoritm – Bubble Sort

June 1, 2021 3 comments

Learning : Python, Math, Algorithm
Subject: Sorting Algoritm – Bubble Sort

[NOTE: To keep the code as simple as we can, We WILL NOT ADD any user input Varevecations. Assuming that our user will Enter the right inputs.]

Sorting Algorithm is a way to sort a given list of numbers, there are several sorting Algorithm as follow:
Type of Sorting Algorithm
Quick Sort. [Click to Read]
Bubble Sort.
Merge Sort. [Commeing Soon]
Insertion Sort. [Commeing Soon]
Selection Sort. [Commeing Soon]
Heap Sort. [Commeing Soon]
Radix Sort. [Commeing Soon]
Bucket Sort. [Commeing Soon]

Here in this post we will write a function to take a given list and sort it then pass it back. We assume the user will enter a serial of numbers, that he want to sort, our function will sort it and print out the original numbers and the sorted one.

Bubble Sort: Steps of Bubble Sorting Algorithm are:
1. We will select the First Number (Current number) in the list and Compare it with the next number in the list. (Compare list[0] and list[1])

2. If the Next Number in the list IS SMALLER than Current Number SWAP the Two, then compare the Current with the third number and so on.

2.2 If the Next Number in the list IS NOT SMALLER than Current Number, Then we LEFT the Current Number in it’s Position and will Set the Next number as the Current. And will start Comparing Again as Step 2 until the last number in the list.

3. When we reach the end of the list and we perform a SWAP, then we start again with First Element as STEP 1.

4. If we reach the end of the list Without any SWAP being made, then the list is ordered and the algorithm can stop.

Coding Starting with the Main Menu Function and a Function to ask the
User to enter the numbers in the list, here are those two Functions.

python code bubble sorting algorithm project by Ali Radwani doha qatar



And here is the Main code that will call the Menu and trigger the Functions based on the User selecting.

python code bubble sorting algorithm project by Ali Radwani doha qatar



Also we have the Function that will ask the user to Enter the Numbers for the List or Array to be sort.
All the code will be Available as a .py file in the Download Page [Click Here]

Now let’s see the code for Bubble Sorting Algorithm, we will have two version of the code, one for Fast-Run that takes the list and return it back as Sorted, and another one will be to show the Details Step By Step of applying the Algorithm. Both Functions are the same but the details one will have several print statements to show the steps, here I am posting the Fast-Run version.


Run Screen..




End of Bubble Sort Algorithm, hope you enjoy it.


.. Have Fun With Coding ..

To Download my Python code (.py) files Click-Here


Follow me on Twitter..

By: Ali Radwani

Python Project: Disarium Numbers in Range


Learning : python code
Subject: Finding the Disarium number
in a range

[NOTE: To keep the code as simple as we can, We WILL NOT ADD any user input Varevecations. Assuming that our user will Enter the right inputs.]

Definition We call a Number as A Disarium Number if the Sum of it’s Ddigits Powered with their Respective Position is Equal to the Original Number.
So 89 is a Disarium Number, because 8^1 + 9^2 = 8 + 81 = (89 the original number)
and 135 is also a Disarium Number, because 1^1 = 1, 3^2 = 9, 5^3 = 125 and the Total is [1+3+125 = 135 the original number]
we have a previous post to check if a given number is a Disarium Number or not … Read The Post Here .. In this post we will write the Function to print-out all the Disarium Numbers in a given range.

So our application will ask the user to enter two Numbers as a range From and To, then the disarium_n_range(num1,num2) taking two argument will work through a For loop to check each number in the range and if it is a Disarium Number we will store it in a list (disarium_n =[]) .. Let’s start by the asking the user to Input the range numbers..

 # Code to collect the Numbers from the User

print('\n\n   This Project will Print-Out all the Disarium Numbers in a given range.')
num1 = input('\n   Enter the From Number. > ')
num2 = input('\n   Enter the To Number.   > ')




And now let’s see the main Function of the application ..

python project code doha qatar ali radwani


Run-Screen for the range From 10 To 99

python project code doha qatar ali radwani


Another Run for the Range From 100 To 999

python project code doha qatar ali radwani



End of the post ..

To Download my Python code (.py) files Click-Here



Follow me on Twitter..

By: Ali Radwani

Python: Sorting Algorithm (1.Quick Sort)

May 23, 2021 8 comments

Learning : SQL, Python, sqlite, DataBase
Subject: Testing the SQL Join commands using Python.

Sorting Algorithm is a way to sort a given list of numbers, there are several sorting Algorithm as follow:
Type of Sorting Algorithm
Quick Sort.
Bubble Sort.
Merge Sort.
Insertion Sort.
Selection Sort.
Heap Sort.
Radix Sort.
Bucket Sort.

Here in this post we will write a function to take a given list and sort it then pass it back. We assume the user will enter a serial of numbers, that he want to sort, our function will sort it and print out the original numbers and the sorted one.

Quick Sort Steps of Quick Sorting Algorithm are:
1 – Save the first element of the list as pivot. We will call it as pv .
2 – Define Two variables i and j. We will call them as fc, lc fc will be 0 (first element position in the list) and lc will be the length of the list.(last element position in the list) .
3 – Increment fc until the number in the list in fc position is smaller or equal to pv (the first element).
4 – Decrement lc until the number in the list in lc position smaller than pv.

until list[j] < pivot then stop.
5 – If fc less than lc then we swap the two elements in the location of fc and lc. (SWAP list[fc] and list[lc]).

7 – Exchange the pivot element with list[j] element.

Coding First we will write a sort Menu for the project, we will have tree items to select from, Quick Sort Algorithm – Fast Run and Quick Sort Algorithm – Step By Step This will show sorting details.

 # Main Menu

def main_menu ():
    os.system('clear')
    
    print('\n\n',' '*5,'******************************')
    print(' '*5,' ***','  Sorting Algorithm ',' '*1,'***')
    print(' '*5,' ***','     Quick Sort     ',' '*1,'***')
    print(' '*5,' ***',' '*22,'***')
    print(' '*5,' ******************************\n\n')
    
    print(' '*7,'1. Quick Sort Algorithm - Fast Run.')
    print(' '*7,'2. Quick Sort Algorithm - Step By Step.')
    print(' '*7,'9. Exit.')
    
    user_choice = input('\n   Select your choice.  > ')
    return user_choice 



And this is the main code body that will call the menu and check the user selection ..

 # The Main application Body

while True:
    
    user_select = main_menu()

    if user_select == '1' :
        user_list = create_list()
        
        fpos = 0  # first position index
        lpos = len(user_list)-1  # last position index
        
        original_list = user_list 
        print('\n   The original List is: ',original_list)

        user_sorted_list = quick_sort(user_list,fpos,lpos)
        
        print('\n   DONE .. We Finish Sorting .. ')
        print('   The Sorted List is: > ',user_sorted_list)
        input('\n   ...Press any key to continue.  ')
    
    if user_select == '2' :
        user_list = create_list()
        
        print('\n   We will show the Quick Sorting Step By Step... \n')
        fpos = 0  # first position index
        lpos = len(user_list)-1  # last position index
        original_list = user_list

        print('\n   The Original List is: ',original_list)
        user_list = quick_sort_details(user_list,fpos,lpos)
        
        print('\n   DONE .. We Finish Sorting .. ')
        print('   The Sorted List is: > ',user_list)
        input('\n   ...Press any key to continue.  ')

    if user_select == '9' :
        break



Also we will have a Function to take the List of Elements from the user, the user input will be as a string, we will convert it to an integer List and will return it back.. Here is the code ..

 # Create the List

def create_list():
    print('\n   Enter the List Elements separated by SPACE, when Finish just Press Enter.')
    the_list = input('\n   Start Entering the Numbers in the List. >  ')
    
    # Convert user input to List
    the_list = the_list.split()        
    
    # Convert str list to int list  
    the_list = [int(each) for each in the_list]

    return the_list



Now let’s write the Quick_sort function, then we will duplicaet it and add some print statements to show sorting steps. So first the code for Quick Sort Algorithm – Fast Run. Here is the code ..

Screen shot of the Quick Sort Algorithm – Fast Run.
python project code Quick Sort Algorithm ali radwani



Running this Function will return the sorted list and display it on the screen, I thought it will be nice if we show the sorting process Step by Step, so I copy the same Function with adding some print-statement in-between .. here is the code and the run-output..

Screen shot of the Quick Sort Algorithm – Detail Run.
python project code Quick Sort Algorithm ali radwani



End of Sorting Algorithm (1.Quick Sort)

To Download my Python code (.py) files Click-Here



Follow me on Twitter..

By: Ali Radwani

Python: Testing the SQL joines Commands


Learning : SQL Commands, DataBase, Python
Subject: Testing the SQL Join Commands


Introduction In this post we will apply several SQL Join Commands to test them, here are them:

Left Join:
All the Data in the Category
ali radwani learning python sql joins commands
Right Join: All the Data in the Products ali radwani learning python sql joins commands
Inner Join:
All the Data that in Both Tables.
ali radwani learning python sql joins commands
Left Join
Only Data in Category Table and NOT in Product Table.
ali radwani learning python sql joins commands
Right Join:
Only data in Product Table and NOT in Category Table.
ali radwani learning python sql joins commands
Full Outre:
All the Records in both Tables
ali radwani learning python sql joins commands
Full Outre:
All the data from the Category Table that are NOT linked to any Product, AND all the data in Product Table that has NO Category.
ali radwani learning python sql joins commands


First: let’s talk about the Tables,we will create two Tables (Category and Products) each will be very simple, the Category will have two fields [c_id, and cat_name],
the Products will have [p_id, pro_name, cat_id]. (cat_id is the foreign key that connicting the two tables). Some test data will be inserted in both Tables so we can demonstrate the SQL Commands. I create a Dictionary storing information/summary about the project named about_the_project the user can read it in run time.

Coding: We will do the fowlloing:
1. Set a Database for the Project.
2. Writing the codes to Create the Tables.
3. Writing the codes to insert some test Data in the Tables.
4. Creating a Menu for the Project.
5. Writing the Functions to Apply the SQL Join commmands.

NOTE: All the code will be avilable in the DOWNLOAD page.

Let’s import some lybraries, we will need this code:

import sqlite3, os

And here is the code to set the data base and create the connection.
# Create the data-base and name it as Share_S_System.
db_conn = sqlite3.connect (“sql_join_test.db”)

# set the connection.
c = db_conn.cursor()

First function is to create the Tables:

 # Function to create the Tables.

def create_tables ():
    
    # CREATE TABLE:
    category_t = "CREATE TABLE if not exists category_t (c_id INTEGER PRIMARY KEY AUTOINCREMENT, cat_name text)" 
    c.execute(category_t) 
    db_conn.commit()     
    
    product_t = "CREATE TABLE if not exists product_t (p_id INTEGER PRIMARY KEY AUTOINCREMENT, p_name text, cat_id integer)" 
    c.execute(product_t) 
    db_conn.commit()     


Now we will insert some Test data.

 # Function to insert some Data into the Tables

def insert_sample_data():
    
    #First we will call the Function to Crete the Table.
    create_tables ()
    print('\n   Category Table has been Created. ')
    print('\n   Product Table has been Created. ')
    
    # Insert into Category Table
    c.execute ("INSERT INTO category_t (cat_name) VALUES(:cat_name )",{"cat_name":"Mobile Phone"})
    c.execute ("INSERT INTO category_t (cat_name) VALUES(:cat_name )",{"cat_name":"Labtop"}) 
    c.execute ("INSERT INTO category_t (cat_name) VALUES(:cat_name )",{"cat_name":"Ext. HD"}) 
    c.execute ("INSERT INTO category_t (cat_name) VALUES(:cat_name )",{"cat_name":"CCTV Camera"})     
    db_conn.commit()

    # Insert into Product Table.
    c.execute ("INSERT INTO product_t (p_name, cat_id) VALUES(:p_name, :cat_id )",{"p_name":"Note 9","cat_id":"1"})
    c.execute ("INSERT INTO product_t (p_name, cat_id) VALUES(:p_name, :cat_id )",{"p_name":"iPhone 12 pro","cat_id":"1"})
    c.execute ("INSERT INTO product_t (p_name, cat_id) VALUES(:p_name, :cat_id )",{"p_name":"HP","cat_id":"2"})
    c.execute ("INSERT INTO product_t (p_name, cat_id) VALUES(:p_name, :cat_id )",{"p_name":"Toshiba 1T HD","cat_id":"3"})
    c.execute ("INSERT INTO product_t (p_name, cat_id) VALUES(:p_name, :cat_id )",{"p_name":"iMac","cat_id":None})
    db_conn.commit()
    
    print('\n   Sample Date Inserted in both tables.\n   Select 9 from the Main Menu to see the Data')
    
    input('\n      ... Press any key to continue.  > ')


Now, let’s write the function for the Main Menu, it will return the user_choice.. here is the code..

 # Main Menu Function.

def main_menu():
    os.system('clear')
    print("\n==========[ Main Menu ]==========")    
    print(' 1. About this Project.')
    print(' 2. All Categories. (Left Join: All in Category Only).')
    print(' 3. All Products. (Right Join: All in Product Only).')
    print(' 4. Only Categories that linked to a Products. (Inner Join: Only if in Ta AND Tb).')
    print(' 5. All Catigories that are NOT linked to a Product. (Left Join: Only in Category AND NOT in Product .')
    print(' 6. All Products that has NO Category. (Right Join: Only in Product AND NOT in Category.')
    print(' 7. All Categories and Products. (Full Outer Join in Both Table)' )
    print(' 8. All Categories that are NOT linked to any Product, and All Products that has NO Categotry. (Full Outer Join NOT in Both Table)')
    print(' 9. Show the Data') 
    print(' 11. Setting: Create the Tables and Insert Some Sample Data. Run Only One Time.')
    print(' 99. Exit.')

    user_choice = input("\n Select from the Menu: > ") 
    return user_choice
ahradwani.com python code SQL join


The coming part of the code is calling the functions and running the SQL commands based on the user choice. Here is the Main-code-body..

 # The Main section of the Application..

while True :
    user_select = main_menu()

    if user_select == '1' :
        show_data('cat') 

    if user_select == '2' :
        show_data('prod') 

    if user_select == '3' :
        os.system('clear')
        print('\n   First: All the Data in Category and Product ')
        show_data('both','inside')
        print("\n==========[ Show Date: INNER JOIN ]==========\n")
        print('   Inner Join: Only the Data that exist in Category AND Product).')
        print('\n   The SQL Statment:\n    select category_t.c_id, product_t.p_name from category_t inner join product_t on category_t.c_id == product_t.cat_id\n\n ')
        c.execute ("select category_t.c_id, category_t.cat_name, product_t.p_name from category_t inner join product_t on category_t.c_id == product_t.cat_id  ") 
        innerJ_list = c.fetchall() 
     
        print('   [OUTPUT]:\n       Categories Name      |',' '*2,'Products Name    ')
        for innerJ_data in (innerJ_list): 
            print('       ',innerJ_data[1],'.'*(25 - len(str(innerJ_data[1]))),innerJ_data[2]) 
            
        print('\n   We can see that the INNER JOIN Command fetched the records of Products that has a Category.\n   iMac Not listed Because it has No Category Data.')         
        input('\n\n      ...Press any key to continue.  > ') 
    
   if user_select == '4' :
        os.system('clear')
        print('\n   List of All the Data in Category and Product ')
        show_data('both','inside')
        print("\n==========[ Show Date: LEFT JOIN, Only Data in Categoty Table ]==========\n")
        print('   The SQL Statment:\n     select category_t.c_id, category_t.cat_name, product_t.p_name from category_t\n     left join product_t on category_t.c_id == product_t.cat_id\n     where product_t.cat_id is null\n')
        c.execute ("select category_t.c_id, category_t.cat_name, product_t.p_name from category_t left join product_t on category_t.c_id == product_t.cat_id where product_t.cat_id is null") 
        leftJ_list = c.fetchall()     
        print('   [OUTPUT]:\n       Categories Name      |',' '*2,'Products Name    ')
        for leftJ_data in (leftJ_list): 
            print('         ',leftJ_data[1],'.'*(25 - len(str(leftJ_data[1]))),leftJ_data[2]) 
              
        print('\n   We can see that the LEFT JOIN Command fetched all Categories that are not used/linked to/with any Product.\n   CCTV Camera is Not linked. So We can Say: We Do Not have any CCTV Camera Products.')         
        input('\n\n      ...Press any key to continue.  > ') 

    if user_select == '5' :
    ....
# Just to save the time, i will not post all the code here, you can see all the code and download
# the .py source code from the download page.


Here are some screen shot of the output ..

The Main Menu

ahradwani.com python code SQL join functions commands

Output Screen for Option 3: Only Categories that linked to a Products.
(Inner Join: Only if Data in Category AND Product)
ahradwani.com python code SQL join functions commands



End of the Post, and all the code is available to download from the Download page.


To Download my Python code (.py) files Click-Here



Follow me on Twitter..

By: Ali Radwani

Python Project: Disarium Number

April 4, 2021 1 comment


Learning : Python to solve Mathematics Problems
Subject: Disarium Number

In Mathematics there are some formulas or let say rules that generate a sequence of given a certen result, and accordingly we gave that number or that sequence a name, such as even numbers, odd numbers, prime numbers and so on.

Here in this post we will talk about the Disarium Number and will write a code to check if a given number Disarium or Not.
Defenition: A Number is a Disarium if the Sum of its digits powered with their respective position is equal to the original number. Example: If we have 25 as a Number we will say: if (2^1 + 5^2) = 25 then 25 is Disarium.
So: 2^1 = 2, 5^2 = 25, 2+25 = 27; 25 NOT Equal to 27 then 25 is NOT Disarium.

Let’s take n = 175:
1^1 = 1
7^2 = 49
5^3 = 125
(1 + 49 + 125) = 175 thats EQUAL to n so 175 is a Disarium Number.

In the bellow code, we will write a function to take a number from the user the check if it is a Disarium Number or not. In this function we will print out the calculation on the screen. Let’s start by writing the function

# is_disarium function.
def is_disarium(num) :
"""
Project Name: Disarium Number
By: Ali Radwani
Date: 2.4.2021
"""


the_sum = []
l = len(num)
for x in range (0,l):
print(num[x] , '^',x+1,'=', (int(num[x])**(x+1)))
the_sum.append((int(num[x])**(x+1)))

if int(num) == sum(the_sum) :
print ("\n The sum is {}, and the original Number is {} So {} is a Disarium Number.".format(sum(the_sum),num,num))
else:
print ('\n The sum is {}, and the original Number is {} So it is NOT Disarium.'.format(sum(the_sum),num))


num = input('\n Enter a Number to check if it is Disarium. > ')

# Call the function and pass the num.
is_disarium(num)
ali radwani python project learning sql codeing

To Download my Python code (.py) files Click-Here


Follow me on Twitter..


By: Ali Radwani

Python Project: Drawing Cloud Number

March 25, 2021 Leave a comment


Learning : Python, Drawing
Subject: Using Python to Draw Cloud Number

In this project we will write a code to draw a cloud of number, we will do this as layers each layer with different font size and different color density.

To do this we will write a function def draw_cloud(tcolor,max_r,sr,lr) : to fill the screen with max_r random numbers from sr to lr (small range, large ramge) using tcolor color. We will recall the function several time each time we will change the tcolor,max_r,sr,lr. Here is the code ..

The Code
ali radwani python project learning sql codeing

Example with Gray theme

Another Example with Pink theme.


Follow me on Twitter..


By: Ali Radwani

Python: My Orders Tracker P-4

March 17, 2021 Leave a comment


Learning : Pythn, sqlite, Database, SQL
Subject: Create a system to track the orders

In this last part we will write the code to Edit an Order, in editing an order function first we will show all orders and will ask the user to select the one to be EDIT, then we will display that order detail on the screen and ask the user to confirm the action by entering ‘Y’ [our code will handel both y and Y]. We will ask the user about each attribute in the Order details if it need to be change or [Just press Enter to Keep the Current Data], also if the user enter ‘e’ or ‘E’ we will exit from the Editing mode.

Here is the code ..

# Function to Edit an Order

def edit_order():
    os.system('clear')
    print("\n==========[ Edit Orders ]==========")
    
    show_order('yes')
    
    edit_order = input('   Select the Order ID to be Edited. [E to Exit] > ')
    
    if edit_order in ['e','E'] : 
        return
    elif not edit_order.isnumeric() :
        input('\n   You need to enter an Order''s ID [Numeric]. .. Press any Key .. ')
        return 
               
    try:        
        
        c.execute ("select * from orders where o_id ={}".format(edit_order))  
        order_list = c.fetchone() 
        
        if order_list == [] :
            input('\n   ID {} Not Exsist. .. Press any key to continue.  '.format(edit_order))
            return
        
        os.system('clear')
        print("\n==========[ Edit Orders ]==========\n")
        print('\n   Details of the Order you select:\n ')
    
        print(" "*15,"ID: ",order_list[0])  
        print(" "*13,"Date: ",order_list[1])
        print(" "*5,"Order Number: ",order_list[2])
        print(" "*12,"Price: ",order_list[4])
        print(" "*9,"Quantity: ",order_list[5])
        print(" "*3,"Shipment Price: ",order_list[6])
        print(" "*7,"Total Cost:  {:.2f}".format((order_list[4]*order_list[5]) + order_list[6]))
        print(" "*6,"Description: ",order_list[3])
        print(" "*12,"Image:",order_list[8])
        print(" "*13,"Link:",order_list[7])
    
        user_confirm = input("\n\n   You Select to EDIT the above Order, Enter Y to confirm, E to Exit. > ") 
        if user_confirm in ['e','E'] : 
            input('\n   You entered ''E'' to Exit. Nothing  will be change. Press any key. ')
            return 
        
        if user_confirm in ['y','Y'] :
            #To Edit the order.. 
            
            print("#"*57)
            print("##"," "*51,"##")
            print("##   NOTE: Enter E any time to EXIT/Quit."," "*12,"##")
            print("##     OR  JUST Press Enter to keep the Current data."," ##")
            print("##"," "*51,"##")
            print("#"*57,)
            
            while True :
                 
                new_date = input (f'\n   The current date is: {order_list[1]}, Enter the New date as[dd-mm-yyyy] > ')
                
                if e_to_exit(new_date) =='e' : return
                if new_date =="" : break   # Break the while loop if the user want to keep the current Date.
                
                if date_validation (new_date) == 'valid' :
                    break           
                else :
                    print(date_validation (new_date))    
        
                      
            new_onum = input (f'\n   The current Order Number is: {order_list[2]}, Enter the New Order Number. [E to Exit]. > ')
            if e_to_exit(new_onum) =='e' : return           
            
            new_qunt = input (f'\n   The current Quantity is: {order_list[5]}, Enter the New Quantity. [E to Exit]. > ')
            if e_to_exit(new_qunt) =='e' : return
            
            new_price = input (f'\n   The current Price is: {order_list[4]}, Enter the New Price. [E to Exit]. > ')
            if e_to_exit(new_price) =='e' : return
            
            new_ship_price = input (f'\n   The current shipment Price is: {order_list[6]}, Enter the New Quantity. [E to Exit]. > ')
            if e_to_exit(new_ship_price) =='e' : return
            
            new_link = input (f'\n   The current link is: {order_list[7]}, Enter the New Link. [E to Exit]. > ')
            if e_to_exit(new_link) =='e' : return
            
            new_image = input (f'\n   The current Image is: {order_list[8]}, Enter the New Image (path). [E to Exit]. > ')
            if e_to_exit(new_image) =='e' : return
                        
            
            new_desc = input (f'\n   The current Description is:\n     {order_list[3]}.\n\n      Enter the New Description. [E to Exit]. > ')
            if e_to_exit(new_image) =='e' : return
            
            
            # Updating the record in the DataBase. 
            if new_date > '' and new_date != "e" :
                c.execute("update orders set order_date = '{}' where o_id = {}".format(new_date,int(order_list[0]))) 
                db_conn.commit()
            
            if new_onum > '' and new_onum != "e" :
                c.execute("update orders set order_num = '{}' where o_id = {}".format(new_onum,int(order_list[0]))) 
                db_conn.commit() 
        
            if new_qunt > '' and new_qunt != "e" :
                c.execute("update orders set order_quantity = '{}' where o_id = {}".format(new_qunt,int(order_list[0]))) 
                db_conn.commit() 
                        
            if new_price > '' and new_price != "e" :
                c.execute("update orders set order_price = '{}' where o_id = {}".format(new_price,int(order_list[0]))) 
                db_conn.commit() 
            
            if new_ship_price > '' and new_ship_price != "e" :
                c.execute("update orders set order_price = '{}' where o_id = {}".format(new_ship_price,int(order_list[0]))) 
                db_conn.commit() 
                                
            if new_link > '' and new_link != "e" :
                c.execute("update orders set order_link = '{}' where o_id = {}".format(new_link,int(order_list[0]))) 
                db_conn.commit() 
                           
            if new_image > '' and new_image != "e" :
                c.execute("update orders set order_img = '{}' where o_id = {}".format(new_image,int(order_list[0]))) 
                db_conn.commit() 
             
            if new_desc > '' and new_image != "e" : 
                new_desc = " ".join([word.capitalize() for word in new_desc.split(" ")]) 
    
                c.execute("update orders set order_desc = '{}' where o_id = {}".format(new_desc,int(order_list[0]))) 
                db_conn.commit() 
            
            input('\n   One record has been EDITED and Saved... \n      ... Press any key to Continue ...')   
    
        else:        
            input('\n      Wrong input ... Press any key to continue ..')    
    
    except:
        pass

[All the System Codes available in Download Page.]



Finish: Now we have an application that will store and retrieve our simple order data.
Enhancement:
We can do some enhancement in [link and image] data part to show and display them in better way.


Part 1 Part 2 Part 3 Part 4



To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani




Python: My Orders Tracker P-3

March 10, 2021 1 comment


Learning : Pythn, sqlite, Database, SQL
Subject: Create a system to track the orders

In this part we will write the code to Delete an Order that we have from our system, also we will add some validations on the user input, like if the user enter something not from the menu, or to do so, first we will re-call the show_orders() function that we have and passing the ‘yes’ parameter which means we are calling the function from inside another function [we will not print the function header, and will not clear the screen]. Then we will ask the user to select/Enter the ID of the order to be Deleted, after that we will print tha order details again on the screen and ask the user to confirm Deleting command by entering ‘Y’ … thats it.. let’s write the code..

# Delete Order

def del_order():
os.system('clear')
print("\n==========[ Delete Orders ]==========\n")

show_order('yes')

del_order = input(' Select the Order ID to be Deleted. [E to Exit] > ')

if not del_order.isnumeric() :
input('\n You need to enter an Orders ID [Numeric]. .. Press any Key .. ')
return

elif del_order in ['e','E'] :
return

try:
c.execute ("select * from orders where o_id ={}".format(del_order))
order_list = c.fetchone()

if order_list == [] :
input('\n ID {} not exsist.'.format(del_order))
return

os.system('clear')
print("\n==========[ Delete Orders ]==========\n")
print('\n Details of the Order you select:\n ')

print(" ID: ",order_list[0])
print(" Date: ",order_list[1])
print(" Order Number: ",order_list[2])
print(" Price: ",order_list[4])
print(" Quantity: ",order_list[5])
print(" Shipment Price: ",order_list[6])
print(" Total Cost: {:.2f}".format((order_list[4]*order_list[5]) + order_list[6]))
print("\n Description:",order_list[3])
print(" Image:",order_list[8])
print(" Link:",order_list[7])

user_confirm = input("\n\n You Select to DELETE the above Order, Enter Y to confirm, E to Exit. > ")
if user_confirm in ['y','Y'] :
#To Delete the order..
c.execute ("delete from orders where o_id ={}".format(int(del_order)))
db_conn.commit()

input('\n One record has been DELETED ... \n ... Press any key to Continue ...')

elif user_confirm in ['n','N']:
input("\n You select not to DELETE any thing. Press any key to Continue .. ")

elif user_confirm in ['e','E']:
input("\n You select stop the process and EXIT. ... Press any key to Continue .. ")
return

else:
input('\n Wrong input ... Press any key to continue ..')

except:
pass
The user select #3 from the menu to Delete an Order
ali radwani python project learning sql codeing
The screen display the list of orders we have in the system, and the user select Order ID Number 3 to delete it.
The screen display the details of the order ID 3 and ask the user to confirm the deleting by entering ‘Y’

In Next Post: In the coming post P4 , we will write the codes to Edit an order information.

Part 1 Part 2 Part 3 Part 4

To Download my Python code (.py) files Click-Here


Follow me on Twitter..


By: Ali Radwani

Python: My Orders Tracker P-2

February 28, 2021 2 comments


Learning : Pythn, sqlite, Database, SQL
Subject: Create a system to track the orders

In this part we will write the code to Add new Order to the system, and to Show the orders we have in the database. Also we will write tow new functions that we will use in our application, one is the Date Validation and the other is just to check if the user enter a [q or Q] during collecting data [Q mean Quit] then we will call the quit() function.

Before we start the Add new order function, we will write the def date_validation (the_d) : and we will pass the date that the user enter and will check if it is in the right format, here in our application we will check if it is in [dd-mm-yyyy] format, the function will return the ‘valid’ string if the date in in right format, otherwise it will return a message of error.

Here is the function code ..

# Date Validation function.
def date_validation (the_d) :

if the_d=="" or the_d[2] !='-' or the_d[5] !='-' :
return '\n Date Not Valid. [Date format: dd-mm-yyyy]'
else:

if not(len((the_d.split("-")[2])) == 4 ):
return '\n Date Not Valid "Bad Year". [Date format: dd-mm-yyyy].'
if not (len((the_d.split("-")[1])) == 2 and (int(the_d.split("-")[1]) > 0 and int(the_d.split("-")[1]) 0 and int(the_d.split("-")[0]) <=31)) :
return '\n Date Not Valid "Bad Day". [Date format: dd-mm-yyyy].'

return 'valid'

The other function as we said, we will call it after each data entry to check on user input if it is ‘Q’ or Not. Here is the code..

def q_to_quit(check):

# If the user enter [q or Q] the function will return quit function.
if check in ['q','Q'] :
return quit()

Now, we will start to write the function to Add new order, we will ask the user to enter the date for the order, such as Order date, order number, the description, price and so-on. Here is the code..

# Function to add new order to the system.
def add_order():
os.system('clear')
print("\n==========[ Add New Order ]==========\n")

while True :
print(' NOTE: Enter Q any time to EXIT/Quit. \n')
order_date = input(' Enter the Date of the Order. as[dd-mm-yyyy] > ')

q_to_quit(order_date)

if date_validation (order_date) == 'valid' :
break

else :
print(date_validation (order_date))

order_Num = input(' Enter the order ID or Number. > ')
q_to_quit(order_Num)

order_desc = input(' Enter the order Description. > ')
q_to_quit(order_desc)

order_price = input(' Enter the Order Price. > ')
q_to_quit(order_price)

order_quantity = input(' Enter the quantity of the order. > ')
q_to_quit(order_quantity)

shipment_price = input(' Enter the shipment_price. > ')
q_to_quit(order_price)

order_link = input(' Enter the hyper Link to the Order. > ')
q_to_quit(order_link)

order_img = input(' Enter the Image file path. > ')
q_to_quit(order_img)

order_desc = " ".join([word.capitalize() for word in order_desc.split(" ")])
c.execute ("INSERT INTO orders (order_date, order_num, order_desc, order_price,order_quantity, shipment_price , order_link, order_img ) VALUES(:order_date, :order_Num, :order_desc, :order_price, :order_quantity, :shipment_price , :order_link, :order_img)", {"order_date":order_date, "order_Num":order_Num , "order_desc":order_desc, "order_price":order_price,"order_quantity":order_quantity, "shipment_price":shipment_price , "order_link":order_link, "order_img":order_img})

db_conn.commit()

input('\n Press any key to Contenu..')

After adding a records to the database, now we want to show what we have and print it on the screen, so we will write a function to Show the data. Here is the code..

# Function to display the data on the screen. 


def show_order():
os.system('clear')
print("\n==========[ Show Orders ]==========\n")

c.execute ("select * from orders where o_id >0")
order_list = c.fetchall()

for x in range (0,len(order_list)):
print(" ID: ",order_list[x][0]," "*(10-(len(str(order_list[x][0])))), end='')
print("Date: ",order_list[x][1]," "*2, end='')
print(" Order Number: ",order_list[x][2]," "*(8 - len(order_list[x][2])))
print("Price: ",order_list[x][4]," "*(6 - len(str(order_list[x][4]))), end='')
print("Quantity: ",order_list[x][5]," "*(11 - len(str(order_list[x][5]))), end='')
print("Shipment Price: ",order_list[x][6]," "*(10 - len(str(order_list[x][6]))), end='')
print("[ Total Cost: ",(order_list[x][4]*order_list[x][5]) + order_list[x][6],"]")

print("\nDescription:",order_list[x][3])
print("Image:",order_list[x][8])
print("Link:",order_list[x][7])

print("-------------------------------------------------------------------\n")

input('\n Press any key to Contenu.. ')
ali radwani python project learning sql codeing

In Next Post: In the coming post P3 , we will write the codes to Delete an Order and to Edit an order.

To Download my Python code (.py) files Click-Here


Follow me on Twitter..


By: Ali Radwani