Learn Python: 10 steps for beginners

Erik Mannsverk
Analytics Vidhya
Published in
9 min readDec 23, 2020

Python is a programming language used in a wide variety of business applications. Well-known real-world companies like Youtube, Instagram, and Google use Python (and other languages) for the back-end (server-side) of their applications. The language is easy to learn since most of the code is written with understandable English words. This python guide includes exercises and tutorials, and tasks for bigger projects.

I would recommend you follow this table of content when learning Python.

Table of content

My most important tip — which is too good to be on this list — is to adapt everything you learn in your own projects. I have included a collection of tasks you can follow along with, but you should also make your own projects on each subject.

1. Get Started — Installation

To get started, I would recommend using Atom as your text editor, and the terminal as your output device. While you need to download Atom (use the link below), The Terminal is a built-in device on all Operating Systems (Mac OS, Windows, Linux, etc.).

The main point behind the terminal in these examples is to navigate the file system and run programs in it. In this case, my python-file (test.py) is located in the /documents/Python folder. The terminal features a lot of commands, but the two most important are the cd (change directory) and the ls (list files) commands.

Eriks-MacBook-Pro:~ erikmannsverk$ cd documents
Eriks-MacBook-Pro:documents erikmannsverk$ cd Python
Eriks-MacBook-Pro:Python erikmannsverk$ ls
test.py
Eriks-MacBook-Pro:Python erikmannsverk$ python3 test.py
Hello, World!

2. Print

The first lesson in Python would be to print strings and integers to the terminal. This is just to get comfortable with the mechanics of the text editor and the terminal.

print('Hello, World!')TERMINAL:
# Hello, World!
A simple understanding of the teamwork between Atom and the terminal

Try some of the tasks included!

3. Programming with Numbers and Strings

To store values in Python, you use variables. A variable is similar to a parking space in a parking garage where each parking space has an identifier and it can hold a vehicle.

P02 = 'Mercedes'

In another way, you can use variables to store soda cans and the volume per can, which you can multiply to calculate the volume of the soda altogether.

cansPerPack = 6
cansVolum = 0.33
sodaInCans = cansPerRack * cansVolum
print(sodaInCans)
TERMINAL:
#1.98

3.1 User Input

To get some kind of User Interface in the terminal, the easiest way is to use the input-function. This is a built-in function, which there are a lot of in Python (check them out here). To reuse the input later, store it input in a variable.

yourName = input('What is your name? ')
print(yourName)
TERMINAL:
#What is your name? Erik
#Erik

4. Decisions

One of the most important features in Python is the if/else statement. The statement is used to validate if a condition is True or False, and will only run if the condition is true.

total = 10if total > 5:
print('Yay!')
else:
print('Bu ..)
TERMINAL:
#Yay!
A brief understanding of how an if statement works

5. Functions

A function is a sequence of code that easily can be reused. To execute the code in a function you have to call it. In most cases, a function takes a parameter with data from the user and returns data based on the data passed in.

When a function doesn't take any parameters, it’s called a procedure, like the one shown underneath.

def print_hello_world():
print('Hello, World!')
print_hello_world()
print_hello_world()
print_hello_world()
TERMINAL:
#Hello, World!
#Hello, World!
#Hello, World!

Most of the time a function takes a parameter and returns some kind of data. To keep the data returned from a function, it’s normal to store it in a variable.

def calculate_squared(my_number):
total = my_number * my_number
return total
sqrt1 = calculate_squared(3)
sqrt2 = calculate_squared(5)
print(sqrt1)
print(sqrt2)
TERMINAL:
#9
#25

6. Lists

A list is a collection of data types stored in a variable. The list structure gives you the possibility to collect large numbers of value and other things, in a specific order. That way you can collect the data you want from a specific place in the list.

fruits = ['Banana', 'Apple', 'Pear']
print(fruits[1])
TERMINAL:
# Apple

There are several methods useful when working with lists. One of the most important ones is the append-method, which adds an element to the end of the list.

fruits = ['Banana', 'Apple', 'Pear']
frutis.append('Orange')
print(fruits)
TERMINAL:
#['Banana', 'Apple', 'Pear', 'Orange']

Lists allow you to have duplicated values, which may be a disadvantage at times. Let's say you're adding a product to your shopping list, but you don't want two of the same values in your list. Then you would have to do something like this:

shoppingList = ['Banana', 'Apple', 'Pear']newItem = input("Add new item to shoppinglist: ")
if newItem not in shoppingList:
shoppingList.append(newItem)

To avoid this disadvantage, you could use sets or dictionaries.

7. Sets and Dictionaries

Similar to lists — sets and dictionaries hold a collection of data. The main difference is that elements in sets and dictionaries don't have a specific order and that it cant hold duplicated values. Since you can’t access the data via the index, dictionaries use a key to access the value (data).

# Set
names = {'John', 'Lisa', 'Greg', 'ThisIsAKey'}
# Dictionary
phonebook = {
'John' : '21230922',
'Lisa' : '25000695',
'ThisIsAKey':'ThisIsAValue
}

To access the value in a dictionary, you simply use the key.

print("John's phonenumber is", phonebook['John'])TERMINAL:
#John's phonenumber is 21230922

8. Loops

In a loop, a part of your program is repeated over and over. This gives your code the ability to iterate over a sequence (a list (point 6.), a dictionary(point 7.), a set(point 7.), or a string(point 3.)).

8.1 For-loops

For-loops usually iterates over a list or a range. In this example, the loop iterates over a range, which starts at 0, unless something else is passed in as a parameter.

for i in range(4):
print(i)
TERMINAL:
#0
#1
#2
#3

For-loops work well with lists, a collection of data stored in a single variable.

fruits = ['Banana', 'Apple', 'Pear']for fruit in fruits:
print(fruit)
TERMINAL:
#Banana
#Apple
#Pear

You could also combine these with an if-statement.

fruits = ['Banana', 'Apple', 'Pear']for fruit in fruits:
if fruit == 'Apple':
print(fruit)
TERMINAL:
#Apple

Try out these tasks!

8.2 While-loops

While-loops work similarly to for-loops but tend to look more complicated. In a lot of cases, the for loop is the best to use, but in some cases, the while-loop is the one to go for.

Here is an example of the counting-code I made with a for-loop, which is a great example of when you should use a for-loop instead of a while-loop.

i = 0
while i < 4:
print(i)
i += 1
TERMINAL:
#0
#1
#2
#3

You should use while-loops instead of for-loops when asking for user input. The lower() function makes all the characters in a string lowercase, which makes it easier to check the user-input in an if-statement.

inputAccepted = Truewhile inputAccepted:
userInput = input('Do you want to exit the while loop? ').lower()
if userInput == 'yes':
print('You are now exiting the loop!')
inputAccepted = False
TERMINAL:
#Do you want to exit the while loop? no
#Do you want to exit the while loop? no
#Do you want to exit the while loop? yes
#You are now exiting the loop!

9. Files

Assume we have a cheesy_poem.txt file on our computer that goes like this:

Pizza is all that I believe in
Pizza is me
I am Pizza
And if I take you words
Then I take you power
And I get your money
And with that money I buy pizza

To read the lines out to the terminal, you could do use a for loop to access every line of the text-file. The ‘r’ is an attribute of a file object that tells you which mode the file was opened in, and means read.

file = open('cheesy_poem.txt', 'r')
for line in file:
bites = line.strip()
print(bites)
file.close()
TERMINAL:
# Pizza is all that I believe in
# Pizza is me
# I am Pizza
# And if I take you words
# Then I take you power
# And I get your money
# And with that money I buy pizza

9.1 Files combined with lists and loops

In this example, imagine a person.txt containing information about three person's personal information. The information is separated with spaces.

John 07911123456 England
Lisa 12300123 Australia
Sam (133)943-2132 UnitedStates

Just like in the first example, you have to open the file and iterate over the lines with a for-loop. The difference is that we use the split command to slice up the lines at every space, into a list called lines. This is an example of what the bites-list look like [‘John’, ‘07911123456’, ‘England’]. Then we make an f-string, that we print to the terminal. The ‘/n’ just means line shift.

file = open('person.txt', 'r')
for line in file:
bites = line.strip().split()
fString = f"Name: {bites[0]}\nPhonenumber: {bites[1]}\nCountry:
{bites[2]}\n"
print(fString)
file.close()
TERMINAL:
# Name: John
# Phonenumber: 07911123456
# Country: England
#
# Name: Lisa
# Phonenumber: 12300123
# Country: Australia
#
# Name: Sam
# Phonenumber: (133)943-2132
# Country: UnitedStates

10. Objects and Classes — Object Orientated Programming

When you have a good understanding of variables, decisions, functions, data structures (lists, sets, and dictionaries), loops, and files, it’s time to move on to a more advanced topic in programming. The term Object Orientated Programming means that the coding model is based on the concept of ‘objects’. In this list, this concept is just going to be a short introduction to the topic. To generalize, a class is something representing a thing with similar behaviors.

class Human:    #Constructor
def __init__(self, name, age):
self._name = name
self._age = age
#Method
def getInfo(self):
return f"Name: {self._name}\nAge: {self._age}\n"

Then you can make objects of the class, by storing them in a variable. Since the class only has one method, there is only one method to call. You can store the returned data from a class in another variable, which you can print out.

erik = Human('Erik', 20)
john = Human('John', 49)
erik_info = erik.getInfo()
john_info = john.getInfo()
print(erik_info)
print(john_info)
TERMINAL:
# Name: Erik
# Age: 19
#
# Name: John
# Age: 49
#

10.1 Realistic Example

A more realistic example, that made me understand classes and objects really well, was an example based on a coffee machine. When you make an object of the class, it starts with 0 ml of water. Then you can fill it up with a chosen amount, and either make an espresso or a lungo.

class CoffeeMachine:    #Constructor
def __init__(self):
self._water = 0
def makeEspresso(self):
if self._water > 40:
self._water -= 40
print("Here you go, an espresso for you!")
else:
print("There is not enough water in the coffeemachine.")
def makeLungo(self):
if self._water > 110:
self._water -= 110
print("Here you go, a lungo for you!")
else:
print("There is not enough water in the coffeemachine.")
def fillWater(self, ml):
if self._water + ml < 1000:
self._water += ml
else:
print("There is only room for 1000 ml of water.")
def getWater(self):
return f"Amount of water: {self._water}"

This is an example of a coffee machine object.

cMachine_1 = CoffeeMachine()print(cMachine_1.getWater())
# Amount of water: 0
cMachine_1.fillWater(70)print(cMachine_1.getWater())
# Amount of water: 70
cMachine_1.makeEspresso()
# Here you go, an espresso for you!
cMachine_1.makeEspresso()
# There is not enough water in the coffeemachine.
Terminal + Atom example

Try it yourself!

Now that you have finished learning these 10 steps, you know the fundamentals of the language and are ready to make your own big projects. I would recommend you to check out this link, which includes 42 ideas for python projects. Thank you for following along!

--

--