Expressions, Statements, Variables, Data Types in Python [must read]

Expressions

The most common expressions in Python are numerical, string and boolean.  All of them are considered as data items or d-item. For example, this is a numerical expression:

1

or another more complex math expression should be like this:

1/2+10-500*4

Apart from numerical expression, there are also string expressions:

Hello world

the same stands for concatenation strings, like:

"H" + "e" + "l" + "l" + "o" + " world"

and of course another type of expression might be the boolean expression (derived from Boolean algebra, true/false situations), like:

20>30

that returns a false value for example.

Statements and Variables

There are many kinds of statements, like assignments, for-loops, if statements etc. Now let’s start with assignment statements (and thus introduce variables in the same way).

number = 1

In this example, I am putting the numerical value 1 into a variable called number. The data type of this variable is probably integer.

There is no need to provide a data type for a variable because Python automatically assigns data types based on the values that are assigned into them.

So, here’s another one

number = "one"

Now, I am assigning a string into a variable called number. The data type of this variable is probably string. So, you can see that variables in Python are very flexible. Just assign a value into them and that’s it. Also, you can combine expressions, statements and variables, like this:

num1 = 1
num2 = 2
result = num1 + num2

num1 has the value 1 and num2 has the value 2, so if you add them together you’ll get 3 value which is stored into result variable.

Working with numbers

There are several types of numbers you can work within Python. The most common is the integer numbers

300

or the floating-point numbers:

3.14159

or can also work with hexadecimal, octal and binary numbers.

Standard math operations

Addition

2 + 2

Subtraction

10 - 5

Multiplication

2 * 5

Division

100/10

Modulus (remainder of the division)

4 % 2

in this case, 4 mod 2  return no remainder, 0.

3 % 2

in this case, 3 mod 2 returns 1.

Power

There is an exponent operator (like a^b)

2 ** 10

in this case, 2^10 returns 1024

Alternatively, there is a built-in mathematical function called pow()

pow(2,10)

Python uses the default mathematical order of operations

  1. exponents and roots
  2. multiplication and division
  3. addition and subtraction

if you want to change the order, then use parentheses

Mixed Types

When you are working with integers and floating-point, Python always converts them to be all the same (in this case Python converts integer to floating-point). For example:

6.12 + 5

it returns 11.12 because it actually converts 5 (integer) into 5.0 (floating-point) before doing the addition with 6.12. So every time, Python converts up your data so you never gonna lose anything. This is great and it saves you from type casting.

Built-in functions

pow(number,power)

pow(2,10)

This is identical with 2^10 or 1024.

abs(number)

abs(-10)

It returns the absolute value |-10| = 10

round(number)

round(3.9)

It returns 4

Import math functions

Before using these function you have to import math library. So please add this line:

import math

Notice the math. notation. This shows that these functions are members of the math class

math.sqrt()

math.sqrt(100)

It return the square root of 100, which is 10.

math.floor()

math.floor(5.3452)

Return the floor of 5.3452 as a float, the largest integer value less than or equal to 5.3452. So, it returns 5.0

Python Math Documentation

Working with String

A string is any set of characters. To be more precise, it is a sequence of characters inside single or double quotes. So we can write a string using either single quotes or doubles quotes. FYI, single quotes are more of a standard for Python as they are used more often, while double quotes are more of a standard across other programming languages.

string = 'hello world!'

or

string = "hello world!"

In both ways, the string variable called string holds the string value hello world.

Many time you’re going to see double quotes instead of single quotes. This is due to the fact that most programmers do it out of habit. It isn’t wrong or anything like that, both type of quotes work equally fine, so no prob. Just pick one.

String Operations

Concatenation

One of the most common operations we can perform on strings is concatenation. This means you can combine strings together by adding (using the concatenation operator which is the plus (+) sign) them like if they were numbers (but they are strings instead).

>>> str = string + string + string
>>> str
'hello worldhello worldhello world'

Similarly, you can use multiplication, like this

>>> str = string * 3
>>> str
'hello worldhello worldhello world'

let’s see another example of concatenation:

