avatarAmit Chauhan

Summary

The provided web content offers a comprehensive guide on Python programming, covering basics to advanced topics including variables, strings, data structures, operators, control statements, functions, and lambda expressions, aiming to clarify concepts for beginners with practical examples.

Abstract

The web content serves as an extensive tutorial for Python novices, systematically introducing programming concepts through Python. It begins with fundamental elements such as variables and strings, then progresses to more complex data structures like lists, tuples, sets, and dictionaries. The guide also delves into the use of operators, including arithmetic, assignment, relational, unary, logical, and bitwise, and demonstrates how to import libraries to extend Python's functionality. Control statements such as if-else, loops, and the use of break, continue, and pass keywords are explained with examples to illustrate their application in controlling program flow. The content further explores the creation and manipulation of arrays and matrices using NumPy, discusses function definition, argument types, and scope, and concludes with an introduction to lambda functions and their use with filter, map, and reduce operations. The article emphasizes practical learning, ensuring that readers not only understand the theoretical aspects but also gain hands-on experience through code examples.

Opinions

  • The author believes that Python's versatility makes it suitable for various applications, from web development to artificial intelligence.
  • The article suggests that learning Python need not be dull, encouraging a fun and engaging approach to programming.
  • Importing libraries is presented as a necessary step to access additional functions and enhance Python's capabilities.
  • The use of control statements is emphasized as crucial for executing code based on specific conditions, thus providing flexibility in program logic.
  • The author advocates for the use of lambda functions for concise operations, highlighting their efficiency in data processing tasks.
  • The article promotes the idea that breaking down complex tasks into smaller functions can improve the manageability of large projects.
  • The author expresses the importance of understanding the difference between global and local variables to avoid common scoping issues in Python programming.

Programming

Python: Zero to Hero with Examples

A handbook guide for python beginners

Photo by Fernando Hernandez on Unsplash

This article will help many python learners who feel confused about where to start—the concept and examples of python from basic will clear the doubts of every beginner.

The topics to be covered in the long article is shown below:

Section 1: Basics of variables and strings

Section 2: List, Tuple, Set, Dictionary, Range

Section 3: Operators and Importing Libraries

Section 4: If-else and Loops

Section 5: Break, Continue, and Pass keywords.

Section 6: Array and Matrices

Section 7: Functions, Scope, and Arguments

Section 8: Lambda function with Filter, Map, and Reduce

I hope this long article will not make you bore with learning, lets the fun begin.

Section 1:

Basics of variables and strings

I think there is no need for an introduction to what python language is and how useful it is in various applications from web development to artificial intelligence — covering all domains.

What is a variable?

It is a name and storage container in which we assign some values in the form of int or string.

What is a string?

It is a Unicode character in the form of arrays of bytes.

Cool! we got an idea of variables and string definition. Now look for some practical example shown below:

In python, the creation of a variable is effortless. Just write a user-friendly name so that in the future other programmers can understand what it is used for in the program.

#creating a variable name
a = 10
char = "Happy"
float_number = 12.5

#How to check the length of the string
print(len(char))              

#output : 5

#how to add the other string to the existing string
print(char + 'World')        

#output : Happy World

#we cannot change the character of the string by index
char[1] = 'i'
print(char[1])

#output : error, 'str' object does not support item assignment

In the above example, (a, char, float_number) these are variable names given to integer, string, and float value by assigning(=) with this sign.

Section 2:

List

  • It is mutable
  • It uses [] brackets
  • The list is used to group numbers of things in a single bracket [].

Example:

We can create a list by using a square bracket with a variable. Here, ‘list1’ is a variable name, and five integer values assigning to it.

list1 = [1,2,3,4,5]
print(list1)             #output : [1,2,3,4,5]
#accessing values by indexing
print(list1[0])          #output : 1
print(list1[4])          #output : 5
print(list1[2:])         #output : [3,4,5]
print(list1[-1])         #output : 5
print(list1[-5])         #output : 1

A list is an instrumental data structure in python. We can put multiple data types in a list. The list can have float values, integer values, and string values in it.

list2 = [ 5.5, 4, 'Amit']

We can also put multiple lists in a list.

list3 = [list1, list2] 

We can also do operations on lists like append, insert, remove, etc.

list1 = [1,2,3,4,5]
list1.append(6)
print(list1)                     #output : [1,2,3,4,5,6]
#if we remove any values from the list
list1.remove(2)
print(list1)                     #output : [1,3,4,5,6]
#if we insert any values from the list by indexing
list1.insert(2,30)
print(list1)                     #output : [1,3,30,4,5,6]
#deleting values from the list
del list1[3:]
print(list1)                     #output : [1,3,30]

