Python Full Road Map and Resources

Python is the most popular programming language among data scientists, and people new to the world of Programming. But a lot of them get stuck. Why? “There are a lot of free resources to learn from right?”. Yes, there are a “lot” of resources out there and that’s the problem. So you want to find the best one among them right? Well, I can’t share with you the best resources definitely cause everyone has different tastes and new resources just keep popping up like literally every-single-day.

So for that I’ve round up some of the best (not the best) resources out there that will help you, master Python. I’ll also leave alternatives for those who don’t like some of those article or videos. Also I’ll share some of the best books you can use as a reference or guide for learning Python.

Like other roadmaps and plans i’ve shared this one will also be split into a journey of 30 days, so you can learn Python just by spending 1.5 hours everyday and become a Good Python developer.

Other Road maps:
For web development: https://codingdeck.com/blog/web-development-plan/
For Machine Learning: https://codingdeck.com/blog/machine-learning-plan-and-resources/

Note: Do not rush and try to learn all of the things at once. Also don’t copy-paste code or just code along. Instead try to understand every bit of details and this roadmap will be focused on understanding all the stuff.

Note: Don’t worry if you forget stuff like how a function was written or how classes and wrote. If you understand the basic concepts that are good. It’s 100 times easier for you to forget the syntax than to forget the concepts. So make your understanding stronger and the code will come. Now keep calm and code on. ๐Ÿ™‚

Note: Becoming a good coder is always 70% practice and 30% learning. So practice, be curious and experiment to see what the code does.

Now enough talking, let’s get started, shall we?

Table of Contents

The Preparation

Day 1 : Setting up your Python Environment & Saying Hello to the world!

Before we start diving into the topics, Let’s start by watching a quick video about the story of Python by the creator of Python himself – Guido Van Rossum. This will help you understand a gist of why Python was founded in spite of the many already existing programming languages like C, C++, Java, etc.

Now, now, I hope you’re pumped up just like I am, after watching the God of Python ๐Ÿ˜‰ It’s time to getting into action by setting up your development environment and so you can get comfortable with it.

For the Linux geeks out there, here’s a video:

Mac Folks, we haven’t forgotten you ๐Ÿ™‚

Different ways to run Python Code –

Do not worry about the code or the version of Python in the below videos. These are purely for you to see the ways you can run your Python code.

1 – Using the inbuilt Terminal (Mac/Linux) and Command Prompt (Windows)

2 – Running the code via Code Runner in VS Code

3 – Using the Microsoft Python extension in VS Code

The next step is to say Hello to the beautiful world!

Take out your VS Code Editor. Open a new file that says “HelloWorld.py”. Now in your file, type in the following code only .

print("Hello beautiful world!")

Now upon running this code, you should see an output that says “Hello beautiful world!”. Magical, right?.

For the rest of the day today, play around with the print function. Experiment with it, try different things like swapping single quotes with double-quotes. See what error pops up when you don’t include the quotes at all. Play around with it!

Day 2 : Variables, Data Types and Operators

Variables

You can also check out our ever favorite resources – W3Schools.

https://www.w3schools.com/python/python_variables.asp. It offers you a lot of space to try out a lot of stuff on the browser itself. So after each topic, we’ll place the link to practice resources as well so you can get your hands dirty ๐Ÿ˜‰

Data Types

W3 Link – https://www.w3schools.com/python/python_datatypes.asp

Operators

W3 Link – https://www.w3schools.com/python/python_operators.asp

Here’s a video on Input / Output as well:

Day 3 – Strings, Integers & Floats in Detail

Hellllooooooo!
Day 3 is about getting a bit deeper into Textual and Numerical Data in details and their built-in methods that can help you solve a variety of problems.

Strings

Practice strings on W3Schools – https://www.w3schools.com/python/python_strings.asp

Numerical Data

Practice playing around with Numerical data and their methods on W3Schools – https://www.w3schools.com/python/python_numbers.asp

Day 4 – Time to test what you already know

Try solve problems around strings and numerals. If you find the online editor tough on HackerRank, you can solve these problems locally in your IDE.

Stringshttps://www.hackerrank.com/domains/algorithms?filters%5Bsubdomains%5D%5B%5D=strings&filters%5Bdifficulty%5D%5B%5D=easy

Operatorshttps://www.hackerrank.com/challenges/30-operators/problem

Day 5 – Lists (Arrays)

Good job getting this far! Appreciate it. Now it’s time to dive into the data structures.

What is a Data structure?

In computer science, a data structure is a format to organize, manage, and store data thus enabling efficient access and modification. Thus, a data structure is a collection of data values that define the relationships among them, and the various functions or operations that can be applied to the data.

