Python programming 1: Basics

python

Python is an interpreted language and not a compiled language. Therefore, it executes commands and outputs the results of each command in a sequence, till it hits an issue, or completes the program.

This tutorial has various simple scripts to get started with writing Python programs. I use a CentOS 7 host with Python 2.7 installed. I use “#!/usr/bin/python” as the first line in each of the examples so that my shell will understand that it should use Python to execute the file. This is a “shebang“.

Sample script to print “Hello World”

=======

print(“Hello World”)
=======

Python is a white space sensitive language. So we need to put space where required and avoid using when not required. If you are used to other languages such as Java, etc, we have a practice of typing several commands of one function within a set of brackets such as { and }. But in Python, the language understands that all commands starting within a intended series of line as part of one function.
Sample script to print “Hello World” written as a function:
=======
#!/usr/bin/python

def main():
     print(“Hello World”)
=======

If we run the above script, we will not see any output, but will not see any error either. However if we call the fuction separately, it will display the output of the function. For example the below code will print “Hello World” :

=======
#!/usr/bin/python

def main():
     print(“Hello World”)

main()
=======

Sample script to print “Hello World” written as a function, and also print “Hello my friend” which was defines as a variable in the same function:

=======
#!/usr/bin/python

def main():
     myVar = “Hello my friend”
     print(“Hello World”)
     print(myVar)

main()
=======

A global variable is a variable defines outside all functions in a program. The below program print three lines of output, “Hello World”, “This is great” and “This is great”.

=======
#!/usr/bin/python

def main():
     print(“Hello World”)
     print(yourVar)

yourVar = “This is great”
main()
print(yourVar)
=======

In order for a function to use a global variable, the variable has to be defines before the function is called. The below code will give an error:

=======
#!/usr/bin/python

def main():
     print(“Hello World”)
     print(yourVar)

main()
yourVar = “This is great”
print(yourVar)
=======

Functions can be defined that expects a vaiable to be passed when calling them. Below is an example:

=======
#!/usr/bin/python

def helloWorld(myVar):
     print(myVar)

helloWorld(“This is Shiju”)
=======

It is a great practice to write comments in a Python code. Like we use # or ; in other programming languages, we use write comments between a set of “”” and “””. We can also write a comment starting with the line with #.
=======
#!/usr/bin/python
“””A code to print a string”””
def main():
     print(“Hello World”) #Prints a line

main()
=======

Sample script with a function that expects to receive two variables when it is called and returns a value to the line that calls the function.
=======
#!/usr/bin/python

def theAddFunction(var1, var2):
     myResult=var1 + var2
     return myResult

def main():
     print(theAddFunction(1, 1))
     print(theAddFunction(1, 2))
     print(theAddFunction(1, 3))

main()
=======

The variable type in which Python 2.x received variable using input function seems to be different in Python 3.x.
Sample script that received inputs from users:

=======

#!/usr/bin/python

def main():
     myNum = int(input(“Enter an integer: “))
     print(myNum)

main()
=======

Converting a String value to integer can be achieved by using int(<string>)

Logical operators include == , != , < , > , <=, and >= .

Sample code using if, elif and else statements:
=======

#!/usr/bin/python

def car():
      print(“Honda”);

def suv():
      print(“Jeep”);

def truck():
      print(“Mack”);

def bus():
      print(“Volvo”);

def main():
      myOption = str(input (“car, suv, truck or bus:” ))

      if(myOption == ‘car’):
            car()
      elif(myOption == ‘suv’):
            suv()
      elif(myOption == ‘truck’):
            truck()
      elif(myOption == ‘bus’):
            bus()
      else:
            print(“Oooppss …..”)

main()

=======

Exception handlers are used to manage and exit program gracefully if an error is identified during execution.
Below is an example where a user “can” enter a string input to a variable expecting an integer. The program exits gracefully even is a type error is identified when a String is entered.

=======
#!/usr/bin/python

def main():
     try:
          num1 = int(input(“Please enter an integer :”))
     except:
          print(“Seems you did not enter an integer. Exiting the program !!”)
          return
     myResult = num1 * 2
     print(myResult)

main()
=======

In the above example, if we need to catch only value-based errors and not all errors, we should be mentioning “except ValueError” instead of just “except”. A better code will be as follows:
=======
#!/usr/bin/python

def main():
     try:
               num1 = int(input(“Please enter an integer :”))
     except ValueError:
               print(“Seems you did not enter an integer. Exiting the program !!”)
               return
     except:
               print(“Some unknown error happened. Exiting the program !!”)
               return
     myResult = num1 * 2
     print(myResult)

main()
=======

A While-loop is a very powereful feature in programming to repeat certain commands till a desired result is achieved. Below is a program that prompts a user to input a value till a valid integer is entered:

=======
myValidInput = False #False is a boolean keyword

while not myValidInput:
     try:
               num1 = int(input(“Please enter an integer :”))
               myValidInput = True
     except:
               print(“Seems you did not enter an integer. Try again : “)

     myResult = num1 * 2
     print(myResult)

main()
=======

The “for-loop” is another type of loop that loops ‘n‘ number of times, unlike based on a condition in while-loop. Below is an example that print “Hello World” three times:

=======
#!/usr/bin/python

def main():
     for i in range(3):
          print(“Hello World”)

main()
=======

 

The “Lists” is a collection of items, a very useful feature that can be used in Python language. Below is an example of how to define a new “List” and how to use it.

=======
#!/usr/bin/python

myList = [] #Defining a list

“””Adding more values in the list”””

myList.append(‘Shiju’)
myList.append(‘Bryan’)
myList.append(‘George’)
myList.append(‘Jacob’)
myList.append(‘Sam’)
myList.append(‘Kevin’)

print(“The length of the list is :” + str(len(myList)))

print(“\nThe contents of the list are as follows:”)

print(str(myList))

print(“\n”)
print(“=========================”)

print(“\nThe contents of the list are as follows:”)
for theList in myList:
           print(theList)
=======

A “Dictionary” is very similar to a List. However a Dictionary has a key associated with a value. Below is an example that defines a Dictionary, adds value and does various operations.

=======
#!/usr/bin/python

def main():
          thePlaces = {} #Defining a disctionary

          “””Adding values to a dictionary”””
          thePlaces[‘India’] = ‘Taj Mahal’
          thePlaces[‘China’] = ‘The great wall of China’
          thePlaces[‘USA’] = ‘The Grand Canyon’
          thePlaces[‘Egypt’] = ‘The pyramids’

          print(‘Printing the contents of the dictionary in one line’)
          print(str(thePlaces))

          “””Print the contents of the Dictionary, line by line based of key”””
          for key in thePlaces:
               print(‘The value of the key ‘ + str(key) + ‘ is ‘ + str(thePlaces[key]))

main()
=======
One of the most beautiful features of Python is that we can import modules and perform operations with functions inside the classes imported. The below is a script saved as “addMe.py

=======
#!/usr/bin/python

def theAddFunction(var1, var2):
          myResult=var1 + var2
          return myResult
=======

Below is a program named “importModule.py” that imports the above module and performs operations with functions inside it.

=======
#!/usr/bin/python

import addMe
print(addMe.theAddFunction(1,2))
=======