Day 07 – Beautify Your Introduction with Escape Sequence

How are you doing? Is that hard to learn Python? How do you feel about programming language? Like you, I’m an absolute beginner in Python and nobody surely knows me. If you have ever followed and very much paid attention to my writing style on my another tech blog, you may have an answer on who I am. Alright don’t mind that. As long as you find something helpful to you in NBKM blog, that’s my pleasure.

If you happen to find this post from Google or Bing, I bet you never read my series I write in a daily basis.  Let’s get started with the Python 101 Series.

For those who have been following my series, I’m going to with you write a beautiful paragraph of code. That’s not just aligned horizontally lines of output you have practiced so far. You are going to learn escape sequence right away!

When it comes to a beautiful paragraph, a long sentence is hard to read even you can. Normally you need to start a new line in a paragraph. In Python, you can achieve such a goal by using \n. Look at the below example:


hobbies = "football\nswimming\nreading\ntravelling"

print hobbies

After executing the code, did you realize that you had 4 lines in the output? The interpreter understands that you want to break the output into 4 lines, starting with football, using \n. We call \n is an escape sequence.

Imagine if you need to have a function like you press TAB when typing on Microsoft Office Word? Look at the below example:


print """
My hobbies are:
\t* Soccer
\t* Swimming
\t* Reading
\t* Phography
"""

py_tab

\t is another escape sequence to make your output more readable. There are many other escape sequences but right now I only need \n and \t. If you need to know more, go read this article.

Advertisements

Day 06 – Variable 101

Good morning every body! I hope you are reading this post as you love my writing style for absolute beginner in learning programming. It’s not the first time I learnt a programming language. It’s surely the first time I’m learning Python which I’m serious. That’s why I need to memorize and practice myself by just writing here and in an editor, namely Atom.

There is not a new thing to learn in this post. You are not going to learn any new formatter, or a new way of writing code. This post is going to give you some of the practical use of variable I’ve learnt from the Python course from University of Michigan.

A variable is a named place in the memory where a programmer can store data and later retrieve the data using the variable “name”. Programmers have their choice to chose the name of their variables.

A variable must start with a letter or underscore (_). For example, in previous posts we used my_hair, my_eyes, my_weight…etc.

A variable is distinguished by case sensitive. For example my_hair is different from my_Hair. Try with the below one to test:


my_hair = "black"
my_Hair = "red"

print my_hair
print my_Hair

When you name your variable, you should start with a letter or underscore rather than a number. For example:

  • Good: _intro, _acc, my_account, my_hair, _house
  • Bad: #intro, 1intro, 1.intro

In Python, there are number of reserved words you cannot use for your variable name: del, for, is, raise, assert, elif, from, lambda, return, break, else, global, not, try, class, except, if, or, while, continue, exec, import, pass, yield, def, finally, in, print, as, with. Make sure you memorize all of these reserved words to avoid naming for your variables.

You can assign your variable an expression. Remember in Day 05 post, you created a new variable named income and assigned an expression (salary * 12).


salary = 5000
income = salary * 12

You can also reflect two variables:


my_car = "Audi"
your_car = my_car

print your_car

I think that’s quite enough for me and you right now.

 

Day 05 – Continue Your Introduction

If you follow my serial posts about learning Python for absolute beginner, I believe you now can write a bunch of code to introduce yourself with decimal integer, string and variables. You can also let the interpreter to help you calculate basic maths that you are lazy to do. Today in this article I’m going to introduce one more string formatter which is helpful. You do not need to deeply understand how such a formatter works, or how the interpreters processes to understand your input.

Look at this example:


intro = "Good morning, my name is NKBM. Nice to meet you"
print "%r" % intro

Don’t guess the output. Execute the code then see the output. You will then understand what %r does for you. From the code above, you created a variable named intro, whose value is the long string. And you wanted to print that long string. There is another way like below:


intro = "Good morning, my name is NKBM. Nice to meet you"
print intro

The two outputs are very much similar. The only difference is the bracket. Technically speaking, when you use %s, you are to convert Python object using str(). When you use %r, you are to convert Python object using repr(). Don’t mind to understand if such an explanation gets you confused.

Just think of a software, if you use %r you can’t remove bracket from the output, right? And the %s is used to come out without bracket. With this in mind, %r is often used for debugging that does not display to end user (who uses your software). Vice versa, %s is used to display value to end user. Let’s practice


