Author: - Post Category: Python, Resources - Date:May 5, 2020

ūüźć Python Crash Course 2020

During the course we will cover the basics but also dig into more advenced
concepts like file manipulation, object oriented programming and testing.

Categories: Python and Resources. Tags: Programming and python.
Programming with Python Crash Course

ūüźć Python is a general purpose programming language, easy to read and it’s definitely worth learning. It can be used to build different types of programs from web based applications to softwares with Graphical user interfaces, command line applications, Machine learning and IT Automation.

Course Introduction

Course Topics

  1. Course Introduction

    A quick introduction to the Programming with Python Crash Course

  2. Environment Setup

    Setup our development environment, Install Python (Windows/Linux/MacOS), Install VSCode and the code runner extension.

  3. Variables

    Learn about variables in Python. How to define a valid variable and invalid variables errors

  4. Strings

    In this module we will study strings, one of the Python basic data types.

  5. Numbers and Booleans

    In this module we will study two more basic data types, Numbers and Booleans in Python.

  6. Lists

    In this module we will cover the basic data type called List, and how to use them.

  7. Dictionaries

    In this module we will cover the basic data type called Dictionary, and how to use them.

  8. Tuples

    In this module we will cover the basic data type called Tuple, and how to use them.

  9. Conditionals

  10. Loops

  11. List Comprehension

  12. Functions

  13. Object-Oriented Programming

  14. Files and CSV Manipulation

  15. Testing

Playlist Completa Corso (Work in Progress)

Programming with Python
#2 Environment Setup

Let’s see how to install Python and a couple of other tools that we will use during the course.

Environment Setup

Windows Installation: 

To install python on windows, visit the website python.org, click the download button to get the installer then open it and follow the instructions. Make sure to check the box during “Add python to your path” during the installation.

Once the installation is completed open the windows power shell and type:

python -V

Install on Linux/MacOS: 

Linux distributions comes with python 2 and 3 preinstalled. to verify that run the following in the terminal

python -v 
python3 -v

The same applies to Mac OS.

If the package is not present in your system you can use the package manager to install it in Linux.

sudo apt install python3

For macOS visit the Download page of Python.org to download it.

Open the python interpreter:

In Linux, open the terminal and type

python3

In Windows power shell

python

Text editor and Python files:

To do this I assume that you already use some sort of text editor or IDE like sublime, Athom or VisualStudio code. If not I reccomend you to use Visual Studio code becase it’s what I will be using during the course.


You can download it at https://code.visualstudio.com/, it’s free.
Once downloaded and installed, start the program and click the extensions tab and install the extention “code runner”


Now that your environment is ready, let’s get started with Python programming.

# 3 Variables

The first building block of most programming languages. Variables.

Variables

The first concept that we will cover are Variables. If you already master other programming languages this is nothing new to you.
A Variable is a word that we define and use to store informations in our program for later use.It can only start with letters and underscore, It can contain numbers and underscore. It cannot start with a number or other characters and cannot contain characters that are notnumbers, letters or underscore. 

# Valid variables: 
_name = "Fabio"
name = "Fabio"
name_1 = "Fabio"
# Invalid: 
-name = "Fabio"
9_name = "Fabio"
name! = "Fabio"

#4 Strings

Strings are sequences of characters. We can write strings in single, double or triple quotes.

Python Crash Course – Strings
'This is a python crash course'
"This is a python crash course"
"""This is a python crash course"""

We¬†can¬†assign¬†stings¬†to¬†a¬†variable¬†and¬†concatenate¬†them¬†using¬†the¬†plus¬†sign”+”¬†or¬†the¬†.format()¬†method.

name = "Fabio"
profession = "Developer"

sentence = name + " is a " + profession

sentence = "{} is a {}".format(name, profession)

We can assign a string to a variable and access single elements or part of the string using squre brackets and the slice method. 

Access a single character:

name = "Fabio"
name[0] 

Using the Slice method:

name[2:]
name[:2]

String Indexing

we can get the position of an element of the string (character) using the index method

name.index("b")

Strings are Immutable:

name[0] = "B" 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

new_name = "B" + name[1:]
print(new_name)
'Babio'

#5 – Numbers and Booleans

Numbers are another basic data type in Python. There are two types of numbers.Integers and float.

15 # integer
15.5 # float

We can use numbers to perform calculations.

# Sum
5+2
# Subtraction
5-2
# Moltiplication
5*2
# Division
10/2