There are various operations in the list, and try to do it all for more clarity.

Tuple

  • It is Immutable.
  • It is almost the same as the list, but the tuple uses a round bracket ().

Immutable means that we cannot change the values of the tuple.

Examples:

tup1 = (20,30,40,50)
print(tup1[2])                         #output : 40
#what if we change the values
tup1[2] = 44
print(tup1)   
#output : error, 'str' object does not support item assignment

Where we use tuples

  • It is like a list. We don’t want to change the value of it. In certain projects, we have a requirement where we don’t need to change the values. We go for a tuple.
  • Iteration in the tuple is faster than the list and enhance the speed of the execution.

Set

  • It is also a collection of elements.
  • Set is differentiating with curly brackets {}.
  • The set never follows the sequence.

Example:

set1 = {21,32,55,46}
print(set1)                 #output : {32,46,55,21}

Here, we saw that the output of the set values sequence is not exactly the same. Can we get the values in the set by indexing? Let's check.

print(set1[2])                   #output : error

In set, there is not any sequence, so we cannot access values by indexing.

Dictionary

  • In the dictionary, we assign keys to all values.
  • It uses curly brackets {} with key-value pairs.

Example:

dic = {1:'Apple', 2:'Orange', 3:'Banana'}
print(dic)
#output:
{1:'Apple', 2:'Orange', 3:'Banana'}

In a dictionary, we can access keys and values separately also.

print(dic.keys())
print(dic.values())
#output:
dict_keys([1,2,3])
dict_values(['Apple','Orange','Banana'])

We can use keys to get the values also.

print(dic[2])               #output : 'Orange'

Range

  • The range is used to get a range from starting point to the endpoint, i.e., a fixed interval.

Examples:

range(10)
print(range(10)                 #output: range(0,10)
print(list(range(10))           #output : [0,1,2,3,4,5,6,7,8,9]
#starting point, end point, difference between them
print(list(range(2,10,2)))      #output : [2,4,6,8]

Section 3:

Operators

Operators in python are of various types to do arithmetic and computation processes. Types of the operator are shown below:

  • Arithmetic Operator

Example:

x,y = 2,3
print(x+y)                         #output : 5
print(x-y)                         #output : -1
print(x*y)                         #output : 6
print(x/y)                         #output : 0.6666
  • Assignment Operator

Example:

x = 8
x = x+2
print(x)            #output : 10
x += 2
print(x)            #output : 12
x *= 2
print(x)            #output : 24
#assigning multiple values in one line 
x,y = 2,3
  • Relational Operator

Example:

x,y = 5,6
print(x<y)           #output : True
print(x>y)           #output : False
for comparison we use double equal sign '=='
print(x=y)          #output : False
print(x<=y)         #output : True
print(x>=y)         #output : True
print(x!=y)         #output : True
  • Unary Operator

Example:

x = 3
print(x)              #output : 3
print(-x)             #output : -3
x = -x
print(x)              #output : -3
  • Logical Operator

Example:

# 'and' - condition 
x,y = 5,4
print(x<8 and y<5)             #output : True
print(x<8 and y<2)             #output : False
# 'or' - condition
print((x<8 or y<2))            #output : True
# 'not'
x = True
print(x)                       #output : True
print( not x)                  #output : False
  • Bitwise Operator

Bitwise operators are used to doing bitwise calculations on integers.

Example:

# Compliment ( ~ ) operator
print(~12)                        #output : -13
#Bitwise And ( & ) operator
print(12&13)                      #output : 12
#Bitwise Or ( | ) operator
print(12|13)                      #output : 13
# Xor ( ^ ) operator 
print(12^13)                      #output : 1
# Left shift ( << ) operator
print(10<<2)                      #output : 40
# Right shift ( >> ) operator
print(10>>2)                      #output : 2

Importing Libraries

  • Sometimes python alone does not have all function itself, and we need to import them from libraries so that we can use them in our algorithms and program.

Example:

#finding the square root 
a = sqrt(36)
print(a)               #output : error, name sqrt is not defined

So, we need to import a math library to use the sqrt function

import math
a = math.sqrt(36)
print(x)                 #output : 6.0
a = math.sqrt(15)
print(x)                 #output : 3.8729

When we have some decimal values, then to get integer value, we use two functions, i.e., floor and ceil

floor — whatever value comes in floor function it will round off to the bottom number

Ceil — Whatever value comes in the ceil function, it will round off to the top number. Even if 2.1, it will show the 3.

Example:

print(math.floor(2.9))           #output : 2
print(math.ceil(2.2))            #output : 3

What if instead of using math word in importing, just use ‘m’ for this we have to call it as an alias name

import math as m
print(m.sqrt(36))   #output : 6.0

Section 4:

if-else

  • Control statements are used to execute statements base on conditions given to them. If the condition is true, then it will execute the if part otherwise, not.

Example:

# if 
if True:
    print("This statement is True")
#output : This statement is True

The condition of the if is True so, the statement will execute.

Here, we encounter two new things—the colon after condition and spaces in the next line. The colon is for that some block is started and inside that block, we give indentation ( spaces ) so that, this statement belongs to this block only.

x = 6
remainder = x%2
if remainder == 0:
    print("Even")
else:
    print("odd")
print("loop works")
#output:
even
loop works

While loop

  • Loops are used in programming to repeat iterations.

Example:

a = 1
while a<=3:
    print("It is working")
    a = a+1
#output:
It is working
It is working
It is working
It is working

For loop

  • It is used for sequence.

Example:

a = [1, 2, 'Amit']
print(a)               #output:[1, 2, 'Amit']

What if we want values in the list by iteration means one by one.

a = [1, 2, 'Amit']
for i in a:
    print(i)
#output:
1
2
Amit
b =  'AMIT'
for i in b:
    print(i)
#output:
A
M
I
T

Section 5:

In some conditions, we use these keywords to break, continue, and pass to make the code more useful.

Break keyword

  • If the condition is not true, then it comes out from the loop.

Example:

x = 4
a = int(input('Enter the number:'))
b = 1
while b<=a:
    if b>=x:
        break
    print("Hello")
    b+=1
print("Done")
#output:
Enter the number: 5
Hello
Hello
Hello
Hello
Done

Continue keyword

  • The continue keyword is used to skip the true statement and continue to print others.
for i in range(1, 10):
    if i%3==0 or i%5==0:
        continue
    print(i)
print("Done")
#output:
1
2
4
6
7
8

Pass Keyword

  • The pass keyword is used to skip the true statement and continue to print others.
for i in range(1, 11)
    if(i%2!=0):
        pass
    else:
        print(i)
print("Done")
#output:
2
4
6
8
10

Section 6:

Array

  • The array is handy for a variable that holds many values.
  • Array does not have a fixed size. Expand it, shrink it.
  • We have to import an array to use them in the program.
import array import *
num = array()
  • Star * is used to import all functions from the array.

Example:

import array import *
num = array('i', [1,2,3,4,5])
print(num)
#output: array('i',[1,2,3,4,5])
  • In the array value, the code ‘i’ stands for integer values only in the list.
  • How to check the buffer (address and typecode).
import array import *
num = array('i', [1,2,3,4,5])
print(num.buffer_info())
print(num.typecode)
#output:
(85049343, 5)
i
  • The buffer gives the address and size of the array.
  • We can use the character typecode also for working with character.
import array import *
num = array('i', ['a','b','c'])
for i in num:
    print(i)
#output:
a
b
c
  • To get the index number of the value in an array.
import array import *
num = array('i', [1,2,3,4,5])
num1 = int(input("value for search: ")
print(num.index(num1))
#output:
value for search: 3
2      #it is index number

Ways of creating arrays

  • array()
import array import *
num = array([1,2])
print(num)
print(num.dtype)
#output:
[1,2]
int32
  • linspace()
num = linspace(1,5,6)
print(num)
#here 6 means breaking range 1 to 5 into 6 parts
#output: [0., 1., 2., 3., 4., 5.]
  • arange()
num = arange(1, 10, 3)
print(num)
#output: [1 4 7 10]

There are many other functions also.

Adding two Arrays

ar1 = array([1,2,3])
ar2 = array([4,5,6])
ar3 = ar1 + ar2
print(ar3)
#output: [5 7 9]

Concatenate two arrays

ar1 = array([1,2,3])
ar2 = array([4,5,6])
print(concatenate([ar1, ar2])
#output: [1 2 3 4 5 6]

Shallow and Deep copy

Shallow copy: Both arrays are still dependent on each other

Example:

ar1 = array([1,2,3])
ar2 = ar1.view()
ar1[0] = 5
print(ar1)
print(ar2)
#output:
[5 2 3]
[5 2 3]

When we use shallow copy, it also changing the value in the second array also.

Deep copy: Two arrays which is not linked with each other in any way use function copy() instead if viewe().

ar1 = array([1,2,3])
ar2 = ar1.copy()
ar1[0] = 5
print(ar1)
print(ar2)
#output:
[5 2 3]
[1 2 3]

Matrix

  • Matrix is a special data type in a data structure in which data are arranged in a multi-dimensional array.
  • Array does not support a multi-dimensional array that why a third package NumPy is used.

Example:

from numpy import *
ar1 = array([
             []
             []
            ])
print(ar1)
print(ar1.dtype)
#output:
[[1 2 3]
 [4 5 6]]
int32

To know the dimension of array, use (ndim).

print(ar1.ndim)
print(ar1.shape)
#output:
2
(2,3)     # row and column
print(ar1.size)
#output:  6

Three Dimensional array

ar1 = array([
             [1,2,3,4,5,6], 
             [2,5,2,7,9,10]
           ])
ar2 = ar1.flatten()
ar3 = ar2.reshape(3,4)
print(ar3)
#output:
[[1 2 3 4]
 [5 6 2 5]
 [2 7 9 10]]

Section 7:

Functions

  • When we are working on a big project, we can break into smaller tasks, and then we use functions.
  • Two main things we have to know.
  1. Defining a function
  2. Calling a function

Syntax

def function_name():

We use a def word to define a function.

Example:

def hello():                    # Defining a function
    print("This is the first statement")
hello()                         # Calling a function
  • We can allocate a task to a function.
  • We can call the function multiple times.
#adding two numbers
def add(a,b)
    x = a+b
    print(x)
add(2,3)     # passing two arguments when we call a function
#output: 5

Types of Argument

  • Formal Arguments: Which are defined in a function.
  • Actual Arguments: Define in a calling function.

In actual arguments, there are 4 types:

  1. Position

Example:

def person(name, age):
    print(name)
    print(age)
person('Amit', 25)
#output:
Amit
25

In position argument, how do we know that Amit goes to name and 25 goes to the age? That’s where position comes into role.

2. Keywords

  • We use keywords if we don’t know the sequence.
person(age = 25, name = 'Amit')

3. Default

One argument is already defined in a formal argument, and only one argument has to pass.

def person(name, age = 25):
    print(name)
    print(age)
person('Amit')

4. Variable-length Argument

  • This type of argument is used to pass multiple values.

Example:

def sum(x, *y)
    a = x+y
    print(a)
sum(5,6,7,2)
  • Here, the tip is that when we pass multiple values, then the first value goes to the first formal argument, and the star used with the second formal argument is to accept all other values in it.
  • x gets 5 and *y get (6,7,2)

Scope

  • It is based on Global and Local variables in a function.
x = 5                #this is Global Variable
def hello():
    x = 10           #this is Local Variable
    print(x)
hello(x)

If we want to make a local variable to a global variable so, we need to write global explicitly.

x = 5                #this is Global Variable
def hello():
    global x
    x = 10           #this is Local Variable
    print(x)
hello(x)

Section 8:

Lambda function with Filter, Map and Reduce

Lambda is a function in which we do all function tasks in one statement. Sometimes we work on big data and break them into small chunks, and we do filter the data, map the data, and reduce the data.

Example:

func = lambda x:x*x
result = func(x)
print(result)
#output:
25

Filter function

Syntax

filter(function, iterable)

This function is a customized function. It only returns one value. In that case, use lambda.

def is_even(x):
    return x%2 == 0
num = [2,6,7,4,9,10]
even = list(filter(lambda x:x%2==0, num)
print(even)
#output:
[2,6,4,10]

Map function

Syntax

map(function, iteration)

After filtration, we need to map the data.

num = [2,6,7,4,9,10]
even = list(filter(lambda x:x%2==0, num)
add = list(map(lambda x: x+2, even))
print(add)
#output:
[4,12,8,20]

Reduce function

  • Reduce function belongs to a module called functools.
from functools import reduce
num = [2,6,7,4,9,10]
even = list(filter(lambda x:x%2==0, num)
add = list(map(lambda x: x+2, even))
sum = reduce(lambda a,b: a+b, add)
print(sum)
#output:
44

Conclusion

Almost python is used in every field for business development. This article gives a few basic concepts of python for new beginners. I hope you made it to the last. If you forget something, go up again and read.

I hope you like the article. Reach me on my LinkedIn and twitter.

Recommended Articles

1. 15 Most Usable NumPy Methods with Python 2. NumPy: Linear Algebra on Images 3. Exception Handling Concepts in Python 4. Pandas: Dealing with Categorical Data 5. Hyper-parameters: RandomSeachCV and GridSearchCV in Machine Learning 6. Fully Explained Linear Regression with Python 7. Fully Explained Logistic Regression with Python 8. Data Distribution using Numpy with Python 9. 40 Most Insanely Usable Methods in Python 10. 20 Most Usable Pandas Shortcut Methods in Python

Python
Programming
Data Science
Analytics
Machine Learning
Recommended from ReadMedium