intro = "I'm handsome!"
not_intro = "I am so weak"

print "%s" % intro
print "%r" % not_intro

Do you understand the use of %r ? Let’s practice with a long paragraphs to get your hands pretty more dirty using everything you have learnt so far.


name = "NKBM"
age = 30
location = "planet"
job = "enginner"
salary = 5000
income = salary * 12
bank_acc = 20000
hair = "black"
eyes = "brown"
height = 165
weight = 65
not_intr = "I still have so many things I can't tell you"

greeting = "Good evening everyone!"
name_intro = "My name %s. I am %d years old. I am living in the %s." %(name, age,location)
job_intro = "I am an %s, receiving %d USD per month" %(job,salary)
bank_intro = "My total asset is %d USD" %bank_acc
intro = "My hair is %s. My eyes is %s. " %(hair, eyes)
intro01 = "My height is %d cm. My weight is %d kg" %(height,weight)

print greeting
print name_intro
print job_intro
print bank_intro
print intro + intro01
print "%r" %not_intr
print "I earn ", income,"USD per year"
#End my code

If your output shows no error then you are done.

Did you realize the line #End my code. Was it executed by the interpreter? Sure it was not. You didn’t see the last line of code in the output. It’s because you use which is used for commenting. In programming, commenting is very important because it helps not only you but also your team understand your purpose of writing. For example:


salary = 5000 #Declare salary per month
income = salary * 12 #Multiply my salary by 12 months
print "I earn",income,"USD per year"
#end my code

You can put # everywhere as long as people will understand your code.  People often put before you write a bunch of code, or beside your declaration (like example above)

Day 04 – Advanced Introduction With Formatter

Good evening every person who are following my blog. I do appreciate your following and hopefully you are interested in with me on the road of learning Python before getting into Data Science area like me. Again, I do not recommend you to follow my serial posts on learning Python. I write here to just keep me practicing the skill of both English and Python. This helps me memorize what I’ve just learnt. If you still read this post until now, I believe you like what I learn and feel comfortable with my writing style.  And do please read my post word by word, from top to the bottom.That’s my humbly pleasure!

I believe now you pretty love programming especially that’s the very first time you type code instead of typical messages to your friends. Before we start Day 04, I recommend you to spend just 15 minutes to practice from Day 01 – Day 03 to be familiar with print, math and variable.

There are two things I would like you to note before Day 04:

  1. Do not start your variable name with number. For example 1st_acc because the interpreter shall throw out the error. Instead, use acc_1st.
  2. Do not use minus when naming variable. For example acc-1st because the interpreter shall understand that the value you declare for acc minus the one assigned to 1st. Instead, use under-character (_) like several examples you have practiced until now.

In this post (or article I often use when writing in my blog), I’m going to do more advanced introduction with formatter. You should be able to understand after then. So look at the code in Day 02.


my_hair = 'black'
my_height = 165
my_weight = 60

print "Hello everyone!"
print "My name is NBKM"
print "My hair is", my_hair
print "My height is", my_height, "cm"
print "My weight is", my_weight, "kg"

What if you need to tell people your hair color but put inside quotation marks? Is that something like?


my_hair = 'black'
print "My hair is black"

You are correct. I promise you I will not tell that you are wrong in this case. But imagine if you need another way to replace “black” inside quotation marks. That’s one of the features in Python. Look at the example below:


my_hair = 'black'

print "My hair is %s" %my_hair

Execute the above and see the output. The %s is called a string formatter. “s” is stand for string. According to Wikipedia,  string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. When you use %s, Python shall look at the right side to pick the first string depending on your order of formatter. For better understanding, run the following example and see the output:


my_hair = 'black'
my_eye = 'brown'

print "My hair is %s & my eye is %s" % (my_hair, my_eye)

The first %s picks the value of the first variable (my_hair) inside the bracket and the second %s picks value of the second variable (my_skin).

What if you don’t define your hair and eyes color? Run the following


print "My hair is %s & my eye is %s" % (my_hair, my_eye)

The interpreter will tell you that you haven’t defined my_hair yet when it reads the first %s. It’s stopped regardless of what you define in my_eye. That’s why you need to tell the interpreter that you have already defined for both variables my_hair and my_eye.