In simpler terms, a data structure is a container where you can store your data, organize your data, manipulate and access your data.

Why do you need a Data Structure?

As your programs start getting bigger, the amount of data that you use in your Program also increases. But the only way we know to hold data as of now is by using a variable to store data. But what would you do if you had to store 10 pieces of data? To hold those 10 pieces of data, you’d have to declare 10 variables. Considering its only 10 variables, it’s still okay. But what if you had to hold 50 pieces of data?. How about 100 pieces of data? How about 1000?

Honestly, you’d not be able to declare those many variables and even if you could, it just doesn’t seem like a super-efficient way to do it, considering that we have a Computer.

That’s why we have Data Structures because they act like containers where your data can be organized efficiently, so you can access and modify them efficiently and, a List or an Array is one such important, widely used Data Structure in the Programming World.

What is a List?

A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ].

In a list, you can modify the values that are stored in it, thus making it “mutable”.

Lists are great to use when you want to work with many related values. They enable you to keep data together that belongs together, condense your code, and perform the same methods and operations on multiple values at once.

To get started, letโ€™s create a list that contains items of the string data type:

sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'anemone']

When we print out the list, the output looks exactly like the list we created:

print(sea_creatures)
Output['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'anemone']

Note: Do not panic if a different Code Editor is used in the video because whatever is used in these videos, can definitely be replicated in the code editor you have. I’ll be including multiple resources for Lists so you can get a variety of inputs on the same topic, thus strengthening your foundation.

W3 Schools Link – https://www.w3schools.com/python/python_lists.asp

Day 6 – Tuples

What is a Tuple?

A tuple is a data structure that is an immutable, or unchangeable, ordered sequence of elements. Because tuples are immutable, their values cannot be modified.

Tuples are very similar to Lists, but they have a fundamental difference between them. Which is the fact that, you cannot modify data that is stored inside a Tuple but you can modify the data stored in a List.

A tuple in Python looks like this:

coral = ('blue coral', 'staghorn coral', 'pillar coral', 'elkhorn coral')

Tuples are used for grouping data. Each element or value that is inside of a tuple is called an item.

Tuples have values between parentheses ( ) separated by commas ,. Empty tuples will appear as coral = (), but tuples with even one value must use a comma as in coral = ('blue coral',).

If we print() the tuple above, weโ€™ll receive the following output, with the tuple still typed by parentheses:

print(coral)
Output('blue coral', 'staghorn coral', 'pillar coral', 'elkhorn coral')

W3 Schools Link – https://www.w3schools.com/python/python_tuples.asp

Day 7 – Dictionaries (Hash-Maps)

The dictionary is Pythonโ€™s built-in mapping type. Dictionaries map keys to values and these key-value pairs provide a useful way to store data in Python.

To give you a better picture of a Dictionary, think of a Dictionary. For instance, if you wanted to know the meaning of a word in a dictionary, you would search for the word and once you find the word, you would look for the meaning of that word. So here, the word acts as the key, the meaning acts as the value. You can also relate to a Phone Book in the exact same way.

Why do we need a Dictionary when we already have Lists and Tuples?

Let’s assume that you are coding a program where you store details about students’ marks. Would it be an efficient idea to store marks in an array? Even if you did, how would you connect the Students with their marks? You’d still have to “map” them together, right?

That’s where Dictionaries (Hash-Maps) come into play as an effective and efficient structure to use. Using a Dictionary, you could easily store Students’ names as keys and their marks as values and thus for a user to access them, all they’d have to do is ask for the marks using the Student’s names.

Dictionaries are typically used to hold data that are related, such as the information contained in an ID or a user profile and dictionaries are constructed with curly braces on either side { }.

A dictionary looks like this:

sammy = {'username': 'sammy-shark', 'online': True, 'followers': 987}

In addition to the curly braces, there are also colons (:) throughout the dictionary.

The words to the left of the colons are the keys and Keys can be made up of any immutable data type. The keys in the dictionary above are:

  • 'username'
  • 'online'
  • 'followers'

Each of the keys in the above example are string values.

The words to the right of the colons are the values. Values can be comprised of any data type. The values in the dictionary above are:

  • 'sammy-shark'
  • True
  • 987

W3 Schools Link – https://www.w3schools.com/python/python_dictionaries.asp

Day 8 – Sets

A Set as you can imagine is based on the exact Set theory that we may have encountered in Mathematics.

A set is created by placing all the items (elements) inside curly braces {}, separated by a comma, or by using the built-in set() function.

It can have any number of items and they can be of different types (integer, float, tuple, string, etc.). But a set cannot have mutable elements like lists, sets, or dictionaries as its elements and a set also cannot have duplicate elements thus can be effectively used in problems where you may want to find out if a duplicate element exists.

# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

Output

{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}

W3 Schools Link – https://www.w3schools.com/python/python_sets.asp

Day 9 – Conditional Statements (If.. Else)

Fantastic job making it through the 30 days of Python until this. Now, it’s time for something really fun and important.
The decision making portion of Programming.

What is a Conditional Statement?

If you could pause for a minute and think about it, you would realize that most of our day to day activities can often be broken down into actions with two or more consequences. If this, then do that. Otherwise, do something different.

The simplest form of Decision Making is choosing between “this” or “that”, “Yes” or “No”(In Computer language, it’s either 1 or 0)

For instance, if it’s time for you to wake up, you wake up. Otherwise, you continue to sleep. Another example is that, if you’re hungry, you eat. Otherwise, you don’t eat (or probably wait until you’re hungry so you can eat ๐Ÿ™‚ ). Computers explicitly operate that way too to make a decision and to perform specific actions when the specified condition is met.

So a conditional statement helps you branch the flow of your program by executing a certain action if a particular condition is met or perform an alternate action if the condition is not met.

If it weren’t for this decision-making portion, then computers are a little dumb, aren’t they?. Therefore, Conditional Statements / Decision making is an extremely important Programming concept no matter what language you pick. Because decision making defines and drives all logical paths a program can take.

So as you may have already guessed, Python’s If Else loop works on the exact same logic. If a condition is met, then its corresponding action is executed. Else(Otherwise), an alternate action is executed.

if condition1:
    then execute action1
elif condition2:
    then execute action2
else:
    then execute action3
#Program to check if a given number is even or odd.

x = 5
if x%2 == 0:
    print("Even number!")
else:
    print("Odd number!")

Here are a few tutorial videos that will help you further solidify the idea of If Loops.

W3 Schools Link – https://www.w3schools.com/python/python_conditions.asp

Day 10 – Control Flow – While Loops

Now, what is the first thing that pops into your mind when you think of a loop? The infinity symbol? Or in simpler words, a circle? (Fruit Loops?).. Something going on and on and on with no end?.

What is a Loop?

The first thing we all visualize about when we hear the word “Loop” is something that keeps running endlessly. You’re almost right!

In the computer world, a loop is a control flow mechanism. Something that allows you to handle repetitive tasks in your code, thus saving a lot of your time and repetitive statements in your code, by setting boundary conditions.

Boundary Conditions are very important because if proper boundary conditions are not set, your code could be running in an infinite loop and you’d have to manually stop the code.

What is a While Loop?

A while loop is an important Control Flow Statement in Programming. In simple English terms, the idea of a while Loop is expressed as “Until the condition is met, keep repeating”. So if the condition is not met, it just keeps going on forever.

while hungry:
    eat
#so until you're hungry, you eat. You stop the moment you're not hungry

May be a lame example, but you get the idea, right?.
Here’s a code snippet to better demonstrate the idea.

#we initialize a variable that will serve as our start boundary
i = 0
#we then code the while loop to keep printing "Hello world"! until i equals 10
while i != 10: #here we define the end boundary
    print("Hello world!")
    i += 1 #Here we increment i by 1 with every loop, so that when i equals 10, the loop stops.

Cool, right? Now let’s expand further on this idea by watching some interesting tutorials.

W3 Schools link – https://www.w3schools.com/python/python_while_loops.asp

Day 11 – For Loops

A for loop is pretty similar to a while loop. Except that it has a couple of extra checks so that an infinite loop is avoided.

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. An iterable object is just something that you can loop over and the process of iterating over an iterable object is called traversal, because you traverse through the sequence.

for x in range(1,10):
    print(x)
Output:
1
2
3
4
5
6
7
8
9

W3 Schools Link – https://www.w3schools.com/python/python_for_loops.asp

Day 12 – Boolean Conditions

Boolean refers to nothing but two output values – True or False. It refers to the fundamental idea of Programming that it’s either a 1 or a 0. It’s either True or False. It’s more useful in programming than you can ever imagine. Here, check it out.

W3 Schools Link – https://www.w3schools.com/python/python_booleans.asp

Day 13 – Type Casting / Conversion

When you start solving coding problems, there will be times where you may feel that it would have been better if a particular string value say “12” was actually an integer and not a string. Well, Python offers an extremely easy method to do that.
Ex: Let’s say you have the value “12” assigned to a variable.

a = "12"

All it would take, to convert it to an int, is:

b = int(a)

To check the type of variable:

print(type(b))

Pretty simple and powerful, right?. Using this method, you can change the data type of any variable in your program from the current data type to a different data type. For example, you can convert a string to a list by simply using list () and as you can imagine, the possibilities are endless.

Now here are some resources that’ll help you absorb the idea better.

W3 Schools Link – https://www.w3schools.com/python/python_casting.asp

Day 14 – Functions and Arguments

Welcome to functions in Python.

What is a Function?

In simple terms, Functions are reusable pieces of code that you can call multiple times in your code without having to repeat yourself because the golden rule of a good code is – DRY (Don’t Repeat Yourself).

When a Function is used, every function must return a value as its output value. So, a return value is pretty much like a print statement within the function but a return keyword cannot be used outside a function.

What is an Argument in a Function?

Arguments are simply parameters that you can pass to a function and parameters, when broken down are simply pieces of information.

A function’s syntax is as follows:

def myfunction():
    return "Hello, World!"

print(myfunction())

Example Code –

def addition(number1, number2):
    return number1 + number2

print(addition(23 , 45))
print(addition(653, 7348))
Output:
68
8001

In the above code, number 1 and number 2 are what we call arguments. They inform the function of what will be passed by the main program to them so they can use that to process an output.

To help you understand better, here are some fantastic resources:

W3 Schools Link – https://www.w3schools.com/python/python_functions.asp

Day 15 – Problem Solving time

Time to put all that we have learnt, into solving some problems.

#1 : https://www.hackerrank.com/challenges/python-loops/problem

#2 : https://www.codewars.com/kata/5526fc09a1bbd946250002dc

#3 : https://www.codewars.com/kata/515e188a311df01cba000003

#4 : https://www.hackerrank.com/challenges/30-arrays/problem

#5 : Print out n Fibonacci numbers

A Fibonacci number series looks like this –
0,1,1,2,3,5,8,13,21…n
Each number is the sum of the previous two digits. Print out the first 10 or first 20 Fibonacci numbers.

#6: https://www.hackerrank.com/challenges/30-conditional-statements/problem

#7: https://www.codewars.com/kata/5412509bd436bd33920011bc

#8: https://www.codewars.com/kata/5679aa472b8f57fb8c000047

#9 https://www.codewars.com/kata/5287e858c6b5a9678200083c

#10: https://www.codewars.com/kata/587731fda577b3d1b0001196

Bonus Problem: https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c

I know that this problem is significantly tougher than the previous problems. But what kills us makes us stronger, right? ๐Ÿ™‚ Try it out, do your best!

Day 16 – File Handling

Welcome to Day 16 of Python Programming and I hope you had fun with all the previous problems until now. Today, we are going to learn how to handle Files in Python.

What does File Handling mean?

In short, File Handling refers to the different ways you can handle your files. Out of the many operations, that you can perform on files, read, and write are the most important operations you will be performing. Let’s dive a bit into the different access modes that allow you to perform File operations.

Access Modes – What are access modes?

Access modes define and govern the type of operations that you can perform in an open file. It refers to how the file will be used once its opened.

Available Access Modes in Python

  1. Read Only (โ€˜rโ€™)
  2. Read and Write (โ€˜r+โ€™)
  3. Write Only (โ€˜wโ€™)
  4. Write and Read (โ€˜w+โ€™)
  5. Append Only (โ€˜aโ€™)
  6. Append and Read (โ€˜a+โ€™)

Example Code

f = open("helloworld.txt","r+")
f.write("Hello world!")
f.close()

In short, the above code creates a text file named “helloworld.txt” if it is not already available and writes “Hello world!” in the text file and thereby closing the file after use. Interesting?

Here are some tutorials that will help you further grasp the concepts of File Handling.

W3 Schools Link – https://www.w3schools.com/python/python_file_handling.asp

Day 17 – Exception Handling

When it comes to programming, Exceptions are inevitable and what differentiates an average programmer and a good programmer is how well the programmer handles Exceptions beforehand.

What is an Exception?

An exception is an unexpected event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

For instance, if you’re coding a program that finds out whether the user input is an odd number or an even number, there are chances where a user may enter a string instead of an integer simply because the user may not know what the program does.

When the user enters a string wherein our program expects an integer, we encounter an exception that’s called “ValueError: invalid literal for int() with base 10: ‘str’ “

What do we do when Exceptions occur?

As I had mentioned, when it comes to Programs, Exceptions are bound to happen. But the good news is, Exceptions can be handled through what’s called “Exception Handling”.

Exception Handling in Python

In Python, Exceptions are handled by using “Try” and “Except” Blocks. The code specified in the try block is first executed as part of the normal flow & the possible Exceptions are specified under the “Except” Blocks. So, as soon as an Exception occurs, the code in the Except block is triggered.

Example Code:

A normal program to find out if the given input number is odd or even, is written as follows

num = int(input("Enter a number: \n"))
if num % 2 == 0:
    print(num,"is an even number!\n")
else:
    print(num,"is an odd number!\n")

In the above program, when the user is prompted for an input, if the user enters a string or maybe an alphanumeric character, this is the exception the program encounters.

ValueError: invalid literal for int() with base 10: 'str'

Why does this exception happen?

Because, the input is designed to take only integer as an input using int(input()) statement. Even if you hadn’t specified int(), you would still receive the error because you cannot divide a string by 2, can you? ๐Ÿ™‚

To manage this exception, the syntax is as follows:

Syntax –

try:
    num = int(input("Enter a number: \n"))
    if num % 2 == 0:
        print(num,"is an even number!\n")
    else:
        print(num,"is an odd number!\n")
except ValueError:
    print("Please enter a number\n")

Explanation

It simply means that keep trying to execute the code until you hit an exception and when you do, inform the user of how to overcome the exception by execute the code under “Except”.

So as per the above code, if the user enters a different data type as opposed to an integer, instead of an alarming exception, the user will receive a simple print statement that reminds the user to only input an integer ๐Ÿ™‚

To sum up the idea of Exception Handling, here are some tutorials that will get you up to speed with the concept and its implementation.

And here are the W3 Schools Resources – https://www.w3schools.com/python/python_try_except.asp

Day 18 – 21 – Object Oriented Programming

What does Object Oriented Programming mean?

Object-oriented programming (OOP) is an important programming paradigm based on the concept of “objects”, which can contain data, in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods or functions).