>>> str = string + ' Goodbye world!'
>>> str
'hello world Goodbye world!'

Concatenation is very important because you are going to need very often to combine data into one variable.

String Length

One of the basic built-in function we can operate for strings is len(). It tells you how many characters are inside a string.

>>> str = 'four'
>>> len(str)
4

Character position

As I told you before, strings in Python are sequence of characters and each character has a unique position. So if you want to see the n-th position of a string you are going to use array notation ( string[n+1] )

  1. First character –> [0] position
  2. Seconds character –> [1] position
  3. Third character –> [2] position
  4. and so on. . . . .

For example, if I want to see the first character of the string:

>>> str = 'paok'
>>> str[0]
'p'

Notice I use str[0] because the first character is located at position zero

For example, if you want to see the seconds character:

>>> str = 'paok'
>>> str[1]
'a'

Slice notation

If you want a portion of a string, you can use slice.

The best way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:

 +---+---+---+---+---+ 
 | H | e | l | p | A |
 +---+---+---+---+---+ 
 0   1   2   3   4   5 
-5  -4  -3  -2  -1

For example if you want the first 2 characters:

>>> str[0:2]
'pa'

or if you want to get all characters before a specified number:

>>> str[:2]
'pa'

or if you want to get all the characters after a specified number:

>>> str[2:]
'ok'

if you want to see the last character:

>>> str[-1]
'k'[/cc]

The split operator

It takes a single argument — the delimiter — and give you back the string converted into a list based on the delimiter.

>>> str = 'Hey, you, come here!'
>>> str.split(',')
['Hey', ' you', ' come here!']

So each word/phrase separated by comma is going to be on its own on a list.

Strip ’em all \m/

It’s often for many but unknown reason, programmers want to remove certain characters from start or end or both of strings. For example let’s say you have unnecessary whitespace in a string which looks ugly. Let’s strip (remove) the whitespace.

>>> str = '      This is a string!!!      '

>>> str.strip()
'This is a string!!!'

or you can just strip the right end of the string using rstrip() method.

str.rstrip()

'      This is a string!!!'

Notice that strip method remove characters only from the beginning and end of strings, not from inside the string.

Working with Boolean Data Type

Boolean data types are either True or False and they are usually generated by comparisons. For example 1 > 2 this indicates a false boolean value. Another way of representation is the binary one: 1 (True), False (0).

Let’s see some examples:

>>> 1 == 1
True

 Notice that the ‘==’ is the equality check, not the assign ‘=’ operator. It simply checks if both sides are equal and returns True (1) if they are, or False (0) if they are not.

You can also store a boolean type into a variable and use this variable later as a flag.

>>> is_greater = 10 > 2
>>> is_greater
True

Working with List data structure

The most simple kind of list is the empty one. This is a plain set of brackets (open and close) and it represents the empty list.

>>> []
[]

If you actually want to create a list with items in it (non-empty), you simply put items in the list separating each item with a comma.

>>> list_of_numbers = [1,2,3,4,5,6,7,8,9,10]
>>> list_of_numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

If you want to access in each item you have to use index notation (aka array notation).

  1. First element would be —-> list_of_numbers[0]  —-> 1
  2. Second element would be —-> list_of_numbers[1] —-> 2
  3. and so on . . . . . .

For example, if you want to add the first element with the last element ( I reming you that you can simply use the recursive way for the last item, which is simpler to do than looking for the last one )

>>> list_of_numbers[0] + list_of_numbers[-1]
11

which is similar to

>>> list_of_numbers[0] + list_of_numbers[9]
11

Slice notation

You can also work with slice notation and grab a portion of the list. Let’s say you want only the first 5 items, there are several ways to do it:

>>> list_of_numbers[0:5]
[1, 2, 3, 4, 5]

or

>>> list_of_numbers[:5]
[1, 2, 3, 4, 5]

or recursively

>>> list_of_numbers[:-5]
[1, 2, 3, 4, 5]

Slice with step

The third argument in slice notation is the step

>>> list_of_numbers[0:9:3]
[1, 4, 7]

Length of list

You can have the length of list (how many items it contains) by using the len method

