Let's start with simple program, common in many other languages given as introductory example. If you run it, you will see a message: "hello world" at the console. The purpose of this example is to introduce you to the most common syntax rules.
# compiler entry point
if __name__ == "__main__":
print("hello world")
Python is an interpreted language. This means you can run a REPL application. The REPL = Read Evaluate Print Loop, is a program called python.exe. This is the interpreter. After you start python interpreter you can use commands and python will execute these command immediately then display the results. Therefore previous program "hello-world" has the same effect as the following commands:
c:\projects> c:\projects>python >>> print("hello world") >>> hello world
A statement is usually on line of code that contains expressions and symbols. There are several kind of statements. The most usual form of statement is the assign statement. One larger statement called "block" statement can include several other single line statements.
Python is an imperative language. Therefore, most statements are using a keyword to start, except the assign statement that start with an identifier. In python an assign statement is also an expression. Therefore this will work:
>>> a = b = 10 >>> a >>> 10 >>> b >>> 10
A code line, is simple put a text row ending with new line. It has a visual representation as: "¶". It is interpreted as (CR+LF) on Windows and (LF) on Linux. Most of editors do not show this hidden symbol. Some editors have an option to show hidden characters.
In Python one statement is usually a single code line. However not all statement are on a single line. Sometimes one code line can have many statements separated by semicolon (;). When a statement is too long, it can be continued on next lines.
There are two ways to break a statement in multiple code lines. First method is to use backslash (\) at end of line the continue on the next line. This is called "continuation" operator. Second, a code line that end with an operator like "+" may continue on next line. In this case the continuation operator "\" is not necessary.
Some larger statements are wrappers for other statements. These macro statements are called block statements. Multiple statements starting with same number of spaces belong to same block. When indentation is reduced, the block statement is considered ended. Officialy there is no keyword used in Python to end a block of code.
# test python indentation and block
if True:
print("This is a demo.")
print("True is always True.")
else:
print("This is absurd")
print("True is never False")
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 four 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 dead code and is a good practice to avoid it.
Homework:
Open the example in external website and run it:
indentation-demo
An identifier is a name that we give to a syntax element. Think about identifiers like labels or tags you apply for things. Identifiers can be a single character or several characters up to 32. One identifier start with a letter and can contain letters, numbers and underscore (_).
A name that is given to a value that can be modified later is called a variable. Sometimes a variable can represent a memory address. In this case a variable represents a reference. In other words, variables are value identifiers.
A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as containers that hold information which cannot be changed later. We have a convention to use capital letters for constant identifiers. In reality Python do not have constants but is just a convention.
A literal is a value symbol that can be a number, string or collection of values. The literal is also truly constant. You can not change value of literals during runtime. For example: 520 is a literal but "520" is also a literal. Literals represent hard coded data.
5
24
520
'a'
"test"
[1,2,3]
An expression is an enumeration of identifiers, symbols and operators that can interact and produce a result. Python interpreter can understand expressions and will display the result immediately after you press enter. Statements are useful to make a short computation or to display a message to the console using print() function.
# this is python REPL test
0 + 1 + 2*3
a/(b + c)
"python" + "is great"
'test' + 1
In python we use symbols to separate elements of an expression. Usually one symbol is one special character. Sometimes one symbol is created from two characters. Symbols are: punctuation markers, operators or separators. Take some time to read description for each symbol in the next table:
Symbol | Purpose | Example |
---|---|---|
# | single line comment or end of line comment | #this is a comment |
= | assign value to variable | x=10 |
; | separate multiple statements | a=1; b=a + 1; c = a+2 |
. | dot notation (member of) | self.a = 1 |
"..." | Unicode string | s="this is a string" |
'...' | string | s='this is a string' |
""" | triple quoted string (documentation) | """ this is a large string on multiple lines """ |
() | empty tuple literal | t=(1,2,"a") |
[] | empty list literal | l=[1,2,3] |
{} | empty set literal | s={1,2,3} |
{:} | empty dic (dictionary) | d={"a":1,"b":2,"c":3} |
: | define or pair-up | d={"a":1,"b":2,"c":3} |
[n] | subscript (n) for collection | s[0] == 1 #this is true |
\ | statement continuation symbol | x = a + b \ + (c+d) |
Python implements most common arithmetic operators as ASCII characters.There are several arithmetic operators that use two characters.When two characters are used there is no space between the two.
Symbol | Purpose | Example | + | addition | a=1+2 #result is 3 |
---|---|---|
* | multiplication | a=2*2 #result is 4 |
/ | division | a=1/2 #result is 0.5 |
** | exponent (power) | a=2**3 #result is 8 |
// | floor division | a=9//2 #result is 4 |
% | remainder | a=3%2 #result is 1 |
Modifiers are in place operators that alter value associated to an identifier.Modifiers are also assignment statements. Python modifiers are inherited from C language.Modifiers can accept expressions not only constants.
Symbol | Purpose | Example |
---|---|---|
+= | in place addition | a: int = 1 a+= 1 #a = 2 |
-= | in place subtraction | a: int = 1 a-= 1 #a = 0 |
*= | in place multiplication | a: int = 2 a*= 3 #a = 6 |
/= | in place division | a: int = 9 a/= 3 #a = 3 |
%= | in place addition modulo | a: int = 5 a%2 #a = 1 |
A relation operator can be used to compare two values. Usually values are numeric but can be also strings or objects.Relation operators are also known as comparison operators.These operators produce a Boolean result.
In the next example we initialize value x, called "test fixture" and we use this value to create relation x==5 to demonstrate how a relation produce a Boolean response.In the next table, we use variable x = 5 to demonstrate various comparison expressions.
#example of identity relation
x = 5 # create a test fixture
print(x) # check x value
print("is x equal to 5? ", x == 5)
Symbol | Description | Expression | Result |
---|---|---|---|
== | equal to | x == 8 | False |
x == 5 | True | ||
x == "5" | False | ||
!= | not equal | x != 8 | True |
> | greater than | x > 8 | False |
< | less than | x < 8 | True |
>= | greater than or equal to | x >= 8 | False |
<= | less than or equal to | x <= 8 | True |
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? Read description for each operator to find out!
Operator | Name | Description | Example |
---|---|---|---|
& | Binary AND | Operator copies a bit to the result if it exists in both operands | (a & b) |
| | Binary OR | It copies a bit if it exists in either operand. | (a | b) |
^ | Binary XOR | It copies the bit if it is set in one operand but not both. | (a ^ b) |
~ | Binary Ones Complement | It is unary and has the effect of 'flipping' bits (not). | (~a ) |
<< | Binary Left Shift | The left operands value is moved left by the number of bits specified by the right operand. | a << 2 |
>> | Binary Right Shift | The left operands value is moved right by the number of bits specified by the right operand. | a >> 2 |
In python we work with two Boolean values: True = 1 and False = 0. Logical operators are used to combine these type of values or produce these type of values. Usually, logical operators have two operands, except operator "not" that will operate on a single operand.
keyword | significance |
---|---|
and | Logical AND operator |
or | Logical OR operator |
not | Logical NOT operator |
in | membership operator |
is | object identity operator |
Logical operators in Python are lowercase keywords and not special symbols.These operators can operate on logical values to create logical expressions.Following logical operators are available in Python: {or, and, not}.Using keywords, makes Python logic expressions easier to read than JavaScript expressions.
Examples:You can run these examples in Python console:
#Test logical expressions
>> True and True
True
>> not True
False
>> False or True
True
>> not False
True
Note: operator xor is not present in Python but it can be simulated using formula:
#define xor() function
def xor( a, b ):
return (a or b) and not (a and b)
Next table will help you understand better all possible combinations of values and the result yield by logical operators {"or", "and", "xor"}.
P | Q | P or Q | P and Q | P xor Q |
---|---|---|---|---|
False | False | False | False | False |
True | False | True | False | True |
False | True | True | False | True |
True | True | True | True | False |
None | None | None | None | None |
None | True | True | False | True |
True | None | True | False | True |
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.
and | exec | not |
assert | finally | or |
break | for | pass |
class | from | |
continue | global | raise |
def | if | return |
del | import | try |
elif | in | while |
else | is | with |
except | lambda | yield |
I hope you enjoy learning Python. Take a break and read next tomorrow morning.
Read next: Variables