To understand OOP better, we must understand what a class means and therefore, what an object means.

What is a Class & an Object?

A class is a user-defined blueprint from which objects are created. To expand further on it, Classes simply provide a means of bundling data and functionality together.

An object is simply a collection of data (variables) and methods (functions) that act on those data, thus making the Class a blueprint.

Example 1 –

For instance, let’s consider that you want to track Pokemon based on their attributes like –

  • Name
  • Type
  • Strength
  • Weakness
  • Top Attack

Here, think of Pokemon as the class and all their attributes as its objects.

Example 2 –

For instance, if you consider dogs as a Class, then its attributes would be –

  • Name
  • Age
  • Breed
  • Color

Therefore, an object consists of :

  • The state is represented by attributes of an object and also reflects the properties of an object.
  • Behavior is represented by methods of an object and also reflects the response of an object with other objects.
  • Identity is what gives a unique name to an object and also enables the interaction between objects

Why are classes necessary?

Referring to our earlier example, letโ€™s say you wanted to track the number of dogs which may have different attributes like breed, age, color etc. If a list is used, the first element could be the dogโ€™s breed while the second element could represent its age. Letโ€™s suppose there are 100 different dogs, then how would you know which element is supposed to be which?

For instance, what if you wanted to add other properties to these dogs? Therefore, classes are used when the need for organization arises.

