Something about programming

Python syntax and build-in types

Previous tutorial: Python interactive shell and interpreting of .py files
Next tutorial: Loops and conditions in Python

In this tutorial we'll learn basic syntax and data types of Python programming language. Compared to other programming languages, Python syntax is very simple.

Comments in Python

Comment is text that is not evaluated by Python interpreter. Comments are needed to explain the code. Like when you have some complex part, you write description for yourself or other coders. Yes, you need to write comments for yourself. When you will read your code in couple months you will not remember why you write the code in such way.

Python comments are marked with # symbol. All text after # and till the end of line is considered as a comment by Python interpreter:

# comment 2 + 1 # another comment

As you can see, you can write comments on lines with the code. On second string only expression 2 + 1 is evaluated. Python interpreter will ignore everything after #.

Besides of #, there is a special construct in Python which is used for commenting - doc string. They are used for describing modules, classes, functions. We will learn all these things in next tutorials. Doc string is indicated by three double quotes: """ doc string """:

""" Here can be description of module, class, method/function """

Indentation and blocks of code in Python

Python uses indentation to denote blocks of code. Loops, conditions, functions, class definitions, all of it should be indented by the same amount of white spaces or tabs).

for i in range(1,100): for j in range(1,100): if i == j: // do something else: pass // placeholder for code

Each next level is indented more. One block of code should be indented by the same amount of spaces. Also pay attentions to colons. Colon in Python means: there will be block of code on next line.

It's common practice to use 4 white spaces for indentation of code. I prefer to use 2, and I always set up editor to convert tabs to 2 spaces. You'll see that a lot in attachment source files of next tutorials.

Primitive built-in data types of Python language

We will discuss several basic data types in Python below. But Python additionally has more complex types, though this is subject of another tutorial.

Numbers

Python allows to use different numbers:

5 # integer number 3.2 # float number 1 + 2j # complex number; j - imaginary unit

Python allows next math operations: + (sum), - (difference), * (multiplication), / (division). For powering ** is used: 2**3 equals 8. Also, there is additional operation - remainder of division %:

3 % 2 # result - 1 8 % 3 # result - 2

I.e. % divides number, and returns remainder without integer part.

In Python we can change the type of the number. Special functions are used for this: int (from integer), float, complex. It's easy to use these constructs:

int(3.14) # result - 3 float(3) # result - 3.0 complex(3) # result - 3 + 0j

These functions allows to indicate obviously what number we want to get. For example, we have some mathematical expression, and we need only integer part of the result.

int( (100 + 32 / 5) * 11 ) # without int result is 1170.4

Such explicit type pointing is called "type casting".

Boolean values in Python: True and False

There are two keywords in Python: True and False, they starts with capitalized letter. If you write them with lower-case first letter, interpreter will show you the error. These two values are called Boolean.

We can cast any value to boolean type with bool function:

bool( 1 ) # True bool( 0 ) # False bool( 323 ) # True bool( "Hello" ) # True bool( "" ) # False

Next values are False in Python:

None # special value in Python for "nothing" False # boolean value 0 # zero (integer) 0.0 # zero (float) 0j # zero (complex number) "" # empty string (see below) () # empty tuple [] # empty list {} # empty dictionary set() # empty set

Any other value that you pass to bool will be evaluated as True. Boolean values are needed when we need to check some condition.

Checking for truth

Very often we need to answer to the question: "Is this expression true or false". For example, if one number is bigger; is the string is empty; is the element belongs to the set:

bool( 1 > 0 ) # False bool( "Hello" == "" ) # False bool( 3 in {1,2,3} ) # True

In this case we are casting expressions result to the bool type. In the next tutorials we will see that it''s not necessary. Python automatically casting expressions to the bool when it's needed to answer to the question: "Is this expression true?".

Strings in Python

In Python string is the text in quotes, double quotes or in three double quotes:

'Hello' "Hello" """Hello"""

You need to clearly understand that some number and this number in the string are two different values:

5 "5"

In Python we can compute string length with the len function:

len("Hello") # 5 len("") # 0

Strings in Python have type str and we can use the function with the same name for casting different values to str type:

str(True) # 'True' str(322) # '322'

Literals in Python

When we see in code just a value (any type: integer or float number, string) - it's a literal:

2 # integer literal 1.5 # float literal False # boolean literal "Hello" # string literal

For now we've discussed five Python data types: int, float, complex, bool, str. These are basic types of the programming language. Now let's see how we can store different values for future usage.

Variables

Variable is a memory cell which stores some value and has name (identifier).

In Python identifier of variable is the string which consists of letters, digits and underscore and which starts from letter or underscore symbol.

Assignment

In (almost) any programming language sign of equality = is used for assignment: value that is on the right-side of the = is moved to the variable on the left-side of the =:

a = 3 _a = 4 _a1 = 5

Here are defined three variables with different values. Now we can use them for computation:

b = a + _a # b = 7 bool( _a < _a1 ) # False

In some programming language variables have strict type - you can't assign to the variable value if they have different types. Python in contrary allow such things:

a = 3 a = "Hello"

We can learn the type of any value, expression or variable with the type function:

type("Hello") # result <class 'str'> a = 3 type(a) # result <class 'int'>

Notice, that this function returns not just name of the type, but tells that it received object of some class. Python is object-oriented language and everything in it is an object. We will learn OOP later.

Operator precedence

All operations in Python have precedence (order of evaluation):

a = 3 + 1 * 2

Here the multiplication will be computed, then sum and then the result will be assigned to variable a. In this example multiplication has highest priority. Precedence of arithmetic operations is the same as in math.

Along with precedence you need to understand associativity of operations - in which order operations with same precedence are evaluated:

1 + 2 - 3 # associativity from left to right a = 1 b = 2 c = 3 a = b = c # = has associativity from right to left

In the last string all three variables get value 3. Firstly b will assign value contained in c, then result will be stored in a.

Statement evaluating

Any expression evaluates in some resulting value. Simple numbers, booleans and strings are evaluated to themselves, these values as we already know are called literals:

5 # number literal 5 True # boolean literal True "Hello" # string literal \'Hello\'

Using operations and functions on literals we can get some value.

Variables are evaluated to the values they contain. When we write name of the variable to the right-side of the =, Python automatically replaces identifier with value of the variable:

a = 1 1 + a # a evaluated to 1, and all expression to 2

Every expression has a result. In some cases Python automatically casting expression result to the needed type. Especially when type bool is needed.

Console output - print

For text output Python 3.x uses print function:

print( "Hello!" )

In Python 2.x print can be called without parentheses:

print "Hello!"

In third version of Python print is actually a function and in the second it's language construct.

Python syntax. Summary

In this tutorial we've discussed basics of Python and it's primitive types. As you may noticed Python has simple and straightforward syntax. Python syntax doesn't suffer from redundancy like other languages. Instead of curly braces Python uses indentation, that additionally gives us readable code. In next tutorials we will learn conditions in Python and will deal with built in data structures: lists, sets, dictionaries.

Comments:

No comments yet