Posts Tagged ‘function’

Python Project: Properties Maintenance System P6

November 8, 2021 2 comments

Subject: Writing a Full Application for Properties Maintenance System [Add New Property Functions]
Learning : Python, Math, SQL, Logeic

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

This is Part-6 of an Application to Manage Properties Maintenance in this part we will writ a Function to Add New Property to our System.

Add New Property:
This May be the longest Function in our system, we will ask the user to Enter the Data for a New Property and then saving it to the DataBase.

Simple Validation:
In this Function we will do a very simple check on the user inputs, and will keep this as simple as we can so the code will not be long. Sample on this Validation will be if the user enter [E or e] we will exit the process and stop the Function.

Code Part Sample:
In asking the user to select the property Type were we are using a look-up table for the Property Types, we will use the Function def get_lookup_values(tname,t_id,key_id): were we passing the table-name, the ID column name and the ID of the data we want to retrieve. Another code part we may see is checking the user input of the p_type_id (MUST BE NUMERIC)

if (p_type_id.isalpha()):
input(‘\n You Must Enter a Numeric Value. Press any key to Try Again .. > ‘)
Also we can see the part of the code that will make sure that the user did not enter the [E to Exit] (if the user enter E we will display a message then will return to the Menu-Page)
p_bedrooms = input(‘\n Enter the Number of Bedrooms in the Property. [E to Exit] > ‘)
if p_bedrooms in [‘e’,’E’] :
input (‘\n You Select to Exit .. Press any Key. >’)

Saving the Record:
After the user Enter all the data we need we will display it on the screen and asking for a confirmation to Save the record, If the user Enter [Y] as Yes, we will use the “INSERT INTO properties_t …” SQL command to save the Record to the dataBase.
Here is a screen-shot of the all code of the Function,

python project Properties Maintenance System code by ali radwani doha qatar

NOTE: If you Download this Part you MUST Run the Option 82 (82. Delete the Data-Base and Start Again.) from the Main Menu to do the following Updates:

  • Update the properties_t Table (Adding the number of BathRooms)
  • Update on create_tables Function.
  • Update on insert_zero_records Function.

In Part-7 In the Next Part we will write the Function to Display/Show all the Records of the Main-Property-Table on the screen.

:: PMS Parts ::

Part 1 Part 2 Part 3 Part 4
Part 5 Part 6 Part 7 Part 8

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

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

ali radwani python projects codeFollow me on Twitter..

By: Ali Radwani

Python: Generate your Data-Set

August 8, 2021 1 comment

Learning : Python, pandas, function
Subject: Generate your CSV dataset 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.]

The Story:
last week i was reading about Data Cleaning, Deep Learning and Machine Learning, and for all we need some data to play with and testing our code. There are several sites providing a free (to certain limits) Data-set. But while i was working, it just come to my mind Why not to write a code to generate some Fake data-set.

Before I start:
The main question was “What is the subject of the data” or Data about What? This is the main question that will guide us to write our code, and tha answer was very..very fast 🙂 .. at that moment I was holding my Coffee Mug, and just jump to my mind, Data about Coffee … Coffee Consumption. So we are taking the data of Coffee Consumption from a Coffee-Shop, the coffee-shop is collecting the following data: Date-Time (of the order), Coffee-Name, Coffee-Type, Coffee-size, Sex, Rank. Here is in more details..

Dat-Time: Date and Time of Order, Date format: dd-mm-yyyy, the Time format: hh:mm (24h)

Coffee-Name: Such as: [black, latte, espresso, americano, cappuccino, mocha, lungo, flat white, irish, macchiato,ristretto, iced coffee]

Coffee-Type: 3n1 , pods, grounded

Coffee Size: samll, medium, large, venti  

Sex: The person how order it male, female 

Rank: if the customer drink the coffee in the shop, will ask for a ranks (1,10) 1:bad, 10:Grate

Scope of Work: We will write several functions to generate random data for each attribute we have, saving the data into a list, then combining all the lists in a pandas dataframe df and save the data_set df to a csv file. Later on we can re-call the file using pandas command df.read_csv(file_name) and manipulate the data.