The self

Class methods must have an extra first parameter in method definition and we do not give a value for this parameter when we call the method, Python provides it. If we have a method that takes no arguments, then we still have to have one argument.

Generally, it is referred to as using the self keyword.

For instance, when we call a method of this object as myobject.method(arg1, arg2), this is automatically converted by Python into MyClass.method(myobject, arg1, arg2).

The Constructor – __init__

__init__ as the word means initiates the class for you. It simply constructs a class to begin with and therefore, init is called a Constructor.

Constructors are used to construct the objectโ€™s state and like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation.

A very simple Example –

# A Sample class with init method  
class Person:  
    
    # init method or constructor   
    def __init__(self, name):  
        self.name = name  
    
    # Sample Method   
    def say_hi(self):  
        print('Hello, my name is', self.name)  
    
p = Person('Shyam')  
p.say_hi()

Now that we know the whats of OOPs, let’s dive deeper into the concept with a few tutorials. Since it takes 3-4 days to completely wrap your head around OOPs as a concept and implement it, please take your time to understand and absorb the idea.

Note: Please break these videos down and watch them over a period of 3-4 days if required and hence, we have tried our best to include the best playlists and the most detailed tutorials which will help you soak the idea in.

W3 Schools Link – https://www.w3schools.com/python/python_classes.asp