# Exponenet
5**2
# Modulo
16%4
# Floor division
15//4

Like in math operations inside parenteses take precedence. Then the exponent,moltiplication and division, modulo and floor and finallyadditions and subtractions.

Booleans:

A boolean value is either True or False. We use it to take decisions in our code based on a condition.

is_risky = True
is_safe = False

#6 – Lists

A list is a sequenze of elements. usually of the same type but it can contain different elements.

Define a list

To define a list we use square brackets and separate each element with a comma.

[1, 3, 5 , 6 , 7]
["Developer", "Writer", "Student", "Teacher"]

Access a list element:

We can access elements in a list by assigning it to a variable like wedid with strings. Then we can use quare brackets and the index mathod in the same way.

>>> jobs = ["Developer", "Writer", "teacher"]
>>> jobs[0]
'Developer'
>>> jobs[1:]
['Writer', 'teacher']
>>> jobs[:2]
['Developer', 'Writer']
>>> jobs[0:2]
['Developer', 'Writer']
>>> jobs.index("Writer")
1

Add elements

We can do a lot more with lists, like add an element to it using the appendmethod. It adds it at the end of the list.

>>> jobs.append("Front-end engineer")
>>> jobs
['Developer', 'Writer', 'teacher', 'Front-end engineer']
>>>

Insert an element:

we¬†can¬†also¬†insert¬†an¬†element¬†in¬†a¬†specific¬†position.¬†The¬†first¬†argument¬†is¬†the¬†index¬†where¬†we¬†want¬†to¬†intert¬†the¬†element,¬†it’s¬†an¬†integer.if¬†the¬†integer¬†is¬†a¬†number¬†grather¬†than¬†the¬†lenght¬†of¬†items¬†of¬†the¬†list¬†the¬†new¬†element¬†will¬†be¬†inserted¬†at¬†the¬†end.

>>> jobs.insert(0, "SEO")
>>> jobs.insert(10, "Back-end developer")
>>> jobs
['SEO', 'Developer', 'Writer', 'teacher', 'Front-end engineer', 'Back-end developer']
>>>

Remove elements:

We¬†can¬†use¬†pop()¬†to¬†remove¬†elements¬†from¬†the¬†end¬†of¬†the¬†list¬†or¬†a¬†specific¬†elementif¬†we¬†specify¬†it’s¬†index¬†position.

>>> jobs.pop()
'Back-end developer'
>>> jobs.pop(3)
'teacher'
>>> jobs
['SEO', 'Developer', 'Writer', 'Front-end engineer']

Using the remove() method:

We can use remove to delete first occurrence of an element

>>> jobs.append("Developer")
>>> jobs.remove("Developer")
>>> jobs
['SEO', 'Writer', 'Front-end engineer', 'Developer']

Sort elements:

Sort organizes elements in ascending order

>>> jobs
['SEO', 'Writer', 'Front-end engineer', 'Developer']
>>> jobs.sort()
>>> jobs
['Developer', 'Front-end engineer', 'SEO', 'Writer']

Clear the list:

We can remove all elements of a list in two ways

jobs = []
jobs.clear()

Attention: when you see the following symbol ” >>> ” in the code blocks I am executing them inside the Python interpreter. When there is no symbol before the line of code its in a Python file.

#7 – Dictionaries

In¬†this¬†video¬†we¬†are¬†going¬†to¬†cover¬†another¬†basic¬†data¬†type¬†called¬†Dictionary. A¬†dictionary¬†is¬†a¬†sequence¬†of¬†mutable¬†elements.¬†It’s¬†a¬†key¬†value¬†pair¬†elements.¬†Dictionaries¬†are¬†defined¬†withing¬†curly¬†brackets.Its¬†elements¬†are¬†separated¬†by¬†a¬†comma¬†while¬†the¬†key¬†is¬†separated¬†from¬†the¬†value¬†with¬†a¬†semi-colon.

Define a dictionary:

user_stats = {"Name":"Fabio", "Age":40, "Job":"Developer","Skills":["Python","PHP","Laravel", "HTML5", "CSS3","Javascript"]}

A dictionary can contain all type of data types, however, its key is limited to certain data types like strings and numbers.

Access elements:

we can access elements using the keys inside the square brackets or with the get()method.

user_stats["Skills"]
user_stats["Name"]
user_stats["Age"]
user_stats["Job"]

user_stats.get("Skills")

We can also get all values or all keys using the values() and keys() methods.

user_stats.values()
user_stats.keys()

Add elements:

We can add a new element in this way

user_stats["Wife"] = "Serena"

Update elements:

We can assign a new value to an element using the equal sign.

user_stats["Job"] = "Full-stack Engineer"

Update method:

We can also use the update method. This method accepts a dictionary object as paramenter. It actually extends the original dictionary.

user_stats.update({"Interests": ["Coding", "Cycling"]})
print(user_stats)

Remove elements:

We can use the pop method to remove elements using their key.

user_stats.pop("Age")

There is a lot more you can do, for a deep dive check the documentation when you need it.

Clear the dictionary:

With the clear method we can remove all elements in a dictionary.

user_stats.clear()

Or you could assign to the dictionary an empty dictionary, that will work too.

user_stats = {}

In¬†the¬†next¬†video,¬†I’ll¬†show¬†you¬†another¬†basic¬†data¬†type¬†called¬†tuple.¬†See¬†you¬†there.¬†

#8 – Tuples

In¬†this¬†video¬†I’ll¬†give¬†you¬†a¬†brief¬†overview¬†of¬†another¬†basic¬†data¬†type¬†called¬†tuple. A¬†tuple¬†is¬†an¬†immutable¬†sequence¬†of¬†elements.

Define:

It¬†is¬†defined¬†within¬†parentheses¬†and¬†each¬†element¬†is¬†separated¬†by¬†a¬†comma.Elements¬†of¬†a¬†tuple¬†can¬†be¬†of¬†any¬†datatype.Let’s¬†see¬†how¬†to¬†defining¬†a¬†tuple.

user_data = ("Fabio","Pacifici","Developer","Norwich")
print(user_data)

Assign tuples elements to variables

Knowing that a tuple is immutable, allows us to assign each element to a variable in this way

name,last_name,job,city = user_data

Access elements

We¬†can¬†then¬†access¬†the¬†tuple’s¬†elements¬†either¬†using¬†square¬†brackets¬†like we¬†do¬†with¬†other¬†data¬†types¬†or¬†using¬†the¬†newly¬†created¬†variables.

print(user_data[1])
print(last_name)

Slice method:

like with strings, lists and dictionaries we can use the slice method to get a portion of a tuple.

user_data[2:]
user_data[:2]
user_data[1:4]

Add Elements

Tuples are immutable sequence of elements. Meaning that once defined we cannot change its elements. 

However, we can extend the tuple with another tuple using the __add__  special method. This method accepts as parameter another tuple and returns one tuple containing both tuples.

new_data = user_data.__add__((40, "https://fabiopacifici.com"))
print(new_data)

Update:

Attempt¬†to¬†grab¬†one¬†of¬†the¬†elements¬†and¬†replace¬†it’s¬†content¬†will result¬†in¬†a¬†TypeError.

user_data[2] = "Full-Stack Engineer"
# TypeError: 'tuple' object does not support item assignment

So¬†if¬†we¬†want¬†to¬†replace¬†the¬†content¬†of¬†the¬†tuple¬†we¬†can¬†either create¬†a¬†new¬†tuple¬†or¬†replace¬†it’s¬†entire¬†content

user_data = ("Fabio","Pacific","Full-Stack engineer")
print(user_data)

new_user_data = user_data[0:2].__add__(("Developer",40)) 
print(new_user_data)

Index:

We can use the index() method to find the position of an element in the tuple.this method accepts the element as a parameter

user_data.index("Fabio")
# returns 0

Count elements recurrence

The count() method instead returns how many time a given element is present inside the tuple. Returns zero if the element is not in the tuple

user_data.count("Fabio")
# returns 1
user_data.count("Fa")
# returns 0

Remove

We can remove all elements of a tuple by assigning to the variable that stores the tuple an empty tuple. To remove one element from the tuple we have to create a new tuple and exclude the element we want to remove.

user_log = ("Fab", True, "Monday", "Fabio", "Pacifici" )
new_log = user_log[0:2].__add__(user_log[3:])
print(new_log)

new_log = ()
print(new_log)

That’s¬†pretty¬†much¬†it.¬†You¬†can¬†read¬†more¬†about¬†tuples¬†visiting¬†the¬†official python¬†documentation¬†and¬†practice with what we studied in these videos.

#9 – Conditionals

Recording live from Friday 22 May