Python Chapter#1: Getting Started with basic syntax

Ankur Kulhari

In python there are two modes available to program as Matlab:

  1. Interactive Mode Programming
  2. Script Mode Programming

Now let’s see how to program in these modes:

Interactive Mode Programming

Python instructions can be directly executed from the python prompt.
Ex:

Python 3.6.0a3 (v3.6.0a3:f3edf13dc339, Jul 11 2016, 21:40:24) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>print("Hello world!")
Hello world!

Ex:

Python

Fig.1: Interactive Mode Programming example#1

Ex:

>>>x=2
>>>print(x)
2
>>>

Script Mode Programming

Similar to m file in matlab, python also provides facility to write program in a script file with .py extension.
Lets write our first script file in python to print “Hello world!”:
You can write your code in a notepad file and save it with extension .py as:

python programming

Fig.3: Script mode programming with notepad

To run the file open command prompt and change current working directory to the folder where script file is saved and run the command python <script file name>
Python Programming

Fig.5:Run script from command prompt.

You can also run it by opening file in IDLE.
OR
you can open python code editor from IDLE (python) as:
python programming

Fig.4: Script mode programming with IDLE

To run a script press F5 or goto [run–>run module]
Python Programming

Fig.6: Run script from IDLE

Output will be displayed at the IDLE prompt.

Python Identifiers

A Python identifier is a name used to identify a variable, function, class, module or other object.

Rules for Identifiers:
  • An identifier starts with a letter A to Z or a to z or an underscore (_)
  • It contains letters, underscores and digits (0 to 9) only
  • Python is a case sensitive programming language
  • Class names start with an uppercase letter
  • All other identifiers start with a lowercase letter
  • Private identifiers start with (_) underscore
  • Strongly private identifiers start with (__) double underscore
  • A language-defined special name identifier is defined by adding two trailing underscores
Python Reserved Words
  • Reserved words cannot be used as constant or variable or any other identifier names
  • Python keywords contain lowercase letters only

Following are the reserved words in python:

and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Blocks of code
  • Unlike C, C++ and Java, in python blocks are not defined with ({ }) set of curly braces
  • Instead it uses line indentation to indicate blocks of code for class and function definitions or flow control
  • All statements of a block must be indented the same amount. The number of spaces in the indentation can be variable
  • Ex:

    x=0
    while(x<2):
        print(x)
        x=x+1
    print("Finally x=", x)
    

    OUTPUT

    0
    1
    Finally x= 2
    
    Python Programming

    Fig.7: Indents in Python example

    With wrong indentation:

    x=0
    while(x<2):
        print(x)
        x=x+1
      print("Finally x=", x)
    

    Here last statement “print” does not belong to any indentation, leads to error.

    Python Programming

    Fig.8: Wrong indentation

    Multi-Line Statements
    • In python (\) forward slash is used as line continuous character.
      >>> x=2\
         +2+\
         3
      >>>x
      7
      

      It is equivalent to x=2+2+3

    • Statements contained within brackets [], {}, or () do not need to use the line continuation character.
      >>> x= [2,3
          ,4]
      >>> x
      [2, 3, 4]
      

      x is an array.

      String Literals

      To denote string literals in python, single (‘), double (“) and triple (”’ or “””) quotes could be used.
      Ex:

      text='Hey'
      text1="Hey"
      text2='''Hey'''
      text3="""Hey"""
      
      Comments in Python

      A hash sign (#) is can be used in python to begins a comment.

      # First comment
      print("Hello word!") # second comment
      

      OUTPUT:

      Hello word!
      
      User Input in Python at Run Time
      • raw_input() could be used to take user input at run time
      • raw_input() prints the arguments passed into it
      • raw_input() returns the value entered by the user
      • Ex:

        x=raw_input("Enter some value: ")
        print x
        

        OUTPUT:

        Enter some value: <34>
        34
        

        Say, user entered 34, so x=34 and raw_input prints Enter some value:

      Multiple Statements in Single Line

      Multiple statements separated by semicolon (;) can be written in single line.
      Ex:

      x = 'foo'; print x, '\n'
      

      OUTPUT:

      foo
      
      
      Suites in Python

      Suite in Python is a group of individual statements, which make a block of code. Compound or complex statements, such as if, while, def, and class require a header line and a suite.
      Header lines begin the statement (with the keyword i.e. if, while, def, and class) and terminate with a colon (:) and are followed by one or more lines of code, which forms the suite.
      Ex:

      while expression :
          statements
          statements
      if expression : 
          statements
          statements
      elif expression : 
          statements
          statements 
      else : 
          statements
          statements
      
      Command line Arguments

      Similar to gcc command line arguments, python also provides facility of command line arguments.

      • len(sys.argv) gives he number of command-line arguments
      • sys.argv gives the list of command-line arguments
      • sys.argv[0] is the program i.e. script name
      • Ex:

        import sys
        print('Number of arguments:', len(sys.argv), 'arguments')
        print('Argument List:', str(sys.argv))
        

        Run the program from command prompt as python xyz.py argument1 argument2 argument3
        OUTPUT:

        Number of arguments: 4 arguments
        Argument List: ['xyz.py', 'argument1', 'argument2', 'argument3']
        

What do you think about the article?

This site uses Akismet to reduce spam. Learn how your comment data is processed.