Python: Introduction III

The last part of the Python Introduction and I will cover topics on functions, methods and the packages in Python. For sure, there is a difference between function and method. I revisit my original post which I wrote about the differences between functions and methods. You can read up those before continue here.

User-defined Functions

The simplest way I can explain what is function which I wrote in my original post:

A function is a block of code to carry out a task and it calls by its name. All functions may have zero or many arguments. The arguments are passed explicitly (directly). On the exit of the function, it may or may not return value or values.

There are some examples in this post to explain about functions, how to define a function with and without arguments, uses default value for an argument, uses flexible arguments *args and **kwargs and uses of return statement in the function.

Methods

It is like a function, except it is attached to an object (dependent). A method is implicitly (indirectly) passed to the object for which it is invoked. It may or may not return a value or values. The method is accessible to data that is contained within the class.

For methods examples, I wrote it in this post.

Packages

Think the packages as a directory of Python scripts. Example each .py script is a module. This module specifies functions, methods and types in solving a particular problem. I found a link which explained in detail about packages in Python. Refer here for more reading.

In this part III, I know there are many external links are given, mainly is to reduce re-write of those entries which I wrote them sometimes ago. This blog serves as a place to find the relevant resources for reading and examples which I think it is enough to cover the basic understanding of the functions, methods and packages in Python.

Python: Introduction II

I continue from the Python: Introduction which I wrote it yesterday and it gave the very basic idea of how Python is in term of declaring variables, the data types and how we can store the data in a collection. So. variable, data type and collections. If you missed out or cannot recall them, here is the link to yesterday’s post. There are links to various data types and the collections. I did not want to repeat here.

For the part 2, I have decided to concentrate on writing the introduction to control flows. I think it will be great to have these control flows being taught first before we head to more Data Science orientated topic such as using the package called Numpy and creating our own functions and methods. So, I swapped a little bit in term of syllabus or topic in my writing.

if, elif, else

It is a conditional statement which we can use to match certain conditions. There are few methods to write this statement and it is not always that we need to use elif and else. Let us look at this syntax below:

if condition :
  expression

This syntax has 1 single condition to match only, that is why “if” is being used. Example:

z = 4
if z % 2 == 0 :
  print("z is even")

All control flows has a standard syntax and indentation applied to each of them to mark the beginning to the expression or what should it does when the condition is matched. Therefore, you can see the print() statement is slightly indented. In most IDEs, it is automatically indented when we use the colon (:) sign after the condition, in this case, z % 2 == 0.

The moment we have 1 more condition in our code, if else statement is used. See the syntax below:

if condition :
  expression
else :
  expression

In the else statement, often we do not need to specify the condition within the line because it is understood that when the if statement or condition did not match then it goes to the else statement and execute the code. It looks as though else statement is a default statement. I know in some other programming language, it does have default statement at the end of else statement which say, anything not matches then run default statement.

We can omit this else statement when we do not require to process anything if the first condition does not match. However, sometimes, we might miss out important scenarios of the if statement is skipped. What I meant here is besides being legit that the condition does not match, there is also possibilities of exceptions happened while checking through the conditions. It is recommended to use the else statement as an exception handling, either print out a line in the console or log file. This helps in the debugging procedure.

z = 5
if z % 2 == 0 :
  print("z is even")
else
  print("z is odd")

The above is an example of using if-else statement when there are two conditions, either-or situation. The variable z is 5, hence it goes to the else statement and print out “z is odd”.

Next, if-elif-else statement is used when there are few conditions in the scenario which one may get matched during the condition checking. When the first condition does not match, it goes to the next elif condition to check until it has no matches, it will end at else statement. You can have many elif statements in your codes. Below is the syntax:

if condition :
  expression
elif condition :
  expression
else :
  expression

Example of using the syntax:

z = 3
if z % 2 == 0 :
  print("z is divisible by 2")
elif z % 3 == 0 :
  print("z is divisible by 3")
else :
  print("z is neither divisible by 2 nor by 3")