Day 22 – Lambda Functions

In addition to the regular functions in Python, Lambda Functions are just anonymous functions that don’t require you to define the function formally to use it in your code. Lambda Functions can take any number of arguments but can have only one expression and Lambda functions can even be used with regular functions which makes it extremely useful.

Why and when are Lambda Functions useful?

Lambda functions are used when you want a nameless function for a short period of time that isn’t going to be reused anywhere else in your code.

Here are some examples –

x = lambda a,b,c : a + b + c
print(x(1,2,3))
Output:
6
y = lambda a : a%2 == 0
print(y(23454))
Output:
True

In other words, think of Lambda functions as disposable functions. More importantly, Lambda functions are not meant to replace regular Functions and are generally used as a complementary method in conjunction with Functions and expressions.

To sum up the concept and understanding of Lambda Function, here are some tutorials.

W3 Schools Link – https://www.w3schools.com/python/python_lambda.asp

Day 23 – 24 – Map, Filter and Reduce

Map

A Map function helps you map functions to items inside iterables and the map function is extremely flexible because it can take in any number of iterables (Quick Recap – An iterable is an object you can iterate over, like Lists, Tuples, Dictionaries, etc).

The map function follows the below syntax –

map(function, iterable)

Example –

def myFunc(a,b):
    return a+b

