Archive

Posts Tagged ‘Lesson’

Python: Random Pixel Color – P2


Learning : Python, Math
Subject: Random Coloring Pixels

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

Our last post about Random Pixel Color, we generate a Numpy Array of Row, Coloum and color then we Plot it on the screen [Read the Post Here], now in this post we will use some Math consepts to try if we can get some patterns out of ramdom Function.
Our Tools: In this post we will use the following:
1. Jupyter-NoteBook.
2. numpy.
3. random.
4. matplotlib.
5. PIL or Pillow.

In this version we will use “Fibonacci Sequence” Fibonacci Sequence is the sum of the two preceding ones, starting from 0 and 1 such as [1, 1, 2, 3, 5, 8, 13 … n], in our code we will have three variables:
cw: canvas width,
ch: canvas hight,
offset: the offset will be the value that will reset the Fibonacci Sequence to 1.

So, if we run the application, we will generate three numbers that will present the colors R,G,B (Will be Generated ONE time) then for each pixcel in (cw*ch) we will calculate a v as Fibonacci Sequence from fs1 =1, fs2 = 1 here is the code:
v = fs1 + fs2
fs1,fs2 = fs2, v

this value v will be added to the colors r,g,b (on each pixcel) untill the v is grater the the offset numbre that we pass to the Function. If v > offset then we will re-set the fs1 = 1, fs2 = 1,.. Here is the Code ..

ali radwani ahradwani.com python code project draw color
Here are some Out-put

Run No.1python code project color pixcel ali radwani Run No.2
python code project color pixcel ali radwani
Run No.3
python code project color pixcel ali radwani
Run No.4
python code project color pixcel ali radwani


The above is just 25×25 and i change the offset, feel free to download the code and change the numbers .. see what you will get …

..:: Have Fun with Coding ::.. 🙂

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



ali radwani ahradwani.com python projects codeFollow me on Twitter..

By: Ali Radwani

Python: Sort Algorithm – 3 – Insertion Sort

June 8, 2021 2 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.

Insertion Sort: Steps of Insertion Sorting Algorithm are:

1. Start with index (x = 1), Compare the Element (k) in index [x] with the Element in index [x-1].
1.1 If Element in [x-1] SMALLER than Element in [x] we swap the two elements.
1.2 Once we Swap we will have new index for k , and again we will compare the (k) in (new index) with element before it (new index -1), and keep moving it to left until we stop at index [0] or we face an Element GRATER than k.

2. If the Element k GRATER than the element before it, we left k and take the Next Element (to be k) and start comparing K [in x index] with Element in [x-1] index.

3. We do this until k will be in index (length on the list)

Now starting with the codes, as our standard we follow in Sorting Algorithm Applications we will have a Main-Menu and three Items the user will chose among them, and Function to let the user to enter the Numbers [The List or the Array] to be sorted. The Options in the Main-Menu are :
1. Insertion Sort Algorithm – Fast Run.
2. Insertion Sort Algorithm – Step By Step.
9. Exit.

The Fasr-Run we call the create_list(): Function first so the user will Enter the Numbers in the Array, then the Fast-Run will show the sorted Array on the screen.
In the Step-By-Step (Option 2 in the Menu) again calling create_list(): Function first, after the user Enters the Array, we will print-out on the screen each steps of selecting the index, and index-1, the k values and when/if we will SWAP or not.
The last option in the Menu is to Exit the Application (option 9).

Now we start coding.. Here is the Main-Menu.

 # Main-Menu

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


Here is the codes for create_list(): to collect the Array from the user..

ali radwani ahradwani.com python code project sorting algorithm insertion sort
ali radwani ahradwani.com python code project sorting algorithm insertion sort


Finaly, here is the code for the Step-by-Step running for the Insetion Sort Algorithm. It is the same copy of the Fast-Run but with some print statements to show what is happening.

ali radwani ahradwani.com python code project sorting algorithm insertion sort


We Done another coding for Sorting Algorithms, another one will be published in coming days..

… Have fun with Coding … 🙂

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



ali radwani ahradwani.com python projects codeFollow me on Twitter..

By: Ali Radwani

Project: Knapsack Problem


Learning : Python, Math, Algorithm
Subject: Solving Knapsack Problem using 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.]

Definition: The knapsack problem is a Problem in Combinatorial Optimization: Given a set of Items, Each with a Weight and a Value or Profit, We need to Determine the Number of Each Item to Include in a Collection so that the Total Weight is Less than or Equal to a Given Limit and the Total Value is as Large as Possible.
Source: Wikipedia

In this post we will write three Functions, The Main Menu, one to Collect the data and another to solve the problem. So first, let’s see the Main-Menu ..