>>> len(list_of_numbers)
10

String Lists

You can also have a list which contains strings as items separated by comma.

>>> strlist = ['emeis', 'mazi', 'gia', 'mia', 'zoi']
>>> strlist
['emeis', 'mazi', 'gia', 'mia', 'zoi']

Combine lists (concatenate)

You can simply combine lists together by using the concatenation operator which is the plus sign (+). Take a look here:

>>> strlist = ['emeis', 'mazi', 'gia', 'mia', 'zoi']
>>> strlist
['emeis', 'mazi', 'gia', 'mia', 'zoi']
>>> strlist2 = ['aete', 'aete', 'dikefale']
>>> combined_list = strlist + strlist2

>>> combined_list
['emeis', 'mazi', 'gia', 'mia', 'zoi', 'aete', 'aete', 'dikefale']

Replicate a list

Just use the multiplication operator and point the number of times you want to do the repetition.

>>> message = ['warning! ']
>>> message * 5
['warning! ', 'warning! ', 'warning! ', 'warning! ', 'warning! ']

Nested Lists

You can also have lists inside lists:

>>> names = ['Peter', 'Bruce', ['Clark','Kent'], 'Thor', 'Loki']
>>> names
['Peter', 'Bruce', ['Clark', 'Kent'], 'Thor', 'Loki']

>>> names[0]
'Peter'
>>> names[2]
['Clark', 'Kent']
>>> names[2][1]
'Kent'

Working with Dictionary data structure

Dictionary in Python is a way to look up a value based on a key, just like any other dictionary. The simpler dictionary is an empty one, which is created by two curly braces {}

{}

That’s not of much use, so let’s create a dictionary that actually has some data in it. The pattern is similar to this:

{key:value, key2:value2, key3,value3}
>>> iphone = {'Antonis':68424252, 'Orestis':6978833231, 'Mom':2310666999}
>>> iphone
{'Antonis': 68424252, 'Mom': 2310666999, 'Orestis': 6978833231}

How to retrieve a value

You simply call the key and then its value is automatically retrieved by default

>>> iphone['Mom']
2310666999

Notice that retrieval is implemented using normal brackets [] instead of curly ones {}.

>>> iphone{'Mom'}
File "<stdin>", line 1
iphone{'Mom'}
^
SyntaxError: invalid syntax

How am I supposed to know the keys of the dictionary ?

Right! You can use the keys() function in order to get all the keys of a dictionary.

>>> iphone.keys()
['Antonis', 'Mom', 'Orestis']

and of course you can have access to all their values too, using the values() function.

>>> iphone.values()
[68424252, 2310666999, 6978833231]

Working with Tuple data structure

First of all you need to know that a Tuple is very very … very similar to a List data structure. Syntax-wise, Tuples use a different delimiter and make use of parentheses instead of brackets. The major difference is that Tuples cannot be modified after their creation. So every time you modify a tuple’s item, another copy of tuple is created. It basically copies itself and doesn’t change the prototype. So, Tuples are little less efficient that Lists. That’s the difference between tuples and lists, because in lists you can change items “in-place”.

Let me create an empty Tuple:

>>> empty = ()
>>> empty
()

Let’s create an non-empty tuple:

>>> tuple = (1,2,3,4,5)
>>> tuple
(1, 2, 3, 4, 5)

If you want to access in each Tuple’s item individually, you have to use the index notation just like lists. For example:

>>> tuple[1]
2

Sure, you can concatenate:

>>> tuple[1] + tuple[2] * 12
38

We can return the length of the Tuple by using len() method:

>>> len(tuple)
5

and yes sir, slices work too and you can concatenate them in order to combine tuples together:

>>> num1= tuple[:2]
>>> num1
(1, 2)
>>> num2 = tuple[2:]
>>> num2
(3, 4, 5)
>>> numbers = num1 + num2
>>> numbers
(1, 2, 3, 4, 5)

as you can see, all the operation that work on Lists, apply in Tuples too. But there is one thing you can do with Tuples that you can’t do with Lists. A tuple can be used as a key in a dictionary!