x = map(myFunc,("Coding","just"),(" is"," amazing"))
print(list(x))

Output –

['Coding is', 'just amazing']

Filter

A filter function is used when you want a filter an iterable based on a specific condition and return an iterable that’s filtered based on the condition you specified.

Similar to the map function, a filter function also uses the same syntax.

filter(function, iterable)

Example –

nums = [1,2,3,4,5,6,7,8,9,10]

def myFunc(x):
  if x % 2 == 0:
    return True
  else:
    return False

numbers = list(filter(myFunc, nums))

print(numbers)

Subsequently, the output returns a list of even numbers only.

[2, 4, 6, 8, 10]

Reduce

A reduce function is very similar to a Lambda Function in implementation and is used to apply a certain function to all elements in the iterable specified as an argument thus reducing the output to a single number instead of an iterable as a result.

In contrast to the other functions mentioned above, the reduce function requires you to import a module called “functools” and to import functools, you can simply use the “import functools” statement.

Similar to the map and filter function, the reduce function also uses the same syntax.

reduce (function, iterable)

Example –

import functools 
lis = [ 1 , 3, 5, 6, 2, ] 
  
# using reduce to compute sum of list 
print ("The sum of the list elements is : ",end="") 
print (functools.reduce(lambda a,b : a+b,lis)) 

Output –

The sum of the list elements is : 17

In conclusion, here are some tutorial videos to help you better understand the concept.

W3 Schools Link for Map – https://www.w3schools.com/python/ref_func_map.asp

W3 Schools Link for Filter – https://www.w3schools.com/python/ref_func_filter.asp

Day 25 – Comprehensions

In short, Comprehensions help in the construction of sequences from other sequences and can be effectively applied to Lists, Tuples, and Dictionaries.

For example, let’s consider a problem where we have two lists and we need to find the elements in list1 that also exist in list2. This is how list comprehension can help solve it.

lis1 = [1,2,3,4,5,6,7]
lis2 = [5,6,7,8,9,10,11]
lis3 = [x for x in lis1 if x in lis2]
print(lis3)

Output

[5,6,7]

In other words, comprehension can also be applied to a problem that can be solved using a simple iteration.

To conclude, here are some tutorial videos to further strengthen the need for and idea of Comprehension.

Day 26 – 27 – Regular Expressions

In Python, often, you may encounter multiple scenarios where you may see a pattern of strings and may want to search/match the pattern in order to manipulate it. Therefore, you may want to resort to Python’s Regular Expression module where a Regular Expression refers to a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern.

What’s the use of Regular Expressions?

For instance, let’s say you have a use case where you have a Bank Statement from which you’re supposed to extract the 10 digit account number wherein the account number is amidst a lot of other text but it still holds a unique pattern.

This is where Regular Expressions come into play because it helps you in identifying the pattern of account numbers as typically [0-9]{10} which means the pattern will only contain numbers from 0-9 and has 10 continuous occurrences.

Syntax

To use Regular Expressions, you will have to “import re” in your code where re stands for regular expressions and subsequently the re module offers a lot of methods like match, find etc.

Let’s look at a few tutorials to understand how to use regular expressions, in detail.

W3 Schools Link – https://www.w3schools.com/python/python_regex.asp

Day 28 – Python & External Packages

Python is a full-fledged programming language because it has a lot of built-in functions that allow us to perform almost everything. But, remember, Python is Open Source and what makes Open Source beautiful is Contribution. Subsequently, as the language kept on growing, several developers contributed to the language by improving the built-in features and also by creating external libraries/packages that the user could simply import and use in their own programs for their own needs.

How do External Packages help us?

External packages are just independent & separate code files that can be used in your program by importing them because there are definitely functions & actions that you would want to perform in your code and built-in functions may just not be enough to satisfy them.

How to import Packages and use them in code?

Firstly, you will have to install the package you want to use by typing the below syntax in your Terminal/command prompt.

pip install package_name

