.DS_Store (6148, 2022-01-28)
.ipynb_checkpoints (0, 2022-01-28)
.ipynb_checkpoints\intro_to_python-checkpoint.ipynb (211038, 2022-01-28)
.ipynb_checkpoints\python-basics-checkpoint.ipynb (108915, 2022-01-28)
py-built-func.jpg (118071, 2022-01-28)
python-basics.ipynb (108915, 2022-01-28)
# Basic of Python Programming Language
This is a practical introduction to Python Programming Language. The style of this repo was inspired by [Chip Huyen Cool Python repo](https://github.com/chiphuyen/python-is-cool). You can find the companion notebook [here](https://github.com/Nyandwi/python_basics/blob/main/python-basics.ipynb). For advanced Python concepts, check [this repo](https://github.com/Nyandwi/PythonPro)(work in progress)!
Python is an interpreted, high-level, and general purpose programming language that was designed for efficiency, readability, and simplicity.
Python design philosophy emphasizes simplicity and code readability. There are about 19 Python design guiding principles, the top 8 being:
* Beautiful is better than ugly.
* Explicit is better than implicit
* Simple is better than complex
* Complex is better than complicated
* Readability counts
* Now is better than ever
* If the implementation is hard to explain, it's a bad idea.
* If the implementation is easy to explain, it may be a good idea.
More design rules can be found in the [Zen of Python](https://en.wikipedia.org/wiki/Zen_of_Python). You can also display them by importing this(`import this`) in any Python interpreter.
```python
import this
```
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Python is a popular and go-to programming language in different tech communities, most notable in machine learning and data science. It is sometimes referred to as [“batteries included”](https://docs.python.org/3/tutorial/stdlib.html) due to its rich standard library. Below are more elaborated advantages of Python:
* It is simple to read and write: Python syntaxes are very easy to write and easy to recall as well.
* It has a beautiful design and built-in data types.
* It has thousands of great libraries in many disciplines.
* Supportive communities: Good documentation, courses, tutorials, social groups.
* Easy to learn and use due to its simple syntaxes which feel like a natural language.
This introduction will cover the following:
* [1. Variables, Numbers and Strings](#1)
* [1.1 Variables](#1-1)
* [1.2 Numbers](#1-2)
* [1.3 Strings](#1-3)
* [2. Data Structures](#2)
* [2.1 Lists](#2-1)
* [2.2 Dictionaries](#2-2)
* [2.3 Tuples](#2-3)
* [2.4 Sets](#2-4)
* [3. Comparison and Logic Operators](#3)
* [4. Control Flow](#4)
* [4.1 If Condition](#4-1)
* [4.2 For Loop](#4-2)
* [4.3 While Loop](#4-3)
* [5. Functions](#5)
* [6. Lambda Functions](#6)
* [7. Built in functions](#7)
* [7.1 Map Function](#7-1)
* [7.2 Filter Function](#7-2)
* [8. More Useful Python Functions](#8)
* [8.1 List Comprehension](#8-1)
* [8.2 Enumerate Function](#8-2)
* [8.3 Zip Function](#8-3)
*******************
## 1. Variables, Numbers, and Strings
### 1.1 Variables
Below are quick notes about Python variables and other most important things to know before writing actual Python code:
* `A Variable` is a location in memory where we store the data.
* `A variable` in Python can either be of 3 data types: `integer`, `float`, or a `string`. Data type specifies the category of the variables.
* We can use `type(variable_name)` to find the type of given `variable_name`.
* In Python, we use `#` to add `comments`. Comments do not change anything and are not compiled.
* If your comment is longer than one line, you can use triple quotes. The lines inside triple quotes are ignore during runtime.
```
"""
In Python, there is no official way to write long comments, but you can use triple quotes.
The sentence between triple quote are ignored at runtime. You can also use single quote('''....'''). Python treats single quote as double quotes in many scanerios such as strings representation.
Guido also agreed it works: https://twitter.com/gvanrossum/status/112670605505077248
"""
```
* We also use `=` to assign a value to the name of variable. Example: `var_name = 1`. Note that it's different to comparison operator of equal to (`==`).
* We can use `print()` to display the value of variable or the results of any expression.
* Each line of the code start on the new line.
* Be aware of indentations. Python is serious about them.
```python
# EXAMPLE OF CREATING A VARIABLE
# We use # to add comment, it won’t run or affect the code
# You use = to assign a value to the name of the variable.
# Each code starts on the new line. No semicolon or {}
# Python is awesome. You do not need to provide the data type of variable when creating it.
int_var = 1
str_var = 'Hundred'
```
*******************
### 1.2 Numbers
Numbers in Python can either be integers `int` or floats `float`. Integer are real, finite, natural or whole numbers. Take an example: `1`,`2`,`3`,`4` are integers. Floats are numbers that have decimal points such as`4.6`, `6.0`, `7.7`. Note that `4.0` is considered as a float data type too. Recently, Karpathy, AI Director at Tesla posted that [floats are not real](https://twitter.com/karpathy/status/1475317897660612617).
We can perform operations on numbers. The operations that we can perform include addition, multiplication, division, modular, etc...
```python
int_var = 10
float_var = 12.8
type(int_var)
```
int
```python
type(float_var)
```
float
```python
# Numeric Operations
# Addition
1 + 100
```
101
```python
# Multiplication
1 * 100
```
100
```python
# Division
1 / 100
```
0.01
```python
# Floor division
7 // 2
```
3
```python
# Modular (%)
# This is the remainder or a value remaining after dividing two numbers
# 100 / 1 = 100, remainder is 0
100 % 1
```
0
```python
1 % 100
```
1
```python
10 % 2
```
0
```python
# Powers
# 1 power any number is 1 always
1 ** 100
```
1
```python
2 ** 2
```
4
```python
# We use print() to display the results of the operations or a variable
print(1 + 100)
```
101
*******************
### 1.3 Strings
Python supports strings. String is a sequence of characters.
Strings are one of the commonly used and important data types. Most problems involve working with strings. Thus, knowing how to work with strings is an incredible thing.
Strings are expressed in either `"..."` or `'...'`.
```
"text inside here will be a string"
'text inside here will also be a string'
```
We can manipulate strings in many ways. A simple example is to concat the strings.
```python
str_var = 'One'
str_var2 = 'Hundred'
```
```python
str_var + str_var2
```
'OneHundred'
```python
str_var + ' ' + 'and' + ' '+ str_var2 + '.'
```
'One and Hundred.'
```python
# We can use print() to display a string
print(" This is a string")
```
This is a string
```python
# We can also compare strings to check whether they are similar.
# If they are similar, case by case, comparison operator returns true. Else false
"A string" == "a string"
```
False
```python
"A string" == "A string"
```
True
#### Strings Methods
Python provides many built-in methods for manipulating strings. As a programmer, knowing typical string methods and how to use them will give you a real leverage when working with strings.
There are many string methods. You can find them [here](https://docs.python.org/2.5/lib/string-methods.html). Let's see some common methods.
```python
sentence = 'This IS A String'
```
```python
# Case capitalization
# It return the string with first letter capitalized and the rest being lower cases.
sentence.capitalize()
```
'This is a string'
```python
# Given a string, convert it into title (each word is capitalized)
sentence_2 = 'this is a string to be titled'
sentence_2.title()
```
'This Is A String To Be Titled'
```python
# Converting the string to upper case
sentence.upper()
```
'THIS IS A STRING'
```python
# Converting the string to upper case
sentence.lower()
```
'this is a string'
```python
# Splitting the string
sentence.split()
```
['This', 'IS', 'A', 'String']
Lastly, we can use `replace()` method to replace some characters in string with another characters. Replace method takes two inputs: characters to be replaced, and new characters to be inserted in string, `replace('characters to be replaced', 'new characters')`.
Example, given the string "This movie was awesome", replace the world `movie` with `project`.
```python
stri = "This movie was awesome"
stri.replace('movie', 'project')
```
'This project was awesome'
```python
# In the following string, replace all spaces with `%20'
stri_2 = "The future is great"
stri_2.replace(' ', '%20')
```
'The%20future%20is%20great'
As you can see, strings methods are powerful and can save you time. Remember one of the Python philosophies that we saw in the beginning: `Simple is better than complex`.
## 2. Data Structures
Data structures are used to organize and store the data. Algorithms supports operations on data.
Python has 4 main data structures: `Lists`, `Dictionaries`, `Tuples` and `Sets`.
*******************
### 2.1 List
A list is a set of ordered values. Each value in a list is called an `element` or `item` and can be identified by an index. A list supports different data types, we can have a list of integers, strings, and floats.
What we will see with Python lists:
- Creating a list
- Accessing elements in a list
- Slicing a list
- Changing elements in a list
- Traversing a list
- Operations on list
- Nested lists
- List methods
- List and strings
#### Creating a List
A python list can be created by enclosing elements of similar or different data type in square brackets `[...]`, or with `range()` function.
```python
# Creating a list
week_days = ['Mon', 'Tue', 'Wed', 'Thur','Fri']
even_numbers = [2, 4, 6, 8, 10]
mixed_list = ['Mon', 1, 'Tue', 2, 'Wed', 3]
# Displaying elements of a list
print(week_days)
```
['Mon', 'Tue', 'Wed', 'Thur', 'Fri']
```python
# Creating a list with range()
nums = range(5)
for i in nums:
print(i)
```
0
1
2
3
4
#### Accessing the elements of the list
We can access the a given element of the list by providing the index of the element in a bracket. The index starts at 0 in Python.
```python
# Accessing the first elements of the list
week_days[0]
```
'Mon'
```python
even_numbers[2]
```
6
```python
# Getting the last element of the list
print(even_numbers[-1])
```
10
#### Slicing a list
Given a list, we can slice it to get any parts or combination of its elements forming another list.
```python
# Get the elements from index 0 to 2. Index 2 is not included.
week_days = ['Mon', 'Tue', 'Wed', 'Thur','Fri']
week_days[0:2]
```
['Mon', 'Tue']
```python
# Get elements from the last fourth elements to the first
# -1 starts at the last element 'Fri', -2 second last element `Thur'..... -4 to 'Tue'
week_days[-4:]
```
['Tue', 'Wed', 'Thur', 'Fri']
```python
# Get all elements up to the fourth index
week_days[:4]
```
['Mon', 'Tue', 'Wed', 'Thur']
```python
# Get all elements from the second to the last index
week_days[2:]
```
['Wed', 'Thur', 'Fri']
You can use `[:]` to copy the entire list.
```python
week_days[:]
```
['Mon', 'Tue', 'Wed', 'Thur', 'Fri']
#### Changing elements in a list
Python lists are mutable. We can delete or change the elements of the list.
```python
names = ['James', 'Jean', 'Sebastian', 'Prit']
names
```
['James', 'Jean', 'Sebastian', 'Prit']
```python
# Change 'Jean' to 'Nyandwi' and 'Sebastian' to 'Ras'
names[1:3] = ['Nyandwi', 'Ras']
names
```
['James', 'Nyandwi', 'Ras', 'Prit']
```python
# Change 'Prit' to Sun
names[-1] = 'Sun'
names
```
['James', 'Nyandwi', 'Ras', 'Sun']
```python
# Change `James` to ``Francois`
names[0] = 'Francois'
names
```
['Francois', 'Nyandwi', 'Ras', 'Sun']
In order to delete a given element in a list, we can empty slice it but the better way to delete element is to use `del` keyword.
```python
# Delete Nyandwi in names list
del names[1]
names
```
['Francois', 'Ras', 'Sun']
If you know the index of the element you want to remove, you can use `pop()`. If you don't provide the index in pop(), the last element will be deleted.
```python
names = ['James', 'Jean', 'Sebastian', 'Prit']
names.pop(2)
names
```
['James', 'Jean', 'Prit']
Also, we can use `remove()` to delete the element provided inside the remove() method.
```python
names = ['James', 'Jean', 'Sebastian', 'Prit']
names.remove('James')
names
```
['Jean', 'Sebastian', 'Prit']
We can also use `append()` to add element to the list.
```python
# Adding the new elements in list
names = ['James', 'Jean', 'Sebastian', 'Prit']
names.append('Jac')
names.append('Jess')
names
```
['James', 'Jean', 'Sebastian', 'Prit', 'Jac', 'Jess']
#### Traversing a list
There are times that we may need to go over the list to read the elements of the list or perform iterative operations. We can use `for loop` to traverse through the list.
```python
# Given a list names, use for loop to display its elements
names = ['James', 'Jean', 'Sebastian', 'Prit']
for name in names:
print(name)
```
James
Jean
Sebastian
Prit
```python
# Given a list nums, add 1 to the first element, 2 to the second, 3 to 3rd element, 4 to 4th element
# Example: nums = [1,2,3,6] will be nums_new = [2,4,6,10]
nums = [1, 2, 3, 6]
nums_new = []
for i in range(len(nums)): #len(nums) gives the length of the list
num = nums[i] + i + 1
nums_new.append(num)
nums_new
```
[2, 4, 6, 10]
#### Operations on list
```python
# Concatenating two lists
a = [1,2,3]
b = [4,5,6]
c = a + b
c
```
[1, 2, 3, 4, 5, 6]
```python
# We can also use * operator to repeat a list a number of times
[None] * 5
```
[None, None, None, None, None]
```python
[True] * 4
```
[True, True, True, True]
```python
[1,2,4,5] * 2
```
[1, 2, 4, 5, 1, 2, 4, 5]
#### Nested lists
```python
# Creating a list in other list
nested_list = [1,2,3, ['a', 'b', 'c']]
# Get the ['a', 'b', 'c'] from the nested_list
nested_list[3]
```
['a', 'b', 'c']
```python
# Indexing and slicing a nested list is quite similar to normal list
nested_list[1]
```
2
#### List Methods
Python also offers methods which make it easy to work with lists. We already have been using some list methods such as `pop()` and `append()` but let's review more other methods.
```python
# Sorting a list with sort()
even_numbers = [2,14,16,12,20,8,10]
even_numbers.sort()
even_numbers
```
[2, 8, 10, 12, 14, 16, 20]
```python
# Reversing a string with reverse()
even_numbers.reverse()
even_numbers
```
[20, 16, 14, 12, 10, 8, 2]
```python
# Adding other elements to a list with append()
even_numbers = [2,14,16,12,20,8,10]
even_numbers.append(40)
even_numbers
```
[2, 14, 16, 12, 20, 8, 10, 40]
```python
# Removing the first element of a list
even_numbers.remove(2)
even_numbers
```
[14, 16, 12, 20, 8, 10, 40]
```python
## Return the element of the list at index x
even_numbers = [2,14,16,12,20,8,10]
## Return the item at the 1st index
even_numbers.pop(1)
```
14
```python
# pop() without index specified will return the last element of the list
even_numbers = [2,14,16,12,20,8,10]
even_numbers.pop()
```
10
```python
# Count a number of times an element appear in a list
even_numbers = [2,2,4,6,8]
even_numbers.count(2)
```
2
#### List and strings
We previously have learned about strings. Strings are sequence of characters. List is a sequence of values.
```python
# We can convert a string into list
stri = 'Apple'
list(stri)
```
['A', 'p', 'p', 'l', 'e']
```python
# Splitting a string produces a list of individual words
stri_2 = "List and Strings"
stri_2.split()
```
['List', 'and', 'Strings']
The split() string method allows to specify the character to use a a boundary while splitting the string. It's called delimiter.
```python
stri_3 = "state-of-the-art"
stri_3.split('-')
```
['state', 'of', 'the', 'art']
*******************
### 2.2 Dictionaries
Dictionaries are powerful Python builtin data structure that are used to store data of key and values. A dictionary is like a list but rather than using integers as indices, indices in dictionary can be any data type. Also, unlike lists, dictionary are unordered. Dictionaries dont guarrantee keeping the order of the data.
Generally, a dictionary is a collection of key and values. A dictionary stores a mapping of keys and values. A key is what we can refer to index.
What we will see:
- Creating a dictionary
- Accessing values and keys in dictionary
- Solving counting problems with dictionary
- Traversing a dictionary
- The setdefault() method
#### Creating a dictionary
We can create with a `dict()` function and add items later, or insert keys and values right away in the curly brackets { }. Let's start with dict() function to create an empty dictionary.
```python
# Creating a dictionary
countries_code = dict()
print(countries_code)
```
{}
You can verify it's a dictionary by passing it through `type()`.
```python
type(countries_code)
```
dict
Let's add items to the empty dictionary that we just created.
```python
# Adding items to the empty dictionary.
countries_code["United States"] = 1
```
```python
countries_code
```
{'United States': 1}
Let's create a dictionary with {}. It's the common way to create a dictionary.
... ...