Menu Close

Articles

Introduction to Python

Python is a scripting language. It was designed as a glue language to execute operating system commands and C++ applications. It has evolved into something more that that. Now Python is used as a general-purpose multi-paradigm computer language. It can be used to create console applications, services or automation scripts.

Hello world

This is the a simple program program, common in many other languages as first example. If you run it, you will see message: “hello world” at the console. The purpose of this example is to introduce you to the most common syntax rules. 

Example:

Syntax Notes:

  • python comments start with “#” symbol,
  • the main procedure is named “__main__”,
  • strings are enclosed in double quotes: “hello world”,
  • function call is using round parentheses print(…),
  • to start the “if” block we use “:” after the condition,
  • blocks of code are indented at equal number of spaces, usually for spaces.

Interpreter:

Python is an interpreted language. After you start python you can use a command and python will display the result. Therefore previous program has the same effect as the following commands:

c:\>python

Script

Python programs are called scripts. You can run a script using “python” command in console. Before you do you must install “python software” on your computer and make sure it is available for execution in $path environment variable.

In my future examples I will not specify that a program must be saved in a script before execution. All examples are scripts that can be saved with extension *.py and should work if you run them using following command:

c:\>python <program_name>.py.

Note: Replace <program_name> with a proper name of your choosing.

General concepts

Next I will explain basic concepts you should already know. If you find these concepts strange and unfamiliar do not bother. Just go ahead with the reading and eventually in the next articles you will find more information and eventually you will grasp the idea of programming in Python.

Identifier

The “identifier” is a name that we give to a syntax element of a script. Think about identifiers like labels or tags you apply for things. Identifiers can represent something important that you can reuse so you need a name for it. For example a value or formula can have a name. When you use the identifier, Python will find the value or formula and will use it according to program instructions.

Expressions

An expression is an enumeration of identifiers, symbols and operators that can interact and produce a result. The result can be used immediate or can be captured and named so it can be used later to create other expressions or statements.

Example of expressions:

Note: Expressions are immediately evaluated and the result is automatically shown on to the screen console. You can test an expression easy in Python console by typing it and press enter:

Homework:

Open this website address and run several expressions: https://repl.it/languages/python3

Symbols

Before you start understanding the syntax, take a short look at next symbols. Most of these are called operators but some are punctuation markers or separators having different purpose that I will explain later:

SymbolPurposeExample
#single line comment or end of line comment#this is a comment
=assign value to variablex=10
;separate multiple statementsa=1; b=a + 1; c = a+2
.dot notation (member of)self.a = 1
“…”Unicode strings=”this is a string”
‘…’strings=’this is a string’
“””triple quoted string (documentation)

“”” this is a large string

on multiple lines “””

()empty tuple literalt=(1,2,”a”)
[]empty list literall=[1,2,3]
{}empty set literals={1,2,3}
{:}empty dic (dictionary)d={“a”:1,”b”:2,”c”:3}
:define or pair-upd={“a”:1,”b”:2,”c”:3}
[n]subscript (n) for collections[0] == 1 #this is true
+addition a=1+2 #result is 3
*multiplication a=2*2 #result is 4
/division a=2/2 #result is 1.
**exponent (powera=2**3 #result is 8
//floor divisiona=9//2 #result is 4
%remainder a=1/2 #result is 0.5
<>not equal (inequality) 2<>3 #true
!=not equal (inequality) 2!=2 #false
==equal or equivalent 1==1 #true
>=greater then or equal 1 >=0 #true
<=less then or equal 1 <=0 #false
>grater then 1 > 0 #true
<less then 1 < 0 #false
+=in place addition. (modifier). Other modifiers are available for all math operators: -=, *=, /=, %=a: int = 1
a+= 1  #a = 2
\statement continuation  symbol

x = a + b \

   + (c+d); # end of statement

Bitwise operators

Next operators are acting at bit level. They are inherited from C language. An operator usually has 2 operands but one of these operators has only one operand. Which one?

OperatorNameDescriptionExample
&Binary ANDOperator copies a bit to the result if it exists in both operands(a & b)
|Binary ORIt copies a bit if it exists in either operand.(a | b)
^Binary XORIt copies the bit if it is set in one operand but not both.(a ^ b)
~Binary Ones ComplementIt is unary and has the effect of ‘flipping’ bits (not).(~a )
<<Binary Left ShiftThe left operands value is moved left by the number of bits specified by the right operand.a << 2
>>Binary Right ShiftThe left operands value is moved right by the number of bits specified by the right operand.a >> 2

Logic Operators

In python we work with two Boolean values True and False. Logical operators are used to combine these kind of values or produce these kind of values. Usually, logical operators have two operands but “not” will operate on a single operand.

keywordsignificance
andLogical AND operator
orLogical OR operator
notLogucal NOT operator
inmembership operator
isobject identity operator

Reserved Keywords

These words are used for creation statements that I will explain next. Python is a statement oriented language. Some statements are using one single keyword but some can combine multiple keywords.

andexecnot
assertfinallyor
breakforpass
classfromprint
continueglobalraise
defifreturn
delimporttry
elifinwhile
elseiswith
exceptlambdayield

Statement

One statement is usually a line of code in Python. Sometimes a statement can be continued on next line using continuation operator: “\”. A statement is ending with separator “;” if this is used. In Python you can have multiple statements in a single line.

A line of code is ending with new line character: “\n”. This has a weird representation you may be familiar with: ¶ It may be interpreted as CR + LF on Windows and LF on Linux. Most of editors do not show this hidden symbol. 

A code line that end with an operator like “+” may continue on next line. In this case the continuation operator “\” is not necessary. Python interpreter will try to be smart and autocomplete the end of statement when symbol “;” is not present.

Python is an imperative language. Most statements are using a keyword to start a statement, except the assign statement that start with an identifier. An expression is not a statement, please do not confound the two.

Indentation

Some statements are wrappers for other statements. These are called “block statements”. A block of code consist of one parent statement and nested statements belonging to the block. When a statement is nested it must start with several spaces or tabs. Multiple statements starting with same number of spaces belong to same block.

Example:

Note: In previous example I have used statement “if” that is a block statement. Next two statements are using keyword: print and are indented at two spaces. Both belong to “if” block. This particular statement has a secondary block that start with “else:”, the second block contains two print statements that will never execute. This is called also “dead code” and is a good practice to avoid it.

Homework: Open the example in external website and run it:
https://repl.it/@elucian/Indentation-demo

I hope you enjoy so far. If you do, please give us kudos on the forum. 

Read next: Variables