Where package_name is the name of the package you want to import. Upon executing this command for a package of your choice, if you received no errors, and received a “successfully installed” message, then you are good to go.

To use it in your code, simply import it in the first line of your code using the “import” keyword.

Example –

import package_name

How does the Package installer work?

When a developer creates a library/package for the world to use, he is typically required to upload it into one place which hosts and delivers all the packages for Python. This central repository is called PyPi (Stands for Python Package Installer – A web site that hosts all External Python Packages – https://pypi.org/). Whenever a user uses “pip install” to install a package, the pip module communicates with PyPi to search and once the package is located, it downloads the package for the user into his local machine first and then installs it for the user.

Following that, to use the package, all the user has to do is import the installed package into the code file.

For instance, if you ever have an idea and you feel that packaging this idea could make life easier for Python users, you should definitely package your idea and upload it to PyPi. If you want to know how to package your Python code successfully and upload it to PyPi, you can check out the below link where I have written an extensive guide on specifically that topic.

Python Packaging Guide – https://dev.to/shyams1993/python-packaging-guide-25i6

Day 29 – Fun Projects

Hello folks, proud of you for getting this far. Keep up your passion. Now, it’s time to get your hands dirty with some fun projects to show off your Python Skills.

Mini Project 1 : Create a QR Code

What is a QR Code?

Are you also one of those people who has been ever so curious and fascinated by and about QR Codes? A Quick Response code is a two-dimensional bar code that holds information such as webpage URLs, text, and contact information and that information can be retrieved upon scanning the QR code using a QR Code reader. Almost all of the mobiles now have an inbuilt QR Reader.

You can create QR Codes for your portfolios, for your payment links, for your online media, or simply link to your own blogs/pages.

Let’s create a QR Code now.

QR Code Generator – Dependencies

First, we install the package “pyqrcode” by executing “pip install pyqrcode” in the terminal/command prompt.

pip install pyqrcode

If you want to save the output as a png file, you will need to install a dependency named “PyPNG” via the pip install command.

pip install pypng

QR Code Generator – Implementation

Upon successful installation, you will have create a code file and import “pyqrcode” on the first line.

Then, create a variable and assign to it a web page URL or some text . Now you will have to call the member function “create” from the class “pyqrcode” by instantiating the class.

import pyqrcode
link="https://codingdeck.com/blog/python-full-road-map-and-resources/"
output=pyqrcode.create(link)

This creates a QR Code and the final step is to save the output of the QR Code into either a png file or a svg file. For this example, let’s store it a PNG File

output.png("Outputfile.png" , scale=8)

The entire code is just 4 lines long and here is the complete code

import pyqrcode
link="https://codingdeck.com/blog/python-full-road-map-and-resources/"
output=pyqrcode.create(link)
output.png("Outputfile.png" , scale=8)

And here’s the output QR Code that you can scan using your mobile’s camera.

QR Code Output

Wasn’t this fun? Now you can create a QR code for your own resources as well.

Python offers a plethora of such packages and it boasts of the variety/versatility of domains it covers. To name a few, Games, Machine learning, Artificial Intelligence, Natural Language Processing, Computer Vision etc.

Talking about Computer Vision, our next project is going to be a super interesting one and let’s get cracking on that.

Mini Project 2 : Face Detection using Computer Vision

I hope you’re excited about our Mini Project 2 because Face Detection is one of the coolest things that Python’s Computer Vision library can offer where you can write code that identifies a face if there is one found in the image or live stream.

What is Computer Vision?

As the name implies, Computer vision is simply the Computer’s vision. In other words, Computer Vision is the Computer’s representation of what it sees.

How does a Computer read an image?

In the Computer’s vision, it reads an image as a matrix with 3 layers (red, green, and blue), each with values ranging between 0-255, each to signify red, green, and blue. Each element in the i x j matrix represents the red, green and blue values of the pixel at the ith row and jth column (width x height).

Let’s start coding. First, let’s take care of the dependencies.

Face Detection – Dependencies

Firstly, you will need to install the open cv library by typing the below command in your terminal/command prompt. Secondly, as open cv installs, please make sure that “NumPy” also gets installed because all the i x j arrays are NumPy arrays. Usually, it does because NumPy is a dependency package for open cv that is automatically called as soon as open cv is called.

pip install opencv-python

Face Detection – Implementation

#1 – import cv2 and get the HAAR Cascade file’s path

To start with, open a blank file on your code editor and name it with the name you want and a .py extension, say “FaceDetect.py”.

First, Import open cv on the first line using the import keyword.

Followed by that, you would have to input the haar face cascade file.

What is that haar cascade file?

It’s an XML File and Haar Cascade is a machine learning-based approach where a lot of positive and negative images are used to train the classifier.

  • Positive images โ€“ These images contain the images which we want our classifier to identify.
  • Negative Images โ€“ Images of everything else, which do not contain the object we want to detect.

Now, you will have to find the haar cascade file for the frontal face that will hold the markings and processing details of a human face. To find it in your PC, go to the folder where Python’s installed and search for haarcascade_frontface_default.xml. Copy the file’s path and it would typically look like this –

“C:\Users\USER\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml”

Use the file’s path to store it in a variable and remember that the full path of the xml file needs to be specified just like below.

import cv2
haar_file = r'C:\Users\USER\haarcascade_frontalface_default.xml'

#2 – Start the Video Capture

Followed by that you would have to do 2 important things. Firstly, you will have to instantiate the cv2 class (computer vision, version 2) and call its method – CascadeClassifier() passing the haar file as the argument. Secondly, you will have to initialize video streaming by calling cv2’s Video Capture method and specify the argument as 0, because 0 means to use your primary camera.

faceCascade = cv2.CascadeClassifier(haar_file)  
video_capture = cv2.VideoCapture(0)

So the variable video_capture here holds the streaming function. Then we create some kind of a loop that loops over the video stream as separate images frame by frame.

#3 – Gray scale Conversion

Once we have that, we convert the image to a gray scale image and a grayscale (or graylevel) image is simply one in which the only colors are shades of gray. The reason for differentiating such images from any other sort of color image is that less information needs to be provided for each pixel.

Subsequently, the conversion function is called by calling cvtColor method.

while True:
    # Capture frame-by-frame
    frames = video_capture.read()
    gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)