.::.. Coding ..::.
Let’s start with Date-Time Function: def fake_date_time(from_y,to_y): In this function we will use a random.randint() to generate numbers for day’s, months and years, also for hours and minites. The function will take two arguments from_y, to_y and will return a string like this: dd-mm-yyyy hh:mm … here is the code ..

ali radwani python code project

Now,Coffee Name: def fake_coffee_name() : for Coffee Name I create a list of Coffee Names (from the net) and use random.choice(coffee_name_list) to select one from the list. this function is a one-line code .. here it is ..

 # fake_coffee_name() function

def fake_coffee_name() : 
        Function to randomly select one from the list. 
        Return coffee_name 
    coffee_name_list = ['black', 'latte', 'espresso', 'americano', 'cappuccino', 
                         'mocha', 'lungo', 'flat white', 'irish', 'macchiato', 'ristretto', 
                         'iced coffee'
    return random.choice(coffee_name_list) 

Here are another two Functions def fake_coffee_type(): and def fake_coffee_size(): Both are using the random.choice to select from a list.. here is the code ..

]ali radwani python code project

More over, in out dataset we need another two variables sex and rank, both are simple and we don’t need to put them in separate function, we will call the random.choice(‘f’,’m’) to select between Male and Female, and random.randint (1,11) to select a Rank between (1 and 10). Here is the main part of the application, we will use a for loop and append all the returns from the function’s in a list (a list for each attribute) after that we will combine all the list in a dataset using pandas command. Here is the code..

 # Main body of the application

# empty lists of the columns
d_d =[] 
cn_d =[] 
ct_d =[] 
cs_d =[] 
s_d =[] 
r_d = [] 

number_of_rows = 1000 

for x in range(1,number_of_rows): 
    r_d.append(random.randint (1,11)) 

the_data ={'date_time':d_d, 'c_name':cn_d, 'c_type':ct_d, 'c_size':cs_d, 'sex':s_d, 'rank':r_d } 

df = pd.DataFrame (the_data) 

# to create a CSV file and save the data in it. 
file_name = 'coffee_consumption_v1.csv'
df.to_csv(file_name, index=False)

print(f'\n\n    The data been generated, a file named: {file_name} saved')

Now we have a file called: coffee_consumption_v1.csv saved in the same directory of the .py code file. Here is a sample of the data.

ali radwani python code dataset

We will stop here, and we will do another post to apply pandas commands over the dataset.

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

To Download my Python code (.py) files Click-Here
Also the Date-Set coffee_consumption_v1 file (.csv) files is available in the same page.

ali radwani python projects codeFollow me on Twitter..

By: Ali Radwani

Excel, VBA Codes and Formulas-1

March 8, 2020 7 comments

Learn To : In Excel – Drop Down List in a cell.

I start working on a project for a friend, he has some requests to be done on a MS-Excel, so I thought why not to write several posts about MS-Excel capabilities.

MS-Excel is a great application to be used, I will not write to praise the program, but will jump to coding. In Excel we can use dozens of built in ready to use tools and Formulas. Also MS-Excel has a very good, easy to use and learn programming language called VBA (Visual Basic for Application) which with simple code we can perform some tasks and create Menus, buttons and functions that runs in background.

Starting from this post we will use some built-in functions and VBA’s one that I am using in my Excel files.
So let’s say we have a table that has a column called “Pay-Method”, the value we save in this column always is one of three: “Cash, Card, Cheque” we don’t want the user to type it every time, but to select it from a list.

To do this we can use an static approach or a Dynamic approach.

Static Approach: if we have a specific answers that can’t be more like (Yes,No) or as our example above (Cash, Card, Cheque) or similar cases then we can use an static approach. So First Select First cell in the Table, from the menu we will select “Data” then “Data Validation” and select Data Validation.


  • From the Allow box, we select List.
  • Then in Source box, we need to type the items we want to appear in each cell as a drop-down list separated by a comma. Cash, Card, Cheque
  • We need to check [Ignore Blank and In-cell Dropdown] Then Click OK.

Now we will have a small arrow on the first cell in our Table, to copy the List to other Cells (Beneath) hold the small DOT and Drag it down.

And Now we are DONE, we just create a Dropdown List in all “Pay-Method” Column in the table..

