Fun with Python: From Zero to One

Getting starting with simple syntax, string operation to function with fun.

Kashish Rastogi
Analytics Vidhya
9 min readNov 7, 2020

--

Photo by Lukas Blazek on Unsplash

This article aims to discuss all the key features for the basics of the Python programming language. My target is to keep the information accurate, precise, graspable, short, and focus on the key points for better understanding.

After going through this blog, you will be able to implement Python very easily.

You don’t need any prior knowledge of python programming it will be easy to grasp the concept.

Why did I choose python?

  • Choosing python for me was an easy decision because I was bad at remembering the syntax. Python is the easiest language to learn and easy to code for complex problems.
  • Working with python was easy as we can use python in web development, data science, machine learning, deep learning, and what not.

1. Introduction to python

3w’s & H of Python?

Who created python?

  • The world’s most influential programmer Guido van Rossum created python in 1991 for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.

Why do we need to learn python?

  • Python is a high-level object-oriented dynamically-typed scripting language.
  • Python is the most popular language as a fact it’s easy to write and understand the code.
  • As a fact, it takes less time to bring a Python program to market compared to other languages such as C#/Java.
  • Python has different libraries that we can use in Machine Learning and Data Science.
  • A large number of online material and books are available supporting python developers.

Where can we use python?

  • Developing desktop GUI applications,
  • web development
  • game development
  • web scrapping application
  • audio and video application
  • Business intelligence
  • Data analysis, etc

How does python work?

  • Here Interpreter translates high-level python language to low-level machine language.
  • A python virtual machine is created where libraries are installed.
  • Python code is then written into a .py file.
  • CPython compiles the Python code to bytecode. This bytecode is for the Python virtual machine.

2 . The Basics

variables

  • In simple terms, think of variables as storing information. This information can be of any type int, float, string, collection, etc. In python, it is effortless to assign values to variables.
  • The fundamental concept of python is that everything is an object in python.
  • Like any other language, we don’t need to write the data type followed by a variable name, as data types are dynamic in nature.
  • Now imagine you want to store 10 numbers in a variable called ‘x.’

let’s see how it’s done:

Data Types

The chart shows the build in Data Types.

3. Collection

  • In simple terms, collections in python are containers that store the collection of data like list, set, tuple, dict, etc.
  • These are built-in collections.
  • Let’s take a closer look at the properties in List, Tuple, Set, and Dictionary.

Below, a chart shows different properties where we can use list, tuple, set, and dictionary.

List

  • List are written in square bracket.
  • List can contain more than one type of data type element like int, float, string
  • Negative indexing means the element is going to be chosen from the end (right side).
  • -1 refers to the last item, -2 refers to the second-last item.
  • Range of indexing means we can specify a range of indexes by telling where to start and where to end.

The below code shows how we can access the element by negative and positive indexing and also a range of indexing.

Tuple

  • Tuples are written in round brackets. We can’t change tuples like lists.
  • The below code shows how we can access the element by negative and positive indexing and also a range of indexing.

Some basic functions which we can implement on tuple like deleting, indexing, slicing of elements.

Set

Sets are written in curly brackets.

The below code shows how we can access the element by negative and positive indexing and also a range of indexing.

We can perform other functions on set are add, update, remove, pop, and del item.

  • The add() method will add one element to set.
  • The update() method will add more than one item to set.
  • The remove() method will remove an item from the set.
  • The pop() method will remove the last element from the set.
  • The clear() method will empty the set.
  • The del keyword will delete the whole set completely.

Dictionary

  • Dictionary is a collection of key-value pairs.
  • The key is the index pointing to the value. We can access the dictionary value by key.

let’s see how it’s done:

Other functions which we can perform on a dictionary are add(), remove(), change(), clear(), copy(), del, etc.

  • The add(), remove(), clear(), del() methods are having the same function as above mentioned in the set.
  • The change() method will change a specific item by referring to its key name.
  • The copy() method will create an exact copy of dict.

4. Control flow:

“if “ is used to check whether the given condition is True or False. If it is true, then it executes what is inside the if statement.

Let’s see how it’s done:

Here the condition is true so if the statement will execute.

The “else” statement will be executed only when a condition is false

let’s see how it’s done:

Here the condition is false as 10 is not greater than 20, so else the statement will execute.

We can also use the “elif” statement when there are more than one condition.

let’s see how it’s done:

Nested if-else

nested if-else means having if-else in another if-else.

To avoid confusion, use proper indentation in nested if-else.

let’s see how it’s done:

As the number is10, so the first of all number will be checked whether it is greater than zero or not, then it will proceed to the next if condition, where the number will be compared to zero, where the condition is false, so else statement, will execute.

5. shorthand:

  • We use shorthand statements so that we can write more logic and less number of statements.
  • For a better understanding, there is a table having syntax and examples of how to use the shorthand.

Only experts Python Programmers can only understand!

6. Looping:

