To be able to follow this tutorial, you have to have installed:
1. Python 3
2. An IDE for Python.
Watch this video on how to install Python 3 and Visual Studio Code IDE:
If you choose to use Visual Studio Code, see this video on how to create and run a Python script in Visual Studio Code:
Execute this:
import datetime
x = datetime.datetime.now()
print(x)
If you got as output the current date and time, then everything is working great! Now we can go on with the rest of the tutorial.
Python is made up of objects.
2, 100, 3.12, and "Hello" are four examples of Python objects. There are different categories of objects. We call these categories types.
2 and 100 are integer types. 3.12 is a float type. "Hello" is a string type.
rank = 10
eggs = 12
people = 3
temperature = 10.2
rainfall = 5.98
elevation = 1031.88
message = "Welcome to our online shop!"
name = "John"
serial = "R001991981SW"
members = ["Sim Soony", "Marry Roundknee", "Jack Corridor"]
pixel_values = [252, 251, 251, 253, 250, 248, 247]
phone_numbers = {"John Smith": "+37682929928", "Marry Simpons": "+423998200919"}
volcano_elevations = {"Glacier Peak": 3213.9, "Rainer": 4392.1}
Unlike other types, dictionaries are made of keys and values.
You can extract dictionary keys with:
phone_numbers.keys()
And dictionary values with:
phone_numbers.values()
vowels = ('a', 'e', 'i', 'o', 'u')
one_digits = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
Each object category/type has its methods. Integers have their methods, strings have their own, and so on. A method is an operation you can apply to an object. For example, you can apply a replace method to a string object to replace a character in a string with another character.
Here’s how to use the replace() method:
"hello".replace("e", "i")
The above will convert the string “hello” to “hillo”.
If you want to find out what methods you can apply to a certain type of object, go to the Python Shell and write:
dir(str)
dir(list)
dir(dict)
For example, you will see that str(list) returns a bunch of methods. The method count() is one of them. Methods are always accessed from the object using a dot notation:
"hello".replace("e", "i")
['a', 'b', 'c', 'c', 'e'].count('c')
If you want to know how a certain method is used, write on the Python Shell:
help(str.replace)
help(list.count)
Attributes are tied to object types. There are also things called functions that are not tied to any specific attribute. Think of them as “loose”.
You can get a list of functions on the Python Shell with:
dir(__builtins__)
While a method is applied only to its associated type, a function usually can be applied to different types:
max([1,4, 2]) #Returns 4, the max number of the list
max("aabwccd") #Returns w, letter closer to the end of the alphabet
len([1, 4, 2]) #Returns 3, the number of items for the list
len("aabwccd") #Returns 7, the number of characters for the string
When you need to extract or access a certain piece, or slice of a list, or maybe a string, it’s a good idea to have a clear understanding of how these data types are indexed. You should know that list, strings and tuples have a positive and a negative index system.
Each item of a list has an invisible positive index attached to itself:
["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
0 1 2 3 4 5 6
Each item of the list also has an invisible negative index attached to itself:
["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
-7 -6 -5 -4 -3 -2 -1
Say, we want to access the first three items of the list below. This is how you do it using positive indexing:
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days[:3]
Output:['Mon', 'Tue', 'Wed']
If you want to access items that are closer to the end of the list, it’s easier to use the negative indexing system:
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days[-3:]
Output: ['Fri', 'Sat', 'Sun']
Access every item on the list, but the last item::
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
days[:-1]
Output: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
You can use the same [:] syntax to access characters from a string or from a tuple.
Access a single value in a dictionary:
phone_numbers = {"John Smith":"+37682929928", "Marry Simpons":"+423998200919"}
phone_numbers["Marry Simpsons"]
In this tutorial, you used some built-in functions such as max and len. These are functions defined by the developer team who developed Python. You can create your own functions too.
Let’s define a function that calculates the volume of a cube given its side:
def cube_volume(a):
return a * a * a
The above is just the definition of a function. To use the function, you need to call the function. You can use different input values when you call a function:
cube_volume(4)
cube_volume(6)
Conditionals are blocks of Python code that check if a condition is true or false and perform an action depending on that condition. They enable your program to make decisions.
Here’s a conditional that checks if the string “hello” is in string “hello there”:
message = "hello there"
if "hello" in message:
print("hi")
else:
print("I don't understand")
You can use elif if you want to check for multiple case scenarios:
message = "hello there"
if "hello" in message:
print("hi")
elif "hi" in message:
print("hi")
elif "hey" in message:
print("hi")
else:
print("I don't understand")
When working with conditionals, you can use the Python logical operators and and or.
We use the and operator to check if two conditions are True at the same time:
x = 1
y = 1
if x == 1 and y == 1:
print("Yes")
else:
print("No")
Output is Yes since both x and y are 1.
We use the or operator to check if at least on condition is True:
x = 1
y = 2
if x == 1 or y==2:
print("Yes")
else:
print("No")
Output is Yes since x is 1.
If you want your program to receive input from the user via the command-line you should use the input function:
name = input("Enter your name: ")
The input function halts the execution of the program and gets text input from the user. The input function converts any input given by the user to a string, but if you want you can convert the input back to a integer, or a float, and this is how you do it:
experience_months = input("Enter your experience in months: ")
experience_years = int(experience_months) / 12)
Sometimes you have a value stored in a variable, and you want to dynamically insert that value into a string. This is how you do it:
name = "Sim"
experience_years = 1.5
print("Hi {}, you have {} years of experience".format(name, experience_years))
Output: Hi Sim, you have 1.5 years of experience.
A for loop is a block of code that performs batch operations.
Here is an example of a for loop that turns all the characters of a string into uppercase:
for letter in 'abc':
print(letter.upper())
Output:
A
B
C
The name after for (e.g., letter) is just a variable name.
This is how you can loop over dictionary keys:
phone_numbers = {"John Smith":"+37682929928","Marry Simpons":"+423998200919"}
for value in phone_numbers.keys():
print(value)
Output:
John Smith
Marry Simpsons
This how you can loop over dictionary values:
phone_numbers = {"John Smith":"+37682929928","Marry Simpons":"+423998200919"}
for value in phone_numbers.values():
print(value)
Output:
('John Smith', '+37682929928')
('Marry Simpons', '+423998200919')
A while loop is a block that will run as long as a condition is True:
while datetime.datetime.now() < datetime.datetime(2090, 8, 20, 19, 30, 20):
print("It's not yet 19:30:20 of 2090.8.20")
The loop above will print out the string inside print() over and over again until the 20th of August, 2090.
A list comprehension is an expression that creates a list by iterating over another container.
Here you can see a basic list comprehension:
[i*2 for i in [1, 5, 10]]
Output: [2, 10, 20]
We can integrate an if conditional inside a list comprehension:
[i*2 for i in [1, -2, 10] if i>0]
Output: [2, 20]
This is an example of list comprehension with an if and else condition:
[i*2 if i>0 else 0 for i in [1, -2, 10]]
Output: [2, 0, 20]
Functions can have more than one parameter. The function that we define below has a, b, and c as parameters:
def volume(a, b, c):
return a * b * c
Functions can have default parameters (e.g. the coefficient parameter below):
def converter(feet, coefficient = 3.2808):
meters = feet / coefficient
return meters
print(converter(10))
Output: 3.0480370641306997
Arguments can be passed as non-keyword (positional) arguments (e.g. a) or keyword arguments (e.g. b=2 and c=10):
def volume(a, b, c):
return a * b * c
print(volume(1, b=2, c=10))
An *args parameter allows the function to be called with an arbitrary number of non-keyword arguments:
def find_max(*args):
return max(args)
print(find_max(3, 99, 1001, 2, 8))
Output: 1001
An **kwargs parameter allows the function to be called with an arbitrary number of keyword arguments:
def find_winner(**kwargs):
return max(kwargs)
print(find_winner(Andy = 17, Marry = 19, Sim = 45, Kae = 34))
Output: Sim
You can powerfully use Python to process text files. You can read the content of a text file, and write new content to a file using Python.
Here’s how to read the content of a text file. Make sure you have a file.txt in your working directory with some text inside:
with open("file.txt") as file:
content = file.read()
This is how you can create a new file with Python and write some text inside the file:
with open("file.txt", "w") as file:
content = file.write("Sample text")
This is how you can append text to an existing file without overwriting the file:
with open("file.txt", "a") as file:
content = file.write("More sample text")
You can open a file for both reading and appending using:
with open("file.txt", "a+") as file:
content = file.write("Even more sample text")
file.seek(0)
content = file.read()
Built-in objects are all objects that are written by the Python developer team inside the Python interpreter.
Built-in modules contain built-in objects. To use those objects, the module needs to be imported first. E.g.:
import time
time.sleep(5)
A list of all built-in modules can be printed out with:
import sys
sys.builtin_module_name
Standard libraries is a jargon that includes both built-in modules and also modules written in Python.
Standard libraries written in Python reside in the Python installation directory as .py files. You can find their directory path with sys.prefix.
Packages are a collection of .py modules.
Third-party libraries are packages or modules written by third-party persons (not the Python core development team).
Third-party libraries can be installed from the terminal/command line:
Windows:
pip install pandas
Mac and Linux:
pip3 install pandas
This is the end of this tutorial. I really hope that you liked its short structure that I created with the intent to help you memorize the basic concepts and commands in Python.
Remember to practice, practice, practice!
If you want to keep on learning, we recommend you taking the 50-hour complete Python Course: Python Mega Course: Learn Python in 60 Days with 20 Apps
So, have fun learning Python, and talk to you soon!
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.