Python Tutorial
Python - Introduction Python - Syntax Python - Variable Python - Number Python - Casting Python - String Python - Operators Python - Conditions Python - Loops Python - List Python - Tuple Python - Set Python - Dictionary Python - Function Python - Module Python - Date & Time Python - Input Output Python - Error & Exception Python - File Handling
Python OOP
OOP - Introduction OOP - Class Members OOP - Constructor Destructor OOP - Data Hiding OOP - Inheritance OOP - Overriding OOP - Overloading

Python Syntax

Python Indentations

Where in other programming languages the indentation in code is for readability only, in Python the indentation is very important.

Python uses indentation to indicate a block of code.


Python Comments

Python has commenting capability for the purpose of in-code documentation.

Comments start with a #, and Python will render the rest of the line as a comment:


Python Docstrings

Python also has extended documentation capability, called docstrings.

Docstrings can be one line, or multiline.

Python uses triple quotes at the beginning and end of the docstring:



Output Variables

The Python print() function is often used to output variables.

To combine both text and a variable, Python uses the + character:

For numbers, the + character works as a mathematical operator:

By default python's print() function ends with a newline. A programmer with C/C++ background may wonder how to print without newline.

Python's print() function comes with a parameter called end. By default, the value of this parameter is ā€˜\nā€™, i.e. the new line character. You can end a print statement with any character/string using this parameter.


Getting user Input

Python allows for command line input. That means we are able to ask the user for input.

The following example asks for the user's name, by using the input() method, and then prints the name to the screen:


Python Expression

Python Expressions can be used to any data-type:

Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1,2,3] :
    print (x,end = ' ')
1 2 3 Iteration

Indexing, Slicing and Matrix

Assuming the following input:

L = ['C++', 'Java', 'Python']
Python Expression Results Description
L[2] 'Python' Offsets start at zero
L[-2] 'Java' Negative: count from the right
L[1:] ['Java', 'Python'] Slicing fetches sections
L[0:2] ['C++', 'Java'] Slicing fetches sections
L[:3] ['C++', 'Java', 'Python'] Slicing fetches sections
L[:] ['C++', 'Java', 'Python'] Slicing fetches sections