The output is z is divisible by 3. After each expression, the statement terminates and returns the result. It will not proceed to check whether next condition is matched. With these 3 examples, I hope it gives some ideas about if statement, if-else statement and if-elif-else statement.

while

while statement works by repeating an action until condition is met. It is important to assess the code before running the while statement because if any chances the condition is not met, the statement will keep running and this we call it infinite loop. You have to force to end the application manually. The syntax for while statement:

while condition :
  expression

Example of using the while syntax:

x = 0
while x < 5:
     print(f'The number is {x}')
     x += 1  

The most crucial part here is the variable x which works as a counter to ensure the condition is met. Without this line of code (x += 1 ) the condition is always true and the loop becomes infinite.

This is the output from executing the while statement. When x = 5, it stops and exits from the while statement and does not print out anything.

for

Remember in the previous blog, I mentioned about using Python list (collections)? For statement is a good control flow to iterate (repeat) through the Python list to get each element.

for var in seq :
  expression

Without using for statement, we might want to repeat few times of the print statements to print out the elements inside the Python list below:

fam = [1.73, 1.68, 1.71, 1.89]

print(fam[0])
print(fam[1])
print(fam[2])
print(fam[3])

Although this is a correct syntax, it is not a good practice. Below demonstrates how to use a for statement to iterate through the Python list and print the values out.

for height in fam :
  print(height)

Both of the codes returns the same output.

1.73
1.68
1.71
1.89

For statement works well for any types of collections or even with a string. Below example uses my_string as the “list” and a variable character as the “item_name” to represent the elements inside the list. One by one, it prints out each character in the my_string.

In for statement, we can use the enumerate(), a Python built-in function. enumerate() method adds a counter to an iterable and returns it in a form of enumerate object. This enumerate object can then be used directly in for loops or be converted into a list of tuples using list() method.

Why is enumerate return a tuple?

When enumerate() returns in a form of enumerate object, it comes in a form of index, value. It is because enumerate() accepts start parameter which is the index value of the counter, by default it is 0. A simple illustration is as below:

enumerate(iterable, start=0)
list = ["eat","sleep","repeat"] 
print(enumerate(list)

When we check the output from the console, it shows as below:

[(0, 'eat'), (1, 'sleep'), (2, 'repeat')]

It starts with an index 0, of course, it can be changed with indicating the index value, such as enumerate(list,1), then the index begins with 1 instead of 0. This enumerate() function may look useful when we want to list the elements from the collections with the index and value.

fam = [1.73, 1.68, 1.71, 1.89]
for index, height in enumerate(fam) :
  print("index " + str(index) + ": " + str(height))

Reusing the above example and now, we have added enumerate(fam) in the for statement instead of using “for height in fam”. Then, in the print() statement, we convert the index value and height value to string and concatenate them. This maybe useful when we want to print out our shopping cart’s items list. Its output shows:

index 0: 1.73
index 1: 1.68
index 2: 1.71
index 3: 1.89

Mastering the use of the control flows can help in the later stage when we go into the data structure section. I have written separate blogs about if-else statements, while and for loops, you can refer to the links below:

Python: Introduction I

It has been a while I stopped learning Python from DataCamp due to my part time classes and assignment, and work commitment. It is not easy to keep track each of them everyday. On top of it, I still have my volunteer work with TechLadies and regularly have to meet up to brainstorm and updates each other.

Today’s topic is very much on Python, definitely. I want to concentrate on my writing in Python for next 2 weeks before I head off for an holiday. I am sure, I will be lazy after my break. It would be great if I can write up something to summarize or reorganize what I have been writing for the past few months on my Python’s learning using DataCamp and Udemy.

Remember my very first day I started learning Python using Udemy, it taught about the installation and I went on to install IntelliJ. Till to date, I hardly using it, most of my time, I am using the online version of Jupyter Notebook. I find it pretty easy to be used. I understood that there are many other IDEs in the market and there is no specific software to be used to code Python. For now, I will just keep it simple for my learning.

How to begin?

After the installation of the python 3, I open the terminal (in Linux) or command prompt (Windows) to go into the Python’s shell by typing the following command:

python

From the terminal or command prompt screen, I can see a return message from Python with the version number. There are Python 2 and Python 3. So, be clear on which version is being used on the machine because the syntax are slightly different from each others.

Checking version

On the very first time, we always want to know if everything we installed for Python works or not. Checking the version, if it is updated, latest and correct version to be used is first time we might want to do with:

python --version

Simple open up your terminal or command line to type the above command on it. On the screen, it may return you the version info such as below:

Python 3.7.0

print(‘Hello World’)

Next, we always start with simple print statement using the built-in function named print() to print out some lines, most often we will print in our first line is “Hello World”. Really, most people who first started learning programming language will have this line printed. I use this function everywhere in my coding and it is very useful. It is just same as the PRINT statement from the SQL server, if you are coming from database background. Using single quote or double quote is not a matter.

print('Hello World!')
print("Hello World!")

Variables and Types

Then, we touch on the variables and types, the important component in most programming languages. Variables and types are interrelated. I discussed about the characteristic of a variable in my first post. Let me have it here too!

  • Specific and case-sensitive name, best practice to use lowercase.
  • Define things that are subject to change.
  • Can be used to store texts, numbers or dates.
  • Cannot start with number.
  • Cannot use space  and symbols in the name, use _ instead.

Then, there are plenty of different data types as well, yes, that is the types I meant here. Remember, different types have different behaviours. I wrote many posts about each of them before. I will link them up whenever we re-visit the topic.

  • Boolean operations: and, or, not (True, False)
  • Numeric types: int, float, complex (number, decimal)
  • Text sequence type: str (string)
  • Sequence type: list, tuple, range
  • Mapping type: dict 
  • Sets type: set
  • None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. It is a null value or no value at all which is different than empty string, 0 or False.

The simplest way to demonstrate how we can create a variable and assign a value to it.

height = 1.67
weight = 180

name = 'Joanne'
gender = 'Female'

isStudent = True

The above shows the height and weight variables in float and int data type, then we have name and gender in string and a variable called isStudent with a Boolean value. In Python, it does not require to declare a variable with any prefix in front of or behind the variable which we can see in Javascript or SQL Server, if you are familiar with those languages. Then, you may ask how does compiler (computer) knows it is of what type of data types.

What is the difference between (=) and (==)?

The single equal sign (=) assigns the value on the right to a variable on the left whereas the double equal sign (==) tests if the two things have the same value. The two things can be a comparison of two variables or a variable with a math operator.

type()

type(height)
type(weight)
type(name)
type(isStudent)

type() is a built-in function which allows us to check the data types of the variables we created with assigned values. type() helps to answer the above question.

That completed the fundamental and basic to code in Python. Now, you know how to do the following:

  • use the print() statement to print texts.
  • use of variables and data types.
  • use the type() statement to print out the data type of a variable.

Probably, now you want to know what is integer, string, Boolean and etc. I have some links here to help out the basic explanation together with examples:

To talk about numbers and strings, it can be another topics by its own as there are many interesting about them such as the use of (+) sign. It is concatenate sign which means it combines two or more variables of same type together. The way number and string use (+) sign also difference than each other. Also, we have to remember that in Python, string and integer cannot use of (+) sign together. It throws exception (error). Exception is a programming jargon means error. There is a topic of exception handling in Python too. In this case, there is string formatting and integer formatting.

Let us move into fundamental part two, Python List.

Python Collections

It is an interesting topic and important part in Python. Almost everyone of us will use Python List in our daily coding life 🙂 It is a collection of values and allows to have different types within the elements, one of the most simplest and easiest collections. When it comes to the word “collection”, Python has four type of collections.

You can read more about the basic of these collection here. Each of them has different characteristics, syntax, structure and usage. Along the way, we use different collections to explain the Python codes and concepts. Below is an example of how list looks like:

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

Declaring a list is same as declare a variable, it just requires to follow the list’s syntax to create one. As mentioned earlier, it can be any data types in a list. So, you can declare a list as below too:

family = ['Anna', 1.73, 'Eddie', 1.68, 'Mother', 1.71, 'Father', 1.89]

We can use the lists above to work with control flows, going through the iteration and/or condition checking, then calculate a value and return a result. I think I will cover it in the next post.

Up to now, this portion is still a basic Python and does not involve any analytics or data science work if you are looking for one.

MongoDB: The Best Way to Work With Data

Relational databases have a long-standing position in most organizations. This made them the default way to think about storing, using and enriching data. However, modern applicants present new challenges that stretch the limits of what is possible with a relational database. Relational database uses tabular data model, stores data across many tables and links by foreign keys as the need to normalize the data.

Document Model

In contrast, MongoDB uses a document data model and presents data in single structure with the related data embedded as sub-documents and arrays. Below JSON document shows how a customer object is modeled in a single document structure with embedded sub-documents and arrays.

Flexibility: Dynamically Adapting to Changes

MongoDB documents’ fields can vary from document to document within a single collection. There is no need to declare the structure of documents to the system – documents are self-describing. If a new field needed to be added into a document, the field can be added without affecting all other documents in the MongoDB, unlike relational databases, we need to run the ‘ALTER TABLE’ operations.

Schema Governance

While MongoDB allows flexible schema, MongoDB also provides schema validation with the database, from MongoDB version 3.6 and above. The JSON schema validator allows us to define a fixed schema and validation rules directly into the database and free the developers to take care of it from the application level. With this, we can apply data governance standard to the schema while maintaining the benefits of a flexible document model.

Below is the sample validation rule,

db.createCollection( "people" , {
   validator: { $jsonSchema: {
      bsonType: "object",
      required: [ "name", "surname", "email" ],
      properties: {
         name: {
            bsonType: "string",
            description: "required and must be a string" },
         surname: {
            bsonType: "string",
            description: "required and must be a string" },
         email: {
            bsonType: "string",
            pattern: "^.+\@.+$",
            description: "required and must be a valid email address" },
         year_of_birth: {
            bsonType: "int",
            minimum: 1900,
            maximum: 2018,
            description: "the value must be in the range 1900-2018" },
         gender: {
            enum: [ "M", "F" ],
            description: "can be only M or F" }
      }
   }
}})

So, it is possible also to implement the validation rules to the existing collections? The answer is we just need to use the collMod command instead of createCollection command.

db.runCommand( { collMod: "people3",
   validator: {
      $jsonSchema : {
         bsonType: "object",
         required: [ "name", "surname", "gender" ],
         properties: {
            name: {
               bsonType: "string",
               description: "required and must be a string" },
            surname: {
               bsonType: "string",
               description: "required and must be a string" },
            gender: {
               enum: [ "M", "F" ],
               description: "required and must be M or F" }
         }
       }
},
validationLevel: "moderate",
validationAction: "warn"
})

Having a Really Fixed Schema

MongoDB allows the additional fields that are not in the validation rules to be inserted into the collection. If we would like to be more restrictive and have a really fixed schema for the collection we need to add the following parameter in the validation rule,

additionalProperties: false

The below MongoDB script shows how to use the above parameter.

db.createCollection( "people2" , {
   validator: {
     $jsonSchema: {
        bsonType: "object",
        additionalProperties: false,
		required: ["name","age"],
        properties: {
           _id : {
              bsonType: "objectId" },
           name: {
              bsonType: "string",
              description: "required and must be a string" },
           age: {
              bsonType: "int",
              minimum: 0,
              maximum: 100,
              description: "required and must be in the range 0-100" }
        }
     }
}})

Speed: Great Performance

For most of the MongoDB’s queries, there is no need to JOIN multiple records. Should your application require it, MongoDB does provide the equivalent of a JOIN, the $lookup which was introduced since version 3.2. For more reading, you can find in this link.

I will stop here for now and shall return with more information in my next write up or I will continue from this post. Stay tuned.

Old Chang Kee

On the Raya day, I went out to Bugis and stopped by at Old Chang Kee in Bugis Junction to get a curry puff. It has been very long I did not eat their curry puff and they are selling few other favours too, one of it I saw was the nasi lemak puff. It does look odd to me to give myself a try. So, I decided to try their chicken puff, away from the traditional curry puff. For something non-spicy, this chicken puff definitely is a good choice. Inside the puff, it is filled with generous ingredients and the savoury taste of the sauce made it tasted good.

And that made me think of the days when I was working in Tampines and I walked across to the Century Square to get a pack of chicken porridge as my breakfast.

Finally, I did that this morning, I bought a pack of chicken porridge with a bag of yaotiou. It is a traditional Chinese breakfast to have porridge in the morning. I felt it was a blessing that Old Chang Kee still selling porridge. It is only available in the morning and always selling fast.

This time, I did not get it from the same old place at Century Square. They have moved since after Century Square renovated. Now, they are at the Tampines MRT station, conveniently located next to the MRT station, along with Cheers at the traffic light.

This is definitely one of the good choices for big and economic breakfast of a day. Do be there early to get your porridge as it is selling fast at times.

Kelly Jie Seafood

Back in February this year, my friend from Perth, Australia came to visit Singapore after her family trip to Japan. We met up at Kelly Jie Seafood is formerly known as Melben Seafood which is located at Toa Payoh. It is her friends’ recommendation to try their crab here.

Seriously, I did not really go for branded restaurants to eat crabs. Since, it was a recommendation, I just followed with my friend’s craving. It was my first visit to Kelly Jie Seafood.

Being the first time visit, I opened up for any recommendations from the restaurant and we chose to try their signature chili crab. I myself always do not think Singapore chili crab is anything nicer than a black pepper crab and sometimes, I do feel that a steamed crab is always a good way to eat.

Besides that, we ordered lobsters cooked with buttery sauce and a plate of fried mantao (little buns) which can dip the sauces.

Overall, I prefer the lobsters over the crab probably also because I did not like the crab’s starchy sauce. The dish got cold very fast under the air-conditioned room and it made the starchy sauce even worse.

The service was a little slow on the day I visited the restaurant. I have no ideas whether it was due to Chinese New Year period or the restaurant simply has so many people eating there. It was crowded and noisy. My friend and I did not manage to spend a quality time chatting there and decided to finish the food and back to her hotel.

Address: Blk 211, #01, Lor 8 Toa Payoh, 11/15, Singapore 310211.

Hand In Hand Beijing Restaurant

You can enjoy a Chinese cuisine at reasonable price and nice ambiance at
Hand In Hand Beijing Restaurant which is located at Jalan Besar. It is quite near to the Jalan Besar Downtown MRT station and easily accessible by cars and public transportation.

My colleague introduced the malaxiangguo dish which is off the menu for this restaurant. For those who do not know what is it, it is a spicy stirred fry pot with a lot of different ingredients. In some places, the ingredients are based on your selections, it can be a combination of vegetables and meats. Usually, for this dish, the cook puts some of the peppercorns which are spicy and numbing together with the chili oils and dried chili to stir fry the ingredients. It has different level of spiciness and different cooks have different level of spiciness too.

For the first time, we tried with little spiciness because we have a colleague who cannot too spicy. It turned out to be quite decent level of spiciness and it went well with other dishes we ordered that day.

To balance out, the other two dishes were fried vegetable and self-hand-made spring roll with minced meat. I am not able to find out what is the English name of this vegetable but yes, it is delicious especially when it cooks with garlic. The portion is generous and it is more than enough for a table of four persons.

Last but not least, the hand-made spring roll with minced meat. This dish is slightly to its plain taste, yet, it goes well with shredded cucumbers and lettuce. The portion of the meat was too much and we were given 6 skins to wrap. Perhaps, they should allow us to refill so that we can have more wraps. In that case, we can omit the white rice.

This restaurant serves xiao long bao as well, but we did not order for this visit. There are various types of xiao long bao and other dumplings in their menu. It is also one of the good to try dishes.

Address: 143 Jln Besar, Singapore 208859.