Dynamic Approach: If we have a list of items and this list is growing (We may add more items ti it), such as Fruit list in a grocery, then we will use the Dynamic drop-down list.
In this case I prefer to use a new Excel Tab call it “Setting”, so we will create one. On that Tab create a Table call it “Fruit” and list all the fruits you want to be appear in the drop-down cell list (In this example I will list down F1, F2, F3, F4, F5), Select the table and from Menu select “Format as Table” and just chose any format you want. Here is a screen shot.

Here is a screen shot

Move the Mouse next to table head until you get small Arrow, and give it a name. as in here..

Now go-back to our main Table and using the same way we did in the Static Approach (from the menu we will select “Data” then “Data Validation” and select Data Validation.) AND

  • From the Allow box, we select List.
  • Then in Source box, we need to type the Name we select for our table “F-Table_1” for the fruit table
  • We need to check [Ignore Blank and In-cell Dropdown] Then Click OK.

Done … Now if we add new Fruit to the list “F6” it will appear in our Drop-Down cell list.

🙂 Have Fun ..

Follow me on Twitter..

By: Ali Radwani

Python: My Fake Data Generator P-1

December 11, 2019 Leave a comment

Learning : Python: Functions, Procedures and documentation
Subject: About fake data P-1

In the last post (Fake data-set) we play around with a library called “Faker” and we saw that we can call several functions to generate a fake data such as names, dresses, jobs and others. Once you use this you can figure out that a lot of data are random, some time they are random from a list or say a file. So as we are in learning sessions i thought it is a good idea if i start to write “My Fake Data Generator” functions, There is one thing that we (say I) have to consider; that’s the people behind “Faker library” are professionals and are a team not ONE person, there experience in writing codes and documenting thing are away better than whatever we will do,
BUT the goal of this task is to coding, coding and coding.

So what are the functions that we will try to write? Here we will list down the functions that we will work on, this list will grownup as we working so it is not limited to that ever written now. Also i will try to do documentation for the functions so later if we call help() function in Python and pass a function name, we will get something from there. So let’s start and see the list of functions we will work on.

Function Name Description
color To return a random color code in RGB or hex.
Date To return a random date.
Mobile To return a mobile number.
Country To return a random country name.
City To return a random City name.
ID To return 11 random dig as ID.


So first one we will start with is “color”. Color function will return a value that present a color code, this number may be in decimal or hexadecimal, the function will take one argument (type) if type = d or D then the code will be in decimal, if type = h or H then the code will be in hexadecimal, if nothing passes then default will be hexadecimal.

First we need to import random

 # Generate FAKE color code.

def fcolor (t='h'):
    This function named 'fcolor' will return a value that present a color code.
    Function will take one argument str (t), if t = 'd' or 'D' color code will be in RGB,
    if t = 'h' or 'H', color code will be in Hex,

    if nothing passes default color code will be Hex.

        r,g,b = fcolor ('d')
        c = fcolor ('h') or  c = fcolor ()

    Argument: str : t

    return: ccode: list if RGB, str if Hex
    ccode =[]

    r= random.randint (0,255)
    g= random.randint (0,255)
    b= random.randint (0,255)

    if t in ['d','D'] :
        return ccode
        # To convert the RGB color to Hex.

        for each in [r,g,b] :
            num = each
            while num > 0 :
                hexr = num % 16
                if hexr < 10 :
                elif hexr == 10 :
                elif hexr == 11 :
                elif hexr == 12 :
                elif hexr == 13 :
                elif hexr == 14 :
                elif hexr == 15 :
                num = int(num / 16)

            for x in cl :
                co = str(co) + str(x)


        for x in ccode :
            cc = str(cc) + str(x)
        ccode = cc

        while len(ccode)-1 < 6:
            ccode = ccode + '0'

        return ccode

 # Calling the function 3 times.
r,g,b = fcolor ('d')
print('  Color code as int RGB: ',r,g,b)
print('  Color code as list RGB:',fcolor ('d'))
print('  Color code as str Hex:',fcolor ())


  Color code as int RGB:  47 202 248
  Color code as list RGB: [59, 132, 99]
  Color code as str Hex: #85B060

This is the fcolor “Fake color” function, next post will be about the random ID number and what if we want it to be meaningful.

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

Follow me on Twitter..

By: Ali Radwani