Python Syntax

In this tutorial notebook, you will learn how to do programming in python and Jupyter (formerly named as ipython). Open a new python notebook, try to copy and paste the following codes to play with.

When you read the following codes, you will see how simple and clear Python syntax is.


In [1]:
# make a list
students = ['boy', 'boy', 'girl', 'boy', 'girl', 'girl', 'boy', 'boy', 'girl', 'girl', 'boy', 'boy']

boys = 0; girls = 0

for s in students:
    if s == 'boy':
        boys = boys +1
    else:
        girls+=1
        
print("boys:", boys)
print("girls:", girls)

Hello World! in other language

Python

print("Hello World!")

Fortran

PROGRAM HELLO
    WRITE (*,100)
    STOP
100 FORMAT (' Hello World! ' /)
    END

Lisp

(print "Hello World!")

C++

#include <iostream.h>
main()
{
    cout << "Hello World!" << endl;
    return 0;
}

Java

class HelloWorld {
  static public void main( String args[] ) {
    System.out.println( "Hello World!" );
  }
}

Matlab

disp('Hello World!');

JavaScript

document.write('Hello World!')

Jupyter Notebook

operations:

  1. Click on the cell to select it.
  2. Press SHIFT+ENTER on your keyboard or press the play button () in the toolbar above.
  3. Open new cells using the plus button ()

You may read the following tutorial for more information: https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook

Let's us print a Hello World! statement

  1. Write
    print("Hello World!")
    
    into the cell below:
  2. Press SHIFT+ENTER on your keyboard!

In [ ]:

Screen Output

To enter more than one line in a cell, press Enter. The print function will print all the objects seprated by a comma , on the same line, the output will have . For example, print "Hello", "World!" will have a space between Hello and World!.


In [2]:
print("Hello", "World!")

In [3]:
print("Tips 3: Use \ to escape an characters like \"")
print("Tips 4: Use \\n \n to make a newline character")
print("""Tips 5: Use three \" to 
make 
multiple 
line
""")

The magic command (used in jupyte notebook)

Any command starts with % are magic command in ipython notebook. These % command can only be used in ipython instant. A full list of magic command can be found here:

http://ipython.readthedocs.io/en/stable/interactive/magics.html.

These commands are particularly useful in developing and debugging your program.

Performance test

you can time a statement with %timeit and it will output a basic execution time.


In [4]:
%timeit sum(range(100000))


1.22 ms ± 3.59 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Import package and library

Python has a lot of library. Use expression like

import xxxxxxx

or

from xxxxxxx import yyyyyy

to import library provided that you know the name of your library xxxxxx and objects yyyyyyy in the library xxxxxxx.

Package is not loaded at the beginning, you need to import it before using it.


In [5]:
import numpy

In [6]:
numpy


Out[6]:
<module 'numpy' from '/home/yanyan/anaconda3/lib/python3.7/site-packages/numpy/__init__.py'>

In [7]:
import numpy as np

In [8]:
np


Out[8]:
<module 'numpy' from '/home/yanyan/anaconda3/lib/python3.7/site-packages/numpy/__init__.py'>

Comments Are Marked by #


In [9]:
# Declare x=0
x=0

In [10]:
x += 2  # shorthand for x = x + 2

In [11]:
"""
Multi line Strings can also be used as comment (a docstring)
"""
x += 2

A Statement

Remember end of line will terminate a statement. To produce a multi-line code we will add \ to the end of line


In [12]:
x = 1 + 2 + 3 + 4 + 5 \
    + 6 + 7 + 8

It is also possible to continue expressions on the next line within parentheses, without using the \ marker:


In [13]:
x = (1 + 2 + 3 + 4 +
     5 + 6 + 7 + 8)

Sometimes it can be useful to put multiple statements on a single line.


In [14]:
boys = 0; girls = 0

A Note on the print() Function

# Python 2 only!
>> print "first value:", 1
first value: 1
# Python 3 onwards
>> print("first value:", 1)
first value: 1

In order to use print function in python 2, you may execute at the beginning

from __future__ import print_function

Indentation: space ot tab, but don't mix it up


In [15]:
for s in students:
    if s == 'boy':
        boys = boys +1
    else:
        girls+=1
// C code
for(int i=0; i<100; i++)
   {
      // curly braces indicate code block
      total += i;
   }

In Python, code blocks are denoted by indentation:

for i in range(100):
    # indentation indicates code block
    total += i

Conclusion

This is a very brief exploration of the essential features of Python syntax; its purpose is to give you a good frame of reference for when you're reading the code in later sections. The most widely used style guide in Python is known as PEP8, and can be found at https://www.python.org/dev/peps/pep-0008/.