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 fix it:
indentation-demo
Let's learn the most basic elements first. We enumerate some definitions that you need to memorize before you can understand the semantic of Python language. You will use these elements all the time when you create new code:
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]
A function is a block of code that is executed when it is called. Functions can be used to encapsulate code and make it reusable. They can also be used to pass data between different parts of a program. To define a function in Python we use "def" keyword.
A class is a blueprint for creating objects. Objects are instances of classes. Classes can contain data and methods. Methods are functions that are associated with a class. To define a class in Python, you use the class keyword.
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)
Here is a table that describe all relation operators in Python with example, consider x = 5 to evaluate the expressions:
Symbol | Description | Expression | Result |
---|---|---|---|
== | Equal to | x == 8 | 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 |
Notes: 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.
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 |
There are 35 keywords in Python 3.11. These keywords are reserved words that cannot be used as variable names, function names, or any other identifiers. Python is a statement oriented language. Some statements are using one single keyword but some can combine multiple keywords.
Keyword | Description |
---|---|
and | Logical AND operator |
as | Allows you to give an alias to an object |
assert | Checks if an expression is true |
break | Breaks out of a loop |
class | Defines a class |
continue | Continues to the next iteration of a loop |
def | Defines a function |
del | Deletes an object |
elif | Else-if statement |
else | Else statement |
except | Handles exceptions |
finally | Code that is always executed, regardless of whether an exception is raised |
for | Loop statement |
from | Imports modules |
global | Declares a variable as global |
if | Conditional statement |
import | Imports modules |
in | Checks if an object is in a sequence |
is | Checks if two objects are the same |
lambda | Creates an anonymous function |
not | Logical NOT operator |
or | Logical OR operator |
pass | Does nothing |
Prints a value | |
raise | Raises an exception |
return | Returns a value from a function |
try | Executes code that might raise an exception |
while | Loop statement |
Read next: Variables