In python, we can loop in a different form:

“for” loop is used for iterating over a sequence.

Here range() function defaults to increment the value by 1; if you apply any other value like 3, then the increment will be of 3 values or -1, then decrement will be of -1 times.

Let’s see how it’s done:

“While” loop will be executed until the condition becomes false.

Let’s see how it’s done:

Here remember to increment the value of I, or else the loop will execute forever.

7. String functions

Below code for the most common use of build-in string functions.

  • lower(): Returns the string in lower case
  • upper(): Returns the string in upper case
  • replace(): Returns the string with replaced value
  • split(): splits the string into substrings
  • capitalize(): Converts the first character to upper case center() Returns a centered string
  • count(): Returns the number of times a specified value occurs in a string
  • find(): Search the string for a specific value, then return the position of where it was found

Slicing

  • Python slicing is about finding a substring from the given string by slicing with respectively from start to end.
  • Slicing can be done in two ways
  1. slice() constructor

Syntax:

slice(start,stop,step)

slice(stop)

Parameters:

  • start: starting index from where slicing will be done.
  • stop: stopping index from where slicing will be done
  • step: It is an optional parameter which determines the increment between each index of slicing

let’s see how it’s done:

Here with the help of the slice constructor's starting point is 1, and the ending point is 5 with the increment of 2.

Slice constructor for Negative indexing where starting and ending point is -1 & -12 respectively where a step is -2.

2. Extending indexing

In python, indexing syntax can be used for a slice object.

Syntax: string[start,end,step]

Let’s see how it’s done:

8. Function

  • The function is a block of organized, reusable code which only runs when called.
  • The function is defined using the def keyword, and to call a function, just use the function name followed by a parenthesis.
  • More than one argument can be passed in function, just separate with the comma.
  • Functions help break our program into smaller and modular chunks.
  • It also avoids repetition and makes the code reusable.
  • syntax:

def function_name(parameter):

statement(s)

  • A function can be of two types.
  1. Built-in function: the function that are built in python
  2. User-defined function: functions defined by the users themselves

a user-defined function is divided into 4 functions:

  1. Required arguments
  • Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.

2. Default arguments

  • The main purpose of the default argument is to select the default argument if a function is called without argument.

let’s see how it’s done:

3 . Keyword-based arguments

  • If we don’t know how many arguments we are going to use in a function, we can use ‘**’ before the parameter name in the function definition.
  • The arbitrary keyword arguments are often shortened to kwargs in python

let’s see how it’s done:

4. Variable length arguments

  • In variable length arguments, we need to process a function for more arguments than you specified while defining the function.
  • Putting an * before the variable name that holds the value of all non keyworded variable argument

let’s see how it’s done:

Here we didn't know that how many hobbies will be there, so we put * before hobby. So calling the function is now easy.

9. Lambda

  • The most effective function is lambda, as by writing fewer code, the problem is solved.
  • One is free to use lambda functions wherever function objects are required.
  • The main use of lambda is when we use them as an anonymous function inside another function.
  • In the lambda function, we can use as many arguments as we want but can only have one expression.

let’s see how it’s done:

The first function value is increment by 1.

We can assign operations to multiple variables in one line only, which is only possible by using the lambda function, which helps in minimizing the time for writing the code.

Lambda function

let’s see how it’s done:

Here there are two different functions in which one function ‘x’ values is 4 and for the other, it is 3, but the ‘a’ value is not changed it's 2 only.

We can combine both the function in one function with the help of the lambda function, which will result in efficient code and increases the speed.

Map()

The built-in function map() takes a function as a first argument and applies it to each of the elements of its second argument, int, strings, tuples.

map() functions it's more flexible and easier.

let’s see how it’s done:

Here using map() function all the elements will convert into uppercase without writing the same code for every function.

Filter()

  • The function is applied to a particular element.
  • The filter passes each element in function and returns only the ones which have true value.

10. Use of lambda() with map(), filter()

  • As we know, the lambda keyword is used for the creation of an anonymous function.
  • map() function in python takes in a function and a list of arguments. A new list will be returned after all the modifications done in the list.
  • Filter () function in python takes in a function and a list of arguments. A new list will be returned having elements that have the true condition.

In the first example, all the elements will be converted into the lower case with the help of map() and lambda().

In the second example, the odd elements are only going to print.

That’s it!

This blog is divided into various subsections.

  1. Introduction to Python
  2. Basics
  3. Collection (List, tuple, set, dict)
  4. Control Flow (if, if-else, if-elif-else, nested if-else)
  5. Shorthand
  6. Looping (for, while)
  7. String function
  8. Function (Required, Default, Keyword & Variable arguments)
  9. Lambda/ Map/ Filter
  10. Use of lambda() with map() and filter()

References

I hope you liked this content. Support my work!

--

--

Kashish Rastogi
Analytics Vidhya

Data Analyst | Data Visualization | Storyteller | Tableau | Plotly