That is the string. How about the number? Well, it’s simply %d. It’s called decimal integer


height = 165
weight = 65

print "My height is %d & my weight is %d" % (height, weight)

Execute the code and see the output. The first %d picked and is replaced by value of the first variable inside the bracket and the second %d is replaced by value of the second variable inside the bracket. You can combine both string formatter and decimal integer formatter. Look at the below example:


car = 'Audi'
no_of_car = 2

print "I have %d %s cars" %(no_of_car,car)

If you turn over the variable “car” into the first place, like below:


car = 'Audi'
no_of_car = 2

print "I have %d %s cars" %(car,no_of_car)

You will get the error below because the interpreter does not accept the string when you are calling for the decimal integer. “str” stands for string

python_error

I don’t mind to know the maximum formatters that we can put inside the bracket. Maybe in the future I will. There are many more formatters supported in Python. However, at this moment it’s better to adopt two types of formatters.

The lesson is about to end.

Day 03 – Do Math with Python

In Day 02, you introduced yourself with print and simple variable. You can write as much as you can to tell the world about you. The key thing is to use variable to reuse it every time you need. More in the future I don’t know when, the lesson perhaps is more complicated with the use of variable I guess. Don’t mind that! This is not the time to look into complex stuffs.

In this post, I’m going to introduce math in Python, and will do some maths with you. First, you don’t need to understand why interpreter works to calculate your math. What you need in this post is to memorize math symbols which are supported in Python, like any of programming languages. Look at the below list:

  • + plus
  • - minus
  • / slash
  • * asterisk
  • % percent
  • < less-than
  • > greater-than
  • <= less-than-equal
  • >= greater-than-equal

It’s not new to you if you are familiar with general math. Let’s practice just a little bit by telling the world that you have two bank accounts. The first account has 10,000 USD and the other has 7,500 USD. Now let’s tell the world the total amount of money you have.

You can quickly write something like

print 10000 + 7500

That’s not wrong but you are required to tell the world about the amount in each account. Remember the variable you used in the previous lesson.


acc_1st = 10000
acc_2nd = 7500
print acc_1st + acc_2nd

When you need to use the value you declare in your variable, make sure you don’t use quotation marks. If the output is 17500 then you are done the math with Python. Just practice a little more and pray to see the sentence “Totally I have 17500 USD” from the output.


acc_1st = 10000
acc_2nd = 7500
print "Totally I have", acc_1st + acc_2nd, "USD"

What about % (percent)? Is that the percentage you often see in math books, for example: I’ve finished 50% of my assignment. It means if the total exercises in my assignment is 20 so I’ve finished 10 exercises. Alright % (percent) in Python is not that percentage. It is just the remaining value when you divide among numbers. For example the remaining value of 5 divide by 2 is 1.  If I give 5 pencils to 2 people equally, then I have 1 pencil remaining. Let’s practice this case that I have 10,000 pencils. I need to give them equally to 74 people. After then how many remaining pencils do I have? Make sure each person has the same number of pencils.


no_of_pencil = 10000
no_of_people = 74

print no_of_pencil % no_of_people

If the result is 10 then you are done. Each person shall have 135 pencils and the remaining is 10. Test by multiplying 135 by 74 then plus 10, with Python and see the result.


print 74 * 135 + 10

More advance, what is the output if I use the following code:


no_of_pencil = 10000
no_of_people = 74

print 10 - no_of_pencil % no_of_people

Or below:


no_of_pencil = 10000
no_of_people = 74
own = 10

print own - no_of_pencil % no_of_people

If you guess correctly then you are done the basic math in Python. Now have a look at each result of the two below code snippers:

 print 100 > 99 

and

 print 100 < 99 

The first result is True and the second result is False. The interpreter just concludes whether your statement is correct. Obviously 100 is greater than 99 then the interpreter tells that you are correct (True). Vice versa, when you tell the interpreter that 100 is less than 99, it tells you that you are wrong (False). The use of less-than-equal and greater-than-equal are similar. Let’s practice just a little bit more:


a = 100
b = 90

print "Is a greater than b?",a > b

The output shall enlighten more about the use of comparison. Can you guess output of the following code snippet:


no_of_pencil = 10000
no_of_people = 74
own = 10

