Python programming language tutorial for beginners

python programming language
Python programming language

Python contents

           If code
           Else code
           Else if code

           While loop
           For loop

           Numbers
           String
           List
           Tuple
           Dictionary

           Define a function
           Calling a function
           Built in function

                  raw_input
                  input
                  open
                  close
                  write
                  read
                  rename
                  remove
                  mkdir
                  chdir
                  getcwd
                  rmdir

Python programming language Introduction

Python is an extensively used high level programming language. Its code is available under GNU. It is an open source, object oriented and interpreted programming language.
Many organizations prefer python over other languages to create applications. Even NASA uses a python based application called WAS (Workflow Automation System) to manage their various projects.

In this tutorial We are going to use Linux to learn python. However, python is not restricted to use in other OS. You can learn python by installing it on other OS as well, like Microsoft Windows or MAC.
These days, python comes with pre-installed in many OS. So, you should check if python is already installed on your machine or not,
Open terminal, type python and enter. If it's installed it should come up with a python interpreter shell as given below.

# python
 Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) 
 [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
 Type "help", "copyright", "credits" or "license" for more information.
 >>> 

To learn about python programming language you can use interpreter or you can create a file with '.py' extension which contains your python code. In this tutorial we are going to use both interpreter and files to run our codes. Interpreters has an advantage because it can be used to read and execute commands interactively.

Python features

Some of the great features of python programming language are.

  • It's based on Object oriented programming (OOP).
  • With the presence of python interpreter, we do not require compiler to compile programs before running it. We can directly run our codes at run time.
  • Python is an open source programming language.
  • Python has a very big library, which is supportable in many platforms like Windows, MAC, Linux, UNIX, etc.
  • Python supports a very big range of databases like MySQL, mSQL, PostgreSQL, Oracle, etc.
  • Python has GUI Programming features.
  • Python can be used as an scripting language for writing scripts.
  • Python programming language is also used for detecting fingerprints in Bio-metrics.

Uses of python in real world

In the real world python programming language is used for many purposes. They are.

  • Python is used in GIS (Geographic information system) programming.
  • Python is used in Web programming.
  • Python is used for software development.
  • Python is used for GUI programming.
  • Python is used for Game development.
  • Python is used in scientific computing.
  • Python is used to create e-commerce system.

Write your first program in python

Till now you have learned about the uses of python in real world and its features. Now, let's learn how to do real coding in python.

In this example we will use interpreter to test our first python program.

To print anything in python the command 'print' is used. Let's see how to print hello.
In your python shell, type the command as given below and press enter.

>>> print "hello"
Output:
hello

Write your first python script

Let's learn how to create a very simple python script file.
Create a file called 'program.py'

$ vi program.py

and insert the following code into it.

print "Hello, How are you?"

Now, run the script as given below.

$ python program.py

It will produce the following output.

Output:
Hello, How are you?

How to store values in variables

The simplest variables types that are used for storing values in python are 'Numbers' and 'String'. To store values in variables equal sign (=) operator is used. The left hand side of the operator is the variable we declare and the right hand side is the value we can assign to the variable.

Example:1

In the same file 'program.py', erase everything inside and insert the below code.

#Number 
variable number = 500

#String 
variable string = "python"
print number 
print string


Before you run the script, you must give the execute permission to the file.

chmod +x program.py

Now, run.

$ python program.py

The output will be.

Output:
500
python


Example:2

You can also assign single value to a multiple variables. Open your python terminal to test the following codes.

>> c = d = e = 2
>> print c
2
>> print
2
>> print e
2


Example:3

Or you can assign multiple values to multiple variables at a time.

>>> c, d, e = 2, "program", "Happy"
>>> print c
2
>>> print d
program
>>> print e
Happy

Decision making in python (Conditions)

Decision making is taking specific actions according to the conditions. In python there are three types of codes which can be executed based on various conditions, they are.

  • if code
  • else code
  • else if code

If code

If code executes the statement if the condition is true.

Example:

#!/usr/bin/python

value = 4
if ( value  == 4 ):
print "OK"
Output: 
OK

In the above example, if I change the 'value == 4' to 'value == 3', it won't print anything because in that case the if condition won't match.

Else code

Else code is used to execute the statement when the condition is not true. In the below code, the condition is false, hence it executes the else statement.

Example:

#!/usr/bin/python

value = 4
if ( value == 3 ):
print "OK"
else:
print "Not OK"
Output:
Not OK

Else if code

The short of else if in python is elif. Elif code is used to check multiple expressions. The syntax is.

if test expression:
Statement
elif test expression:
Statement
else:
Statement


Example:

#!/usr/bin/python

value = raw_input("Type the name of your favourite fruit: ")
 if value == 'grapes':
  print("It's a fruit")
 elif value == 'orange':
  print("It's a fruit")
 elif value == 'banana':
  print("It's a fruit")
 else:
  print("Sorry, we don't have any information")

In the above example, it takes the keyboard input from the user for its favourite fruit name. It returns true if the expression matches with the input from the user otherwise returns false.

Loops

Loop is used when we want to execute a code a definite number of times. All programming languages has this loop concept. Loops in python programming language are of two types.They are.

  • While loop - In while loop, statement is executed as long as the condition is true.
  • For loop - In for loop, the statement can be iterated a number of times without worrying about the condition.

While loop

Example:

In the below example, the condition is checked before executing the loop.

#!/usr/bin/python

i = 1
 
while (i < 4):   
      print 'Line number:', i
    
  i = i + 1

Output:
 Line number: 1
 Line number: 2
 Line number: 3

We can also combine else code with while loop. In the below example else code executes when while loop completes its iteration.

Example:

 
#!/usr/bin/python

i = 1
 while (i < 4):
    print 'Line number:', i
    i = i + 1
 else:
    print 'Line finished.'
Output:
 Line number: 1
 Line number: 2
 Line number: 3
 Line finished.

For loop

For loops in python can iterates over items in a pattern. For instance, in the below example for loop can iterate over the expression and execute the statement.

Example:1

#!/usr/bin/python

for i in 'Example':
  print i
Output:
 E
 x
 a
 m
 p
 l
 e

Example:2

In this example, for loop is used to iterate over the list of colour.

#!/usr/bin/python

colour = ['Red','Blue','Green','Yellow']
 for i in colour:
  print "Name of colour: ", i
Output:
 Name of colour: Red
 Name of colour: Blue
 Name of colour: Green
 Name of colour: Yellow

The below example will demonstrate how to use else with for loop.

Example:3

The below code will check if the numbers in items contains any even number(Numbers which are divisible by 2) or not. The else statement is executed, if it doesn't find any even number.

#!/usr/bin/python

def items(a):
for i in a:
if i % 2 == 0:
  print ("There is an even number found")
  break
  else:
  print ("There is no even number found")

items([3, 1, 7])
Output:
There is no even number found

If the above code is modified with different items of numbers like below.

for i in range(1, 4, 3):

Output will be.

Output:
There is an even number found

Five data types in python

In the above section we have learned about the two most important data types i.e. 'Numbers' and 'String'. We have also learned how to assign values to variables.
However, there are five data types used in python programming language. We will learn about each of these data types in detail.

  1. Numbers
  2. String
  3. List
  4. Tuple
  5. Dictionary

Numbers

Assign value to a variable and print.

>> a = 2
>> print a
2

To delete the reference to a number object, you can use the del command as given below.

>> del a

To delete multiple objects 'a' and 'b', use del command as given.

>> del a, b

String

Assign string to a variable as given.

>> string = "My name"
>> print string
>> My name

To print character in a first place.

>> print string[1]
y

Or to print character which is in fourth place.

>> print string[4]
a

To concatenate strings, use the code as follows.

>>> print string + " " + "is" + " " + "David"
My name is David

List

List is similar to arrays. However, list can be used to store values of different types. Square brackets [ ] are used to store values in list. Learn more about how to use python lists.


Let's store some values in a list. We will create a list called items and store some values in it.

>>> items = [ 1, "Brush", 2, "Dress", 3, "Soap" ]

Now, access these items with indexes one by one.

>>> print items[0]
1
>>> print items[1]
Brush
>>> print items[2]
2
>>> print items[3]
Dress
>>> print items[5]
Soap

Tuple

Tuples are like list. But there are two main differences between list and tuples.
List values are enclosed within square brackets, where as tuples are enclosed within parentheses.
List value can be changed but tuples value cannot be updated with a new one.

To store values in a tuple, we use the code as given below.

>>> box1 = ( 3, "Orange", "Grapes" )
>>> print box1[1]
Orange

But, tuples cannot be updated with a new value as given below. The below code will throw an error for tuples.

>>> box1[1] = "Pineapple"

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment


To update a tuple with new values, you have to create a new tuple and merge it with the existing tuple.
Look at the below example.

>>> box2 = ( "Banana", "Guava" )
>>> newbox = box1 + box2
>>> print newbox
(3, 'Orange', 'Grapes', 'Banana', 'Guava')

Dictionary

Python dictionary are key pair value. You can access the value by accessing the key.
Items in dictionary are enclosed within curly braces { }. Keys are separated by colons (:) and values are separated by commas.
The below example will illustrate about how to store values in dictionary.

>>> office = {'Name':'Denis', 'ID':410, 'Depart':'IT'}

To access the value, below code format is used. In the below example, to see the value you need to access its key.

>>> print office['Name']
Denis
>>> print office['ID']
410

You can add new entry in this way.

>>> office['Address'] = "Salt Lake"
>>> print office
 {'Address': 'Salt Lake', 'Depart': 'IT', 'Name': 'Denis', 'ID': 410}

Modify any entry in this way.

>>> office['Name'] = "Denis Aster"
>>> print office
 {'Address': 'Salt Lake', 'Depart': 'IT', 'Name': 'Denis Aster', 'ID': 410}


To delete any entry, use the code as given below.

>>> del office['Address']
>>> print office
 {'Depart': 'IT', 'Name': 'Denis Aster', 'ID': 410}

Python function

Functions are block of codes, which can be reused in an application again and again. Functions are of two types.

  • Built-in functions - In python built in functions are already built and defined in python program.
  • User-defined functions - User defined functions are defined by users in a program.

The syntax of user-defined function is

def function_name()

Define a function

Function in python can be defined in this way.

def firstFunction( arg ):

print arg
return


Calling a function

The next thing is to call a function after you have defined a function. Below are the sample python programs. Save the below code in a file called 'program.py' and run.

Example:1

#!/usr/bin/python

def firstFunction( arg ):

print arg
  return;

firstFunction( "This is a function" )


Now, run

# ./program.py 
 This is a function


Example:2

In this example modify the code as given below.

#!/usr/bin/python

def firstFunction( arg ):

arg = "This is a first argument"
  print arg
  return;

arg = "This is a second argument"
 firstFunction( arg );
 print arg

Now, run.

# ./program.py 
 This is a first argument
 This is a second argument

Built in function

There are various Input/Output built-in function present in python programming language. Below are the most common built-in functions in python.

  • raw_input
  • input
  • open
  • close
  • write
  • read
  • rename
  • remove
  • mkdir
  • chdir
  • getcwd
  • rmdir

raw_input()

This function is used to take input from keyboard. For instance.
Create a file with '.py' extension and insert the below code inside the file as given below.

#!/usr/bin/python

name = raw_input("Enter your name: ");
 print "Your name is : ", name

Now run.

# ./program.py 
 Enter your name: Joe
 Your name is :  Joe

input()

This function is also used to read input from keyboard. but the difference is that it considers input a python expression. For instance,

Insert the below code in the file and run.

#!/usr/bin/pytho

value = input("Enter : ");
 print "You entered : ", value

Run,

# ./program.py 
 Enter : [1234]
 You entered : [1234]

Now try to enter you name as input. it will throw an error.

# ./program.py 
 Enter : joe
 Traceback (most recent call last):
  File "./program.py", line 3, in <module>
  value = input("Enter : ");
  File "<string>", line 1, in <module>
 NameError: name 'joe' is not defined

open()

The function open as the name suggest, it is used to open a file. To open a file various modes are used, such as read, write or append.

Example:

#!/usr/bin/python

file = open("file.txt", "w")


The list of modes you can use with open function are.

r - Read only
w - Write only
a - Appends file

rb - Read only in binary format
wb - Write only in binary format
ab - Append only in binary format

r+ - Reading and writing
w+ - Writing and reading
a+ - Appending and reading

rb+ - Reading and writing in binary format
wb+ - Writing and reading in binary format
ab+ Appending and reading in binary format

File object

When you open a file with open function, file object is created. The file object can be used to get many information about that file.
Below are the list of file object attributes.

file.closed - The value is true if files is closed.
file.mode - Displays the mode with which the file was opened (Read, write, etc.)
file.name - Displays the file name.
file.softspace - Returns 0 if space character required to be printed. Otherwise 1.

Example:1

#!/usr/bin/python

fl = open("file.txt", "w")
 print "File name: ", fl.name
 print "File mode: ", fl.mode


You will get the following output on running the above script.

# ./program.py

File name: file.txt
File mode: w

Example:2

#!/usr/bin/python

fl = open("file.txt", "w")
 print "Is it closed?: ", fl.closed
 print "Softspace: ", fl.softspace

Run,

# ./program.py

Is it closed?: False
 Softspace: 0

close()

Close method is used to close any file object, when we are done with writing that file. Look at the below example, where we have closed the file with close method. The file object will return true, as we have closed the file with closed file object.

Example:


#!/usr/bin/python

# Open file
fl = open("file.txt", "w")
print "File name: ", fl.name
print "File mode: ", fl.mode
# Close file
fl.close()
print "Is it closed?: ", fl.closed

Run,

# ./program.py 

File name:  file.txt
File mode:  w
Is it closed?:  True

write()

Write function is used to write anything in a file when it's opened. Let's look at the below example.

#!/usr/bin/python

# File open
 file = open("file.txt", "wb")

# File write
 file.write( "This is our first example to write something in Python.\n");

# File close
 file.close()


In the above example, file is opened for writing, then it's being closed by closed method when the writing is over. The access mode is 'wb', because file data can be both in binary or text.

The file content will be.

# cat file.txt 
 This is our first example to write something in Python.


read()

Read method is used to read the content of the opened file. With the passed parameter, we can decide the number of bytes to be read from the file.

In the below example, we have used the parameter (25), so it will read up to 25 bytes in a file. The access mode is 'rb+' to read data in text as well as binary format.

Example:

#!/usr/bin/python

# File open
 file = open("file.txt", "rb+")

string = file.read(25);
 print "Read till : ", string

# File close
 file.close()
Output is.
Read till : This is our first example


rename()

As the name of the method suggest, rename() is used to rename a file. Rename method takes two parameters, first the actual name of the file, second the new name of that file.
We will import python 'os' module here to rename a file. The os module is used for various purposes, such as finding if a file or directory exist at the location or not, and performing specific tasks on that file like renaming, deleting, etc.

For example.

#!/usr/bin/python

import os

os.rename("file.txt", "fileeee.txt")

The above example when run will rename the file 'file.txt' to 'fileeee.txt'.


remove()

Remove method is used to remove a file. This method takes one parameter, that is the file name to be deleted.

#!/usr/bin/python

import os

os.remove("file.txt")

The above command when run will delete the file from the current directory.

mkdir()

The mkdir method is used to create a new directory to the specified location.

Example:

#!/usr/bin/python

import os

os.mkdir("myDirectory")

The above code will create a directory called myDirectory at the current location.


chdir()

Chdir method is used to change directory. The below example will change the directory and create a new file inside it.

#!/usr/bin/python
 import os

os.chdir("/root/myDirectory")
 open("file.txt", "w")

The above code will create 'file.txt' file inside the folder myDirectory.

getcwd()

This method shows the current working directory. Getcwd method doesn't take any parameter.

#!/usr/bin/python
import os

cwd = os.getcwd()
print "Current Working Directory: ", cwd
Output:
Current Working Directory: /root


rmdir()

Rmdir method is used to remove any directory. It takes one parameter, the directory name.

#!/usr/bin/python
 import os

os.rmdir('myDirectory')

The above code will remove directory from specified location.

Variables

There are two types of variables.

1) Global variables - These variables are defined outside the function. They can be accessed from anywhere inside the program.
2) Local variables - Local variables are locally declared inside the function and are accessable for that specific function only.