# Main Menu of the Project
def main_menu ():
    os.system('clear')
    print('\n',' '*5,'******************************')
    print(' '*5,' ***','   Knapsack Problem','   '*1,'***')
    print(' '*5,' ***',' '*22,'***')
    print(' '*5,' ******************************')    
    print('\n',' '*5,"==========[ Main Menu ]==========")
    print(' '*5,' 1. About Knapsack Problem.')
    print(' '*5,' 2. Collect the Items.')
    print(' '*5,' 3. Solve the Problem.')
    print(' '*5,' 9. Exit.')

    user_choice = input("\n   Select from the Menu: > ") 

    return user_choice



Above Menu will display three option that the user can select from:
1. About Knapsack Problem. [To give simple information about what is Knapsack Problem]
2. Collect the Items. [Will ask the user to Enter the Items and their coresponding Weights and Profits.]
3. Solve the Problem. [The user will Enter the Weight limit we have then we will Solve the problem]

Now we will write the Function to collect the Data from the user we will call it def collect_items(): the user will Enter the Item Name, the Weight and the Value or Profit and will save it in a list, then will return it as item_list. Here is the code and run-time screen.

ali radwani python project Knapsack Problem Algorithm
ali radwani python project Knapsack Problem Algorithm



After Collecting the Items, the user can select Number (3) from the Menu to Solve the Knapsack Problem. First we will ask user to Enter the Weights Limit we have, then calculating the Profit over Weight for each Items. In Knapsack we select the Items based on the Max w/p for each and store the indexs in a list, and with each selection we must not exceed the weight limits. Here is the code.. ..

ali radwani python project Knapsack Problem Algorithm
ali radwani python project Knapsack Problem Algorithm



So from the above example, we can achieve the Maximum Profit with weight limits to 50Kg if we take Full Amount of Item a, and Full Amount of Item b and 0.666666666 (0.67) amount of Item c.

1 * 60 = 60
1 * 100 = 100
0.67 * 120 = 80

60 + 100 + 80 = 240

NOTE: The Weight in Knapsack Problem can be weight in kg, or Number/Amount of the item (60 bags, 100 bags ..) or any Unit.

Have fun and do some 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 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: Data Visualization Part-1

January 6, 2021 1 comment


Learning : python, pygal, Data Visualization, Bar Chart
Subject: Data visualization using pygal library

pygal is a Data Visualization library in python to help us showing our Data as a graph. In coming several posts we will discover and learn how to use the pygal library in simple and easy configuration and style.

First we need to install pygal packeg, to do so write this:
pip install pygal

Now we need some Data to show, in this leson I am using aGalaxy Tab S4, so all the codes will be tested and applyed on trinket.io website [trinket.io alow us to use pygal package online so we don’t need to install it on our divice]

Type of Chart:
pygal has several types of charts that we can use, here we will list them all then in coming posts will use each one with simple data. So what we have:
Line, Bar, Histogram, XY,
Pie, Radar, Box, Dot,
Funnel, SolidGauge, Gauge, Pyramid,
Treemap, Maps

Some of those charts has a sub-types such as in Bar char we have: Basic, Stacked and Horizontal. Also for each chart we can add a title and labels and we can use some styles.

So let’s start ..
First we will go for the Bar chart, and we have three sub-types as Basic, Stacked and Horizontal.

First chart: Bar chart:
In this part we will demonstrate the Bar Chart, it has three sub-types as Basic, Stacked and Horizontal.

We assume that our data is the Males and Female ages on first marage, the data will be as dictionary (later we will see how to customize each bar)

 # Basic Bar Chart using pygal

import pygal 
bar_chart = pygal.Bar() # To create a bar graph object
bar_chart.add('Females', [22,25,18,35,33,18]) 
bar_chart.add('Males', [30,20,23,31,39,44]) 

bar_chart.title = "Males and Females First Marage Age"
bar_chart.x_labels=(range(1,6))
 
bar_chart.render() 


Sample code for Basic bar chart


Another sub-type in Bar chart is Horizontal-Bar, it is semelar to the Basic but as if fliped 90 degree. Here is the code ..

 # Horizontal Bar Chart using pygal

import pygal

# HorizontalBar()
HBar = pygal.HorizontalBar()
HBar.add('Females', [22,25,18,35,33,18]) 
HBar.add('Males', [30,20,23,31,39,44]) 

HBar.title = "Males and Females First Marage Age"

HBar.x_labels=(range(1,6))

HBar.render() 


Sample code for Horizontal Bar chart


Last sub-type in Bar chart is Stacked Bar were all data of each element will be in one bar. Here is the code and example..

 # Stacked Bar Chart using pygal

import pygal 
# StackedBar() 
stackedbar = pygal.StackedBar()
stackedbar.add('Females', [22,25,18,35,33,18]) 
stackedbar.add('Males', [30,20,23,31,39,44]) 
stackedbar.x_labels=(range(1,0))
stackedbar.title = "Males and Females First Marage Age"

stackedbar.render() 




If we say we have another data-set as “age in First-Divorces” and we want to add this set to the Stacked Bar chart, then we first will create the data-set as:
stackedbar.add(‘Divorses’, [35,22,45,33,40,38])
and we will arrange the code line to be at top,middle or bottom of the bar. Here is the code..

Sample code for stacke Bar chart with Divorce data




Next we will talk about Line chart.


:: Data Visualization using pygal ::

Part-1
Bar-Chart
Part-2 Part-3 Part-4




Follow me on Twitter..




By: Ali Radwani




Python: Password Generator

January 1, 2021 Leave a comment


Learning : Python Project
Subject: Password Generator

In this function we will use the string library to select a random X numbers of letters as a Password length and print it on the screen.

First: We create a list of letters type l_type that hold the following: lowercase, uppercase, digits, punctuation and we will use the (random.choice) to select from the list.
Then we will call the ‘password Generator’ pass_generator function torandomly select a letter based on the selected type, we will do so for a X time (X is the length of the password). In this project we will print the password on the screen, in real-life we can send the password via email or SMS. Here is the Code ..

# Password Generator Function

"""

Project: Python Password Generator
By: Ali Radwani
Date: Des-2020


    This function will use the string library to select a random X numbers of letters as a Password and print it on the screen. 

    We create a list of letter type l_type that hold the following lowercase, uppercase, digits, punctuation and we will
    use the (random.choice) to select from the list, then we will call the 'password Generator' pass_generator function to
    randomly select a letter, we will do so for a X time (X is the length of the password). In this project we will print 
    the password on the screen, in real-life we can send the password via email or SMS. 

"""

import random, string 

l_type = ["lowercase","uppercase","digits","punctuation"]

the_password =[]

def pass_generator(lt) :
    if lt =="lowercase":
        the_password.append(random.choice(string.ascii_lowercase))
        
    elif lt =="uppercase" :
        the_password.append(random.choice(string.ascii_uppercase))
        
    elif lt =="digits" :
        the_password.append(random.choice(string.digits))
        
    elif lt =="punctuation":
        the_password.append(random.choice(string.punctuation))
            
    return the_password
   
    
pass_length = int(input("\n   Enter the password Length: > "))


while len(the_password) < pass_length:
    pass_generator(random.choice(l_type))
    

print("\n   The New Generated Password is: ","".join(the_password))





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




Follow me on Twitter..




By: Ali Radwani




Library System with Excel -P4

November 24, 2020 Leave a comment


Learning :Excel formulas and VBA Cods
Subject: To Develop a Library System with Excel

In last post we wrote all the codes needed to Manage the Authors.

In this part we will do all the coding needed to enter New Books and Edit or Delete anyone we select, in Classifications and Authors we were dealing with one attribute, but here with Books Manage form we have several pieces of information to collect from the user such as [Book Title, Book Author, Book Classification, Publish date, Notes, Book Language ]. So first let’s design the form..

1. Open the Books sheet
2. Change the color of the range(B6:E24)
3. In Cell B6 write “Select a Book to Edit or Delete”, Color and format it as you want.

4. In Cell H6 write “Books Form”, Color and format it as you want.

5. Color and format the Range (B6:L26) as you want.
6. Create three rectangular shapes as New, Delete, and Save buttons.
7. Create another three small rectangular shapes write “+” inside them.
5. We need to create a ListBox name it “books_ListBox 4”.
6. Arrange everything as in the image.


Now move to the “setting” sheet and write the following: B4:Books, B5:current_book, C5:1, B6:mode, C6: edit.

Then in the “Data” Sheet starting from A1 write the following:
A1:Books Data, B1:BookTitle, C1:book_author, D1:class, E1:Published, F1:Note, G1:lang
A2:ID, B2:Title, C2:Author, D2:Class, E2:Published, F2:Note, G2:language

CODING:

To copy the list of the Books we have into the books_ListBox 4 we create:
1.1 From the Menu go to Formulas and click on Name Manager.
1.2 From the pop-up screen click on New, then write books_list in Name, and =OFFSET(Data!$B$3,,,COUNTA(Data!$B:$B)) in Refers to.

2.1. Select books_ListBox 4 on the Books sheet.
2.2. Right-click the mouse, and select FormatControl.
2.3. Goto Control Tab, and in Input range write: books_list, and in Cell link write Setting!$C$5 then press OK.

Now the listBox will contain the Books we have in the Books table in Data Sheet. (If we have any Data there)
3. Data Validation: We need to create Data Validation-list in the cells K12: for Authors list, K14: for Classifications list and K18: for Language list.
1. Select K12, from Data-menu click on Data-validation, select List then in the source type this: =OFFSET(Data!$K$3,,,COUNTA(Data!$K:$K))
2. Select K14, from Data-menu click on Data-validation, select List then in the source type this: =OFFSET(Data!$P$3,,,COUNTA(Data!$P:$P))
3. Select K18, from Data-menu click on Data-validation, select List then in the source type this: =OFFSET(Data!$M$3,,,COUNTA(Data!$M:$M))

book_new_Click() In this function we will Clear all cells [k8, k10,k12,k14,k16,k18, K20] also the note_TextBox1 and will change the cell C6 in Setting Sheet to “new”. Here is the code..

Sub book_new_Click()

‘ Clear all cells.
Sheets(“Books”).Range(“K8”).Value = “” ‘ID/number
Sheets(“Books”).Range(“K10”).Value = “” ‘Title
Sheets(“Books”).Range(“K12”).Value = “” ‘Author name
Sheets(“Books”).Range(“K14”).Value = “” ‘classification
Sheets(“Books”).Range(“K16”).Value = “” ‘published date
Sheets(“Books”).Range(“K18”).Value = “” ‘language
Sheets(“Books”).Range(“K20”).Value = “” ‘note
Sheets(“Books”).note_TextBox1 = “”

‘ change book mode to “new”
Sheets(“setting”).Range(“c6”).Value = “new”

Sheets(“Books”).Range(“K8”).Select

End Sub

now in the Books sheet select the button “New” we create and assign the “book_new_Click” macro to it.

book_save_Click() The Save function will have tow parts, if the user click on New then we will have:

Sheets(“setting”).Range(“C6”).Value = “new” in this case we will copy all the Book Data from Range(“K8”),Range(“K10”),Range(“K12”),Range(“K14”),Range(“K16”),Range(“K18”) and the value of the note_TextBox1 to the Data sheet under Boos Table, then will empty all the range in the book form, also will pop-up a MsgBox ” One New Book has been Added.”.

if Sheets(“setting”).Range(“C6”).Value = “edit” in this case we will get the current selected book location by selected_book = Sheets(“setting”).Range(“C5”).Value + 2 then re-copy the book data from the form to the Book Table in the Data Sheet and pop-up MsgBox ” One Book Data has been Updated.”.

In Books form we have also three + buttons next to Author, Classification and Language cells, if the user did not find say the Author in the list then he/she can add new one by clicking on the +

Edit Book Data: The user can select any Book from the Book List on the left-hand list then it’s Data will show-up in the form, the user then can change any of the Book-Data and press on Save.

book_delete_Click() The user will select the Book to de deleted then click on “Delete” button, a massage will pop-up to make sure that Book will be DELETED, if the user confirm the cation (press OK) we will run this line of code:

‘To get the book row number.
selected_book = Sheets(“setting”).Range(“C5”).Value + 2
‘To delete the book row
Sheets(“data”).Range(“A” & selected_book & “:G” & selected_book).Delete Shift:=xlUp

Pressing the (+) button: We have three (+) buttons in this form to add New Authors, Classifications, and Languages if not exist in the list; for example, if the user couldn’t find the Author of the Book (he/she want to enter to the system) pressing the (+) will pop-up a dialog box to Enter New Author and the same for classification and Language. Here is the code..

Sub book_form_new_author()

Sheets(“Books”).Range(“K12”).Value = “”
new_author_name = InputBox(“Enter a New Author Name and Click OK:”, “:: New Author :: “)

‘if we add new author then save it.
If new_author_name > “” Then
‘ Get next empty row
next_row = Sheets(“Data”).Range(“K” & Rows.Count).End(xlUp).Offset(1).Row
Sheets(“Data”).Range(“K” & next_row) = new_author_name
Sheets(“Books”).Range(“K12”).Value = new_author_name ‘Author name
Sheets(“setting”).Range(“F6”).Value = “still”

‘ To Sort the Authors list
next_row = Sheets(“Data”).Range(“K” & Rows.Count).End(xlUp).Offset(1).Row
Sheets(“Data”).Range(“K3:K” & next_row – 1).SortSpecial SortMethod:=xlPinYin

End If
Sheets(“Books”).Range(“K12”).Select

End Sub


End of Part-4

Recap this part:
1. We Create the Books header Tabke.
2. We Create a form to collect the Books from the user.
3. We Create the Books ListBox.
4. We wrote the VBA code to Save, Delete, and Create New Book also to retrieve the Books information into Books ListBox.
5. We let the user to Enter New Author, classification, Language into the system through a dialog box.


:: Library System with Excel ::

Part 1 Part 2 Part 3 Part 4 Part 5



To Download EXCEL (.xlsm) files Click-Here




Follow me on Twitter..




By: Ali Radwani