Python 3 Programming Basics

Python 3 Basics

Python is the most trending programming language nowadays. Again, in recent years it is the most wanted programming language. Use of Python ranges from daily life scripting to Artificial Intelligence programming. So, there is no good time than this for learning Python programming language. In this article we will try to learn the basics of Python programming with Python 3. To exercise with the codes presented here you can use IDLE that comes with Python or you can use any other editor or IDE you prefer.

Before going further in learning about the language we need to know some fundamental facts about Python programming language. In python we can declare variables without declaring it’s type. A variable is like a container where we store objects – objects are things living in computer memory that have value(s) of some type(s). In Python everything is object. Usually a variable can start with any letter from English alphabet or can start with an underscore. The following characters can be any letter from English alphabet, any digit, or underscore(s). Remember that variable name cannot contain spaces or dashes. From Python 3 you can use unicode characters for naming variables.

Print Function (Previously print Statement)

In programming ‘printing’ something does not mean that you are printing something on paper with a physical printer. Like all other programming languages printing something in Python means that you are showing some text on the console or on the screen.

In Python 2.x print was an statement but from Python 3.x print is a function. So, if you want to show some information programmatically on the screen you need to use the builtin Python print() function. As an example look at the following block of code.

print("Hello world, I am learning Python 3 Basics")

Indentation and spacing

Python is cleaner language than other popular languages. It uses proper spacing and indentation that make it look more beautiful, readable, understandable and above of all more manageable. Unlike other languages you cannot put space or tab randomly here and there – you have to abide by rules.

Indentation is as much important as the Python itself. No python code can run without proper indentation. Try to understand the indentation like following: Indentation is the fixed amount of spacing from left to the start of the code on each line. Indentation has levels. Indentation is increased according to the hierarchy in your code. Hierarchy can be created with if-else statement, with for loop, with the with keyword and some other things. Without just discussing in theory let’s have a look at an example.

age = 70
if age < 70:
    print("I am still strong enough")
else:
    print("I have become too old to keep awake at night and keep coding")

Look at the first line of the example. It does not have any spacing at the start of it. That means it has zero indentation level. But in the second line we are checking some condition with the help of if statement and thus it creates one kind of hierarchy in your code. If the condition succeeds then the 3rd line will run – that means you will see the string printed on the screen. The same happens at line 4 and 5.

You can indent using tab or spaces. You can use 4 spaces for one indentation level, you can use 2 spaces, you can use 1 tab, you can use 5 tabs for one indentation level. But you must remember that you have to keep consistent with what you choose throughout the script. That means if you use 2 spaces for the first indentation in your script you have to use the same in the whole script though you can use different number of spaces or tabs in another script within the same set of scripts. It is recommended that you use 4 spaces for one level of indentation. Tab is not recommended approach as it creates confusion and different system has different width for one tab.

The following code will fail with error as it does not have proper indentation.

age = 70
if age < 70:
    print("I am still strong enough")
else:
  print("I have become to old to keep awake at night and keep coding")

If statement, elif, else

In programming we need to work with conditions a lot. We cannot even imagine programming without conditions. But in programming we cannot talk like human. We have to stick to the system of the specific programming language. In python to express some kind of condition you have to use the if statement. To express an alternative condition you have to use elif and to indicate something that should happen if nothing goes to the level of truth you have to use else. Note: elif means else if.

Imagine you want to develop python console based application that will tell you what you should do today with the following conditions.

1) If today if Saturday you have to go to Ron’s office to discuss on some business plan.

2) If today is Sunday then you can sleep until 12.

3) If today is Friday you can hangout with your friends at night.

4) If today is any other day then you have an ordinary boring routine to follow.

So, let’s implement this in python coding. For now we are supplying today as a variable. When we get more mature in programming we would use some system function to ask the computer what is the day today.

today = 'Sunday'
if today == 'Saturday':
    print("You need to go to Ron's office for discussing some business plans")
elif today == 'Sunday':
    print("You can sleep up until 12")
elif today == 'Friday':
    print("Good news, tonight you can go and hangout with your friends")
else:
    print("Oops, today you have ordinary boring routine. Go get started and finish your boring tasks as early as possible")

Boolean types

Boolean type is a type that either means true or false, yes or no, do or don’t type of things. In programming terminology boolean type is the type that indicates either true or false of some something. In python, to represent boolean values you have two keywords True and False. True and False are object that are of boolean type. Let’s see a very simple example.

a_variable = True
if a_variable == True:
    print("a_variable contains the truth value of boolean type")
else:
    print("a_variable contains the false value of boolean type")

As a boolean type can contain only two type of values we do not need to use elif block for checking whether the variable is true of false.

Int and floating point types

Most beginners think that python is a typeless language but that is not correct. Python is duck typed language. Everything in Python has some kind of type. Numbers in Python also has types. What we know in mathematics by whole number is called int or integer in Python. Number with decimal point in mathematics is known as floating point number in Python. To check the type of any object in Python you can use the built in function type(). Run the following code to check outputs.

a_int = 5 # This is an int or integer
a_float = 3.1416 # This is a floating point number
print(type(a_int))
print(type(a_float))

If you divide an int with a floating point number then the resulting number becomes of type floating point number. If you divide an integer with another integer that results in decimal point number then it becomes a float. If you divide one int with another int or float then also it results in float. Try more complex combinations in your mind.

Literals and Quoting

Literals in Python are the types of values that we put by hand in the source code of python script instead of that being generated or inputted dynamically.

v1 = "Hey, I am a string literal"
v2 = 2 # This is an int literal
v3 = 5.5 # This is a float literal
v4 = [1, 3, 5] # This is an array literal that contains int literals
v5 = {'a': 1, 'b': 3} # This is a dictionary literal

There are some other types of literals in Python too.

In your python program if you want to put string type of value then you need to put a bunch of characters inside quotation marks – the quotation can be either double quote or single quote. If you want to put some special or non-printable character inside string then you have to use a mechanism called escaping. Inside string, escaping is taken place by using backslash. You can literally put single quote inside double quoted string and you can put single quote inside double quoted string. But if you want to put double quote mark inside double quoted string then you need to escape that character with escaping mechanism. The same is true for single quoted string. Clarify your concept by looking at the following example and reading it’s comments.

single_quoted_str = 'Hey I am a string that is encapsulated within single quote'
double_quoted_str = "Hey I am a string that is encapsulated within double quote"
str3 = "the following is a newline\nI am in the second line" # Newline character by escaping n with backslash

None Keyword

In python the keyword None represents nothingness. In our human language we can express nothingness in various ways but in Python there is only one way to express it. If you assign None with a variable then the variable indicates that it has nothing with it.

var1 = None

None is equivalent to null in other programming languages.

For loops

For loop is an iterator loop in Python. By iterating we mean that we go over a collection of things and perform some task(s). For loop in Python is different than for loops in languages like C, C++, PHP, Java, etc. Let’s clarify the concept with an example.

Let’s take a python list as a collection to iterate over and print everything inside the collection. In this example we will take integers as example.

int_list = [1, 3, 5, 76, 12]

for i in int_list:
    print(i)

You can see a new variable introduced called i. When we are iterating over a collection of something and doing some work we need to keep the value we get on each iteration in a variable. Here i is that variable, you name it whatever you like.

Break and Continue

Inside a loop (both while loop and for loop) we may at some point need to break out the running loop or start over the iteration. If we want to exit a loop in the middle of iteration we can use the keyword break but if we want to command our loop to stop working at the current point in the looop and go to the next iteration then we have to use the keyword continue

Let’s say you have a list of integers and when you hit the number 100 you want to stop or exit the loop

l = [1, 4, 67, 1000, 100, 666, 23]
for i in l:
    if i == 100:
        print("As I have hit the number 100 I am going to exit the loop now")
        break
    print("Current number in the iteration is: ", i)
    

Now say you have a list of integers and you want to skip every even number then you can use the keyword continue

l = [1, 4, 67, 1000, 100, 666, 23]
for i in l:
    if i % 2 == 0:
        continue
    print("Current odd number in the iteration is: ", i)
    

Reading and Writing to Files

In python reading and writing file is very easy. Python has a builtin function called open() for opening a file in different modes. The open() functions returns a file object and by using various methods on that object you can read, write and do some other things on the file. As the first parameter of the function you have to provide the file name that you want to open as a string. As the second parameter to the function you have to specify the mode of the function. There are different modes of opening function. As a beginner level learning we will use reading and writing mode only. To open a function in read mode you can provide ‘r’ as the second parameter and for opening the function in write mode you can provide ‘w’.

Let’s say we have a file called info.txt in the directory where you have the following script. Now, we want to read everything from the file and print the content to the screen.

f = open("info.txt", "r")
text = f.read()
print(text)
f.close()

It’s a good practice to close a file after opening it.

Remember that the read() method without any size parameter reads the entire file into the memory. This may result in odd situations. For example if you have 2GB of RAM and you try to read 3GB of file at a time then the program will crash and your device will go to unresposive state for sometime. So, what we do when we need only a portion of data from the file? We can put a size parameter for the read() method.

f = open("info.txt", "r")
text = f.read(2)
print(text)
f.close()

In the above example you will only get 2 characters from your text file. There is one more way to work efficiently that is reading a file line by line. To read a file line by line you can use the method readline(). Every time you call the method you will get a single line in return and when you reach the end of the file you get an empty string in return. See the following example.

f = open("info.txt", "r")
while True:
    line = f.readline()
    if not line:
        break
    print(text)
f.close()

Now we want to write some data to info2.txt file in the current directory.

f = open("info2.txt", "w")
f.write("When you open the file called info2.txt in a text viewer or editor you will see the same set of characters you are reading")
f.close()

That’s all for the Python 3 basic, I hope you will practice with the examples.

Note: this article of mine was also published on: mypythonquiz.com


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *