+27833657551     admin@starscientist.org
+27833657551     admin@starscientist.org

# Python for Beginners (part-2)

This is a continuation of the python for beginners’ lessons in the previous page. We have seen how to install python, how to use the python console, and how to get help. I have also introduced you to python identifiers and variables. In this section, we will now look into different python data types and their methods.

## Getting started with Python (part-2)

### Python Data types

There are two main categories of Python data types: immutable and mutable. In Python, immutable data types are objects whose values cannot be changed or updated once they are created. Inversely, mutable objects can be changed or updated after creation. The mutability or immutability of Python objects depends on their data types. For example, string, tuple, int, float, complex, decimal, bool, range, complex, frozenset, and bites are immutable. Mutable objects include list, dictionary, numpy arrays, set, and bitearray. We will learn more about them in the next sections.

#### Python Numeric Types

Numeric types fall under the categories of immutable Python data types. There are three distinct numeric types:

Integers: represent whole numbers and negative numbers without fractional parts or complex components
Example: …, -10, -9, -8,…, 0, 1,.., 8, 9, 10,… Note that other number systems are supported: Base 2 (Binary), Base 8 (Octal), Base 16 (Hexadecimal). Integer numbers are of type int in Python 3.

``````>>>type(-10000)
<class 'int'>
>>>0b1100100 # Binary
100
>>>type(0b1100100)
<class 'int'>
>>>0o144 # Octal
100
>>>type(0o144)
<class 'int'>
>>>0x64 # Hexadecomal
100
>>>type(0x64)
<class 'int'>``````

Notice that we had to put a prefix before the numbers to distinguish them from the usual base 10 systems, 0b for binary, 0o for octal, and 0x for hexadecimal numbers.

Floating point numbers: represent any real number with a decimal point
Example: 3.5, 3.5e+10, 53E-10, 53E+10. Floating point numbers are of type int in Python.

``````>>>3.5
3.5
>>>type(3.5)
<class 'float'>
>>>53E+10
530000000000.0
>>>type(53E+10)
<class 'float'>``````

Complex numbers: To represent complex numbers of the form a + jb where a and b are real numbers and j is an imaginary number with j2 = -1. Python complex numbers are written as a + bj or a+bJ. Complex numbers can also be created using the complex() class. Complex numbers are of type complex.

``````>>>1 + 5j
(1+5j)
>>>1 + 5J
(1 + 5j)
>>>complex(1, 5)
(1+5j)
>>>type(1 + 5J)
<class 'complex'>``````

The real part and the imaginary part of a complex variable c can be obtained using c.real and c.imag, respectively.

``````>>>c = 1 + 5j
>>>c.real
1.0
>>>c.imag
5.0``````

#### Boolean types

Python boolean data types have two possible values: True or False. Comparison operators return a boolean value: ==, !=, >, >=, < , <= . Expressions that return a boolean value are called boolean expressions.

``````>>>5 == 5
True
>>>type(True)
<class 'bool'>
>>>3 != 5
True
>>>3 > 5
False
>>>3 < 5
True
>>>5 <= 5
True
``````

Note that True has a value of 1 and False has a value of 0 internally. Therefore, it is completely Ok to do the following:

``````>>>complex(True, False)
(1+0j)
>>>True + 10
11
>>>True + False
1
>>>True * False
0``````

Logical operators are typically (but not necessarily) used with boolean expressions to yield a single boolean value (True or False). There are three logical operators in Python: and, or, not.

``````>>>(1 == 1) or (3 > 24)
True
>>>(1 == 1) or (3 < 24)
True
>>>(1 == 1) and (3 < 24)
True
>>>(1 == 1) and (3 > 24)
False
>>>not (1 == 1)
False``````

The or operator returns True if any of the boolean operands is True. Python then returns the value of the first True operand and stops evaluating the rest of the expressions. The or operator returns False if everything is False and yields the value of the last operand.

``````>>>(1==3) or (1==1) or (5 <10)
True
# (1 ==3) is False, (1==1) is True so Python does not care about evaluating (5<10).
>>>False or True or False
True
>>> False or False or False
False
>>>() or 10 or {}
10
# () is False, 10 is True, {} is False and thus the result is 10
>>>() or {} or []
[]
# () is False, {} is False, [] is False. Since all expressions are False, Python returns the last operand which is [].
>>>0 or 1 or 20
1``````

The and operator return False if any of the operands are False. Python yields the value of the first False operand and does not evaluate the rest of the expressions. The result of the and operator is True if everything is True. In this case, Python returns the value of the last operand.

``````>>>(1==3) and (1==1) and (5 <10)
False
#(1==3) is False and thus Python stops evaluating the rest of the expressions
>>>False and True and False
False
>>>True and True and True
True
>>>() and 10 and {}
()
>>>() and {} and []
()
>>>0 and 1 and 20
0
>>>30 and 1 and 20
20``````

The not operator reverse the value of boolean expressions. Therefore not True is False and not False is True.

``````>>>not True
False
>>>not False
True
>>>not {}
True
>>>not 0
True
>>>not 10
False``````

#### Strings

Strings are a sequence of characters enclosed in single quotes, double quotes or triple quotes. They are usually used to store text, the name of persons, things or animals.

``````>>>myname = "Ianja"
>>>type(myname)
<class 'str'>
>>>message = "Python is a versatile programmimg language!"
``````

To create multi-line strings, triple quotes can be used.

``````multi_line_string	=	"""This	is	a multi-line string created using triple quotes.
This	is	the	second line.
And this is	the	third	line."""
print(multi_line_string)``````

Upon executing the above code, we get the following output

``````This is a multi-line string created using triple quotes.
This is the second line.
And this is the third line.``````

Muli-line strings can also be created using single quotes or double-quotes. In this case, the \n escape character must be used:

``````multi_line_string = "This is a multi-line string created using double-quotes. \n This is the second line.\n And this is the third line."
print(multi_line_string)``````

This produces the following:

``````This is a multi-line string created using double-quotes.
This is the second line.
And this is the third line.``````

The problem with the above expression is that the line is very long. Python style guide suggests that the maximum line length should be 79 characters. To comply with this guideline, we can enclose the string in round brackets () as follows and get the same output as above:

``````multi_line_string = ("This is a multi-line string created using double-quotes\n"
"This is the second line.\n"
"And this is the third line.")
print (multi_line_string) ``````

String falls into the mutable Python data types and thus, it cannot be changed once it is created. Let’s see this in the following code.

``````>>> strname = "This is a string"
>>> strname.upper() # makes all characters uppercase
'THIS IS A STRING'
>>> strname # the original string has not been changed
'This is a string'
>>> strname = 'A' # Let's try to change the first character
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
``````

#### Python Compound Data Types

##### Lists

Python lists are ordered and mutable data types. They can be created by placing items inside a square bracket: items= [item1, item2, item3,…]. The items inside [] can be of any data types. Therefore, a list can be placed inside a list.

``````>>> mylist = [1, 4.5, True, complex(1,2)]
>>> mylist
[1, 4.5, True, (1+2j)]
>>> type(mylist)
<class 'list'>
>>> list_of_list = [1,2,3,[],[2,3,5]]
>>> list_of_list
[1, 2, 3, [], [2, 3, 5]]
>>>mylist = "ianja"
>>>mylist.count(ianja, 50)``````

Lists have many interesting properties and built-in methods.