Home/Blog/Learn to Code/How to learn Python in 5 easy steps (for beginners)
Home/Blog/Learn to Code/How to learn Python in 5 easy steps (for beginners)

How to learn Python in 5 easy steps (for beginners)

Educative
Jul 11, 2019
10 min read

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Python is one of the most popular languages for its diverse set of applications; it can be used in web development, machine learning, data analysis, and more. If you’re just getting started in your software engineering career, then learning Python is a great place to start.

It can be overwhelming to get your start in a new language. This article will show you the steps to get you writing your own Python programs quickly.


Here’s what will be covered today:

Learn to code today.#


Step 1: Data types and variables#

When first starting out with Python, you’ll need a strong grasp on the different data types available to you and how to assign variables, which allow you to store data that can then be used later on throughout your code.

Unlike many other languages, Python does not place a strong emphasis on defining the data type of an object, which makes coding much simpler.

Python provides three main data types:

  • Numbers
  • Strings
  • Booleans

Numbers#

There are three main types of numbers:

Integers Floating point numbers Complex numbers

Integers

Integers are comprised of all whole numbers. Each integer has memory associated with it, so for example 0 will take up 24 bytes and 1 will take up 28 bytes.

Floating point numbers

Refer to positive and negative decimal numbers such as 3.1, 5.0, -3.24543.

Complex numbers

Complex numbers require two values; the first is a real part of the complex number and the second value will be imaginary and is represented with a j.

The syntax for declaring complex numbers is: complex (real, imaginary). Complex numbers usually takes up around 32 bytes of memory.


Strings#

A string is a collection of characters (strings can also be empty) closed within single or double quotation marks. We’ve all seen the classic Hello World example, well that’s a string. Notice how that example uses a single quotation mark, but if you wanted to say “Hello world it’s me!” you would need to use double quotation marks because there is an apostrophe in the word “it’s”. If you were to try with single quotes you wouldn’t get your desired string.

Every string created has an index associated with it. Take for example the string “Hello” below:

widget

This makes it easy to find the length of a string as well as access characters within it.

To find the length of a string you can simply use the len keyword which you can see here:

random_string = "I am Batman"
print (len(random_string))

The length of the string, “I am Batman” is 11 characters

To access a character you can use the [] and append them to the string.


Boolean#

The Boolean (also known as bool) data type allows you to choose between two values: true and false. A Boolean is used to determine whether the logic of an expression or a comparison is correct. It plays a huge role in data comparisons.


Variables#

A variable is simply a name to which a value can be assigned to give better clarity and management to your code, so if someone was to read your code they would know what’s going on and what each variable means.

The simplest way to assign a value to a variable is through the = operator.

widget

A big advantage of variables is that they allow you to store data so that you can use it later to perform operations in your code. And if a variable ever needs to be changed later on throughout your code you can do that due to their mutable nature.

There are a few rules when it comes to naming your variables so here are a few pro-tips:

  • The name can start with an upper or lower case alphabet.
  • A number can appear in the name, but not at the beginning.
  • The _ character can appear anywhere in the name.
  • Spaces are not allowed. Instead, we must use snake_case to make variable names readable.
  • The name of the variable should be something meaningful that describes the value it holds, instead of being random characters.

Step 2: Conditional statements#

A conditional statement is a Boolean expression that, if True, executes a piece of code. This is a great way to give your program some branching logic that controls the flow of code.

Three types of conditional statements are:

  • If
  • If-else
  • If-elif-else

If statement#

If statements are the simplest conditional statement, but they act as the foundation of conditional programming in Python. If statements are used when you want to achieve a desired result and if that result is not met, then terminate the program. If statements can be read like this:

If the condition holds True, execute the code. Otherwise, skip it and move on.

Here’s a good example of an if statement:

num = 5
if (num == 5):
print ("The number is equal to 5")
if (num > 5)
print ("The number is greater than 5")

Output = The number is equal to 5


If-else statement#

The if-else statement allows for even greater control over program. The statement says that “if this condition is true, execute the code, else execute other code snippet”. Now you have the ability to perform two different actions based on the condition’s value, whether it be true or false.

Here’s an example:

num = 60
if num <= 50:
print ("The number is less than or equal to 50")
else:
print ("The number is greater than 50")

Output = The number is greater than 50


If-elif-else statement#

In programming, it isn’t always a True or False scenario, and a problem can have multiple outcomes. This is where the if-elif-else statement shines. It is the most comprehensive conditional statement because it allows us to create multiple conditions easily. The elif stands for “else if”, indicating that if the previous condition fails, try this one.

Here’s an example:

light = "Red"
if light == "Green":
print ("Go")
elif light == "Yellow":
print ("Caution")
elif light == "Red":
print ("Stop")
else:
print ("Incorrect light signal")

Output = Stop

Learn to code today.#



Step 3: Functions#

Functions are reusable bits of code which help organize and maintain your code, and they even make it easier to debug and write code. Python has two main types of functions and they are:

  • Built-in functions
  • User-defined functions