print own >= no_of_pencil % no_of_people

If you are correct I believe you are not familiar with the use of math and basic variable in Python.

If you like to type more Python code, here is what I extracted from the beginning of the lesson 04. Before executing the code, guess in your brain what the output will be.


cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven

print "There are", cars, "cars available."
print "There are only", drivers, "drivers available."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."

You might be curious the following lines of code:


cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven</span>

Don’t worry. It’s just a math. You declare that you have 100 cars and only have 30 drivers. It means the number of cars that cannot be driven is 70. That’s how you do the math for

 cars_not_driven = cars - drivers 

Of course you can write

 cars_not_driven = 70 

However in programming people tend to flexibly use variables and maths as much as possible because they want the interpreter (computer) to help them calculate. Moreover, they will call (reuse) the value later. We will look into such a case in the future.

The lesson in Day 03 is finished now.

Day 02 – Introduce Yourself By Python

If you’ve already finished the very first lesson in Day 01, you must know how to open Python, execute Python code from PowerShell and print out the sentence of your choice. To continue to the previous lesson, today I’m going to introduce myself by writing more sentences than one.


print "Hello everyone!"
print "I'm someone you never know until I tell you"
print "I don't know why I really need Python do I?"

You do not have to use print 3 times. You can use one print but your sentence must be longer than mine. Save and execute your Python code.

Let’s think of a typical introduction of your properties (e.g. your hair color, height and weight). If you never learnt any programming language, meaning you are an absolute beginner, you may type as follows:


print "Hello everyone!"
print "My name is NBKM"
print "My hair is black"
print "My height is 165 cm"
print "My weight is 60 kg"

You are not wrong with this code snippet. You are totally correct. But if you are lazy at typing the color or your hair, the height and weight values? Have a look at another way:


my_hair = 'black'
my_height = 165
my_weight = 60

print "Hello everyone!"
print "My name is NBKM"
print "My hair is", my_hair
print "My height is", my_height, "cm"
print "My weight is", my_weight, "kg"

Save your file and execute your Python code then compare with the previous output. Is there a difference in output? No there is not! In the second code snippet, you firstly tell people about your hair color, your height and weight value before you print out. In print command, you don’t again tell people the value. Instead, you reuse the values you already told. We call this a variable. And any time when you want to reuse these values, you simple need to type the variable name relatively. For example, if I want to tell people my height in a different way, look at the below


my_height = 165
print my_height, "cm is my height"

Note that you need comma between the variable and content inside quotation marks you are going to tell people. Now let’s combine all variables in one sentence:


my_hair = 'black'
my_height = 165
my_weight = 60
print "My hair is", my_hair, "My height is", my_height, "cm", "My weight is", my_weight, "kg"

Is that simple? Sure that’s simple. But people do not like to write a long sentence like this, they break into smaller set of code for better understanding.

The 2nd day is finished!

Day 01 – Just Install And Write The Very First Python

This post is being written early morning when I go to the company then enjoy atmosphere of the spring from a coffee shop. I only have time at evening until mid-night for learning Python so the learning speed would be slow. It also depends on how well I’m, and of course how free as well.

If you happen to read my blog and like my writing style, I do appreciate you. But I don’t recommend you to follow me to learn from what I write here. Perhaps because there are many other much better resources which explain better than me. English is not my mother-tongue!

Well, let’s get started with the very first lesson of Python. Of course, when learning a programming language, you need to install an SDK (Software Development Kit). Other resources call “interpreter” which understands your code and give you the output. Depending on the material you are using for learning, the Python version may vary. I’m Learn Python The Hard Way course to learn, along with my OS is Windows, then I pick Python 2.7 for Windows. I don’t mind to dig into differences between the two versions. If you need an editor which is better than NotePad, go download and install Atom.

After your Python installation, open Atom or NotePad and start writing the very first line of code to print out the message. It’s simple as follows:

print "Hello World!"
print "Do you want to learn Python"

Save it, with the extension is *.py (e.g, Hello.py). You now need to execute the file Hello.py. To do that, open PowerShell, type python Hello.py (make sure you navigate to where the file is located).

py_hello

Ok you are done the very first line of code using Python programming language. You can type as many lines as you like to get your hands weary. This is the first lesson I learnt last night so I’m about  to finish this article here.