#4 – Detect the object in the image

Followed by that, detectMultiScale function is called and it detects objects of different sizes in the input image. The detected objects are returned as a list of rectangles and in our case, the face is the target image.

faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)

#5 – Draw a Rectangle around the Detected objects

Once we have the rectangles in place, we will need to apply it the resultant image and so we have an inner for loop that iterates using the rectangle’s measurements as values drawing a rectangle for each image in the frame.

    for (x, y, w, h) in faces:
        cv2.rectangle(frames, (x, y), (x+w, y+h), (0, 255, 0), 2)

Now, let’s call the function imshow to display the image. Since we have set the while loop to “True”, it will continuously keep on showing images thus making it look like a video stream but yet is only a sequence of images.

#6 – Set the break to stop the loop

But wait, doesn’t that mean that we’re setting an infinite loop and so how to stop that? Let’s create a condition that says cv2 will wait for 1 ms for each image and waits to see if the key “q” is pressed. If the key q is pressed, the loop will end thus preventing an infinite loop.

    cv2.imshow('Video', frames)
    if cv2.waitKey(1) == ord('q'):
        break

The final code would look like this

import cv2
haar_file = r'C:\Users\USER\haarcascade_frontalface_default.xml'

#Specify the location of the haar cascade file
faceCascade = cv2.CascadeClassifier(haar_file)
#Start the video stream  
video_capture = cv2.VideoCapture(0)
while True:
    # Capture frame-by-frame
    frames = video_capture.read()
    gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)
    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(frames, (x, y), (x+w, y+h), (0, 255, 0), 2)
    # Display the resulting frame
    cv2.imshow('Video', frames)
    if cv2.waitKey(1) == ord('q'):
        break

Go on, execute this and have fun ๐Ÿ™‚

If you get stuck with errors, please drop in into our Discord group or please search online in resources like google, Stack overflow.

Day 30 – n – Some fun problems & Way forward

I have curated a list of some amazing problems for you guys that will keep your brain on adrenaline mode and also strengthen everything that you guys have learned so far.

And, from here on out, you can take different paths. If you are curious and would like to further understand the science of programming & computer science, you could take a course in Data Structures and Algorithms.

If you would like to get into Data Science to play around with and manipulate data, you could always pursue it because Python has a lot of libraries that are widely used for Data Manipulation and Visualization in the wider known field called Data Science.

Python is also highly recommended for Machine Learning because of the availability of libraries that can highly assist in rapidly building efficient Machine learning models for various outcomes.

If you want to go ahead and build a website, Python offers Django that’s one of the most sought after Python library in the world of Python Web Development because of its flexibility and its Object Relational Mapping model.

And of course, gamers, how could I forget you guys? Python literally has it all.

As you may have seen why, Python is everybody’s obvious choice because of the availability of several libraries for versatile domains.

Now having said that, with any stream that you would want to pursue, remember to never ever stop being curious, hungry and passionate to learn, because knowledge is a priceless asset.

Any expert programmer today, was once a beginner and what resonates between all of us is the will to learn and pure raw creativity.

All the best and keep coding.

Leave a Reply