Let's see an example of global and local variable.

#!/usr/bin/python

a = 5; # Global variable.

def func( arg ):

a = arg # Local variable.
  print "Local : ", a
  return a;

func( 10 );
 print "Global variable : ", a

On  running the above code, we get the following output.

# ./program.py 
 Local : 10
 Global variable : 5

Modules

In python, module is a file, which consists of python codes. It is a way to put python definitions and statements in a file.
We can use this modules in any script by importing them.

Create two files, one 'module.py' and another 'program.py'.
We will use module.py file to write our modules and program.py to write our script, then we'll import the module in our script.
Look at the below example for instance.

Content of module.py

#!/usr/bin/python

def firstModule( a ):

print "Value : ", a
  return


Content of program.py

#!/usr/bin/python

import module

module.firstModule(15)


When we run the program.py script, we get the following output.

# ./program.py
 Value : 15

From statement

In python programming language from statement is used to import only specific attribute from the module, not the entire module. For instance.

In 'modules.py' file, we have created two functions.

#!/usr/bin/python

def firstModule( a ):

print "Value : ", a
  return

def sum( a, b ):

total = a + b;

print "Value : ", total
  return


Let's import only function sum() to program.py

#!/usr/bin/python

import module

from module import sum

module.sum(5, 6)

Similarly, more than one functions can be imported in this way.

import module
from module import sum, firstModule

module.sum(5, 6)
module.firstModule(10)

 


So far in this tutorial we have learned about Python programming language for beginners. This article will be helpful for those who aspire to become python programmer and wish to learn basics of python programming.

 

Download Our Free eBook now

Linux and UNIX Shell scripting ebook

Be the first to comment

Leave a Reply

Your email address will not be published.


*


shares