The syntax for functions is as follows:

def function name (parameters):

Let’s break this syntax down:

Functions in Python are declared with the def keyword. Your function name can be anything you want, but it’s a best practice to name for what the bit of code does.

Lastly, you have the parameters of the function which are the inputs. They are a means of passing data to the function; these values/variables passed into the parameters are known as arguments. Note that parameters are optional.

Now let’s take a look at a function with elements in the body:

def minimum (first, second):
if (first < second):
print (first)
else:
print (second)
num1 = 10
num2 = 20
minimum (num1, num2)

Output = 10

The body of the function contains the set of operations that the function will perform. This is always indented to the right. If it’s not indented to the right the function will not execute and you’ll be left with an error. As mentioned before this function can be reused throughout your code.

When creating a function, you must define the number of parameters and their names. These names are only relevant to the function and won’t affect variable names elsewhere in the code. Parameters are enclosed in parentheses and separated by commas.


Step 4: Loops#

A loop is a control structure that is used to perform a set of instructions for a specific number of times — effectively solving the problem of having to write the same set of instructions over and over again.

One of the biggest applications of loops is traversing data structures, e.g. lists, tuples, sets, etc. In such a case, the loop iterates over the elements of the data structure while performing a set of operations each time.

Two main types of loops:

  • For loop
  • While loop

A for loop uses an iterator to traverse a sequence, e.g. a range of numbers, the elements of a list, etc. The iterator starts from the beginning of the sequence and goes through each index until the condition is met. In a for loop, you need to define three main things:

  1. The name of the iterator
  2. The sequence to be traversed
  3. The set of operations to perform

The loop always begins with the for keyword.

Here’s a good example:

float_list = [2.5, 16.42, 10.77, 8.3, 34.21]
count_greater = 0
for num in float_list:
if num > 10:
count_greater += 1
print (count_greater)

Output = 3

The while loop keeps iterating over a certain set of operations as long as a certain condition holds True. It operates using the following logic:

While this condition is true, keep the loop running.

Compared to for loops, you should be more careful when creating while loops. This is because a while loop has the potential to never end which can crash your program.

Useful keywords for while loops to avoid crashing a program:

  • Break
  • Continue
  • Pass

Loops are extremely useful when you need to traverse through a data structure or perform a certain operation a number of times.


Step 5: Data Structures#

A data structure is a way of storing and organizing data according to a certain format or structure.

Python’s four primary data structures are:

  • Lists
  • Tuples
  • Dictionaries
  • Sets

Lists#

The list is perhaps the most commonly used data structure in Python. It allows you to store elements of different data types in one container. Lists are ordered, like strings, where the elements inside are stored linearly at a specific index which makes them easy to traverse and access.

As you can see in the example below, the contents of a list are enclosed by square brackets, [].

jon_snow = ["Jon Snow", "Winterfell, 30]
print (jon_snow) # prints entire list
print (jon_snow[0]) # prints the first letter in the list
print (len(jon_snow)) # prints the length of the list

Tuples#

A tuple is very similar to a list (i.e. linear, ordered), except for the fact that its contents cannot be changed because of its immutable state. However, tuples can contain mutable elements like a list which can be altered.

Here we can see the contents of a tuple are enclosed in parentheses, (), as opposed to square brackets.

car = ("Ford", "Raptor", 2019, "Red")
print (car)
print (len(car))
print (car[1])
print (car[2:])

Dictionaries#

A dictionary stores key-value pairs, where each unique key is an index which holds the value associated with it. Dictionaries are unordered because the entries are not stored in a linear structure.

In Python, you must put the dictionary’s content inside curly brackets, {}:

empty_dict = {}
print (empty_dict)
phone_book = {"Batman": 468426,
"Cersei": 237734,
"Ghostbusters": 44678}
print (phone_book)

Sets#

A set is an unordered collection of data items. Sets are particularly useful when you simply need to keep track of the existence of items. It doesn’t allow duplicates, which means that you can convert another data structure to a set to remove any duplicates. It’s good to keep in mind though that you can only convert immutable data structures to sets, like a tuple, but lists or dictionaries won’t work.

Sets, like dictionaries, make use of curly braces to store the values.

random_set = {"Educative", 1408, 3.142, (True, False)}
print (random_set)

Each data structure has its own benefits and tradeoffs. For example, a list keeps things ordered, so if an order is important to you, then a list will be the data structure of choice. If you need to associate values with keys, so you can look them up efficiently (by key) later on, then a dictionary will be the most useful. It really depends on your use case and what you’re trying to solve.


What to learn next#

Python is a robust language, and the applications for it are endless. What’s been covered here is a light intro to the basics of programming in Python.

If you want to continue your journey, it’s recommended that you check out this Python skill path, Zero to Hero in Python, which will cover everything mentioned here in greater detail, complete with code playgrounds and quizzes to test your understanding.


Happy learning!


  

Free Resources