You are on page 1of 20

Python if Statement

number = 10

# check if number is greater than 0


if number > 0:
print('Number is positive.')

print('The if statement is easy')


Run Code

Output

Number is positive.
The if statement is easy

In the above example, we have created a variable named  number . Notice the
test condition,

number > 0

Here, since  number  is greater than 0, the condition evaluates  True .
If we change the value of variable to a negative integer. Let's say -5.
number = -5

Example 2. Python if...else Statement


number = 10

if number > 0:
print('Positive number')

else:
print('Negative number')

print('This statement is always executed')


Run Code

Output

Positive number
This statement is always executed

In the above example, we have created a variable named  number . Notice the
test condition,
number > 0

Example 2: Python while Loop


# program to calculate the sum of numbers
# until the user enters zero

total = 0

number = int(input('Enter a number: '))

# add numbers until number is zero


while number != 0:
total += number # total = total + number

# take integer input again


number = int(input('Enter a number: '))

print('total =', total)


Run Code

Output

Enter a number: 12
Enter a number: 4
Enter a number: -5
Enter a number: 0
total = 11

In the above example, the  while  iterates until the user enters zero. When
the user enters zero, the test condition evaluates to  False  and the loop
ends.
Python break Statement with while Loop
We can also terminate the  while  loop using the break statement. For
example,
# program to find first 5 multiples of 6

i = 1
while i <= 10:
print('6 * ',(i), '=',6 * i)

if i >= 5:
break

i = i + 1
Run Code

Output

6 * 1 = 6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
6 * 5 = 30

In the above example, we have used the  while  loop to find the
first 5 multiples of 6. Here notice the line,
Example: Python Function
def greet():
print('Hello World!')

# call the function


greet()

print('Outside function')
Run Code

Output

Hello World!
Outside function

In the above example, we have created a function named  greet() . Here's


how the program works:
Working of Python Function
Here,

 When the function is called, the control of the program goes to the
function definition.

 All codes inside the function are executed.

The control of the program jumps to the next statement after the function

call.

Example 1: Python Function Arguments


# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ",sum)

# function call with two values


add_numbers(5, 4)

# Output: Sum: 9
Run Code

In the above example, we have created a function named  add_numbers()  with


arguments:  num1  and  num2 .
Example 4: Python Library Function
import math

# sqrt computes the square root


square_root = math.sqrt(4)

print("Square Root of 4 is",square_root)

# pow() comptes the power


power = pow(2, 3)

print("2 to the power 3 is",power)


Run Code

Output

Square Root of 4 is 2.0


2 to the power 3 is 8

In the above example, we have used

 math.sqrt(4)  - to compute the square root of 4


 pow(2, 3)  - computes the power of a number i.e. 23

Python Class and Object


class Parrot:

# class attribute
name = ""
age = 0

# create parrot1 object


parrot1 = Parrot()
parrot1.name = "Blu"
parrot1.age = 10

# create another object parrot2


parrot2 = Parrot()
parrot2.name = "Woo"
parrot2.age = 15

# access attributes
print(f"{parrot1.name} is {parrot1.age} years old")
print(f"{parrot2.name} is {parrot2.age} years old")
Run Code
Output

Blu is 10 years old


Woo is 15 years old

In the above example, we created a class with the name  Parrot  with two
attributes:  name  and  age .
Then, we create instances of the  Parrot  class. Here,  parrot1  and  parrot2  are
references (value) to our new objects.
We then accessed and assigned different values to the instance attributes
using the objects name and the  .  notation.
Use of Inheritance in Python
# base class
class Animal:

def eat(self):
print( "I can eat!")

def sleep(self):
print("I can sleep!")

# derived class
class Dog(Animal):

def bark(self):
print("I can bark! Woof woof!!")

# Create object of the Dog class


dog1 = Dog()

# Calling members of the base class


dog1.eat()
dog1.sleep()

# Calling member of the derived class


dog1.bark();
Run Code

Output

I can eat!
I can sleep!
I can bark! Woof woof!!

Here,  dog1  (the object of derived class  Dog ) can access members of the base
class Animal. It's because  Dog  is inherited from  Animal .

Polymorphism
class Polygon:
# method to render a shape
def render(self):
print("Rendering Polygon...")

class Square(Polygon):
# renders Square
def render(self):
print("Rendering Square...")

class Circle(Polygon):
# renders circle
def render(self):
print("Rendering Circle...")

# create an object of Square


s1 = Square()
s1.render()

# create an object of Circle


c1 = Circle()
c1.render()
Run Code

Output

Rendering Square...
Rendering Circle...

In the above example, we have created a superclass:  Polygon  and two


subclasses:  Square  and  Circle . Notice the use of the  render()  method.
The main purpose of the  render()  method is to render the shape. However,
the process of rendering a square is different from the process of rendering
a circle.
Hence, the  render()  method behaves differently in different classes. Or, we
can say  render()  is polymorphic.

Python Class and Objects


# define a class
class Bike:
name = ""
gear = 0

# create object of class


bike1 = Bike()

# access attributes and assign new values


bike1.gear = 11
bike1.name = "Mountain Bike"

print(f"Name: {bike1.name}, Gears: {bike1.gear} ")


Run Code

Output

Name: Mountain Bike, Gears: 11

In the above example, we have defined the class named  Bike  with two
attributes:  name  and  gear .

How to use lambda function with map()?


numbers = (1, 2, 3, 4)
result = map(lambda x: x*x, numbers)

print(result)

# converting map object to set


numbersSquare = set(result)
print(numbersSquare)
Run Code

Output

<map 0x7fafc21ccb00>
{16, 1, 4, 9}
Passing Multiple Iterators to map() Using Lambda

In this example, corresponding items of two lists are added.

num1 = [4, 5, 6]
num2 = [5, 6, 7]

result = map(lambda n1, n2: n1+n2, num1, num2)

print(list(result))
Run Code

Output

[9, 11, 13]

Numpy Constants

import numpy as np

radius = 2
circumference = 2 * np.pi * radius
print(circumference)

Output

12.566370614359172

Create a DataFrame from Lists


The DataFrame can be created using a single list or a list of lists.
Example 1
import pandas as pd
data = [1,2,3,4,5]
df = pd.DataFrame(data)
print df
Its output is as follows −
0
0 1
1 2
2 3
3 4
4 5
Create a DataFrame from Dict of ndarrays / Lists
All the ndarrays must be of same length. If index is passed, then the length of the index
should equal to the length of the arrays.
If no index is passed, then by default, index will be range(n), where n is the array length.
Example 1
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data)
print df
Its output is as follows −
Age Name
0 28 Tom
1 34 Jack
2 29 Steve
3 42 Ricky
Note − Observe the values 0,1,2,3. They are the default index assigned to each using the
function range(n).

Aggregation and Grouping


In this article, we are going to see grouping and aggregating using pandas. Grouping
and aggregating will help to achieve data analysis easily using various functions.
These methods will help us to the group and summarize our data and make complex
analysis comparatively easy.  
Creating a sample dataset of marks of various subjects.
Python
# import module
import pandas as pd
  
# Creating our dataset
df = pd.DataFrame([[9, 4, 8, 9],
                   [8, 10, 7, 6],
                   [7, 6, 8, 5]],
                  columns=['Maths',  'English', 
                           'Science', 'History'])
  
# display dataset
print(df)

Output:

Example 7: Python csv.DictWriter()

import csv

with open('players.csv', 'w', newline='') as file:


fieldnames = ['player_name', 'fide_rating']
writer = csv.DictWriter(file, fieldnames=fieldnames)

writer.writeheader()
writer.writerow({'player_name': 'Magnus Carlsen', 'fide_rating': 2870})
writer.writerow({'player_name': 'Fabiano Caruana', 'fide_rating': 2822})
writer.writerow({'player_name': 'Ding Liren', 'fide_rating': 2801})

The program creates a players.csv file with the following entries:

player_name,fide_rating
Magnus Carlsen,2870
Fabiano Caruana,2822

Pandas DataFrame query() Examples

Example 1: Single condition filtering In this example, the data is filtered on the basis
of a single condition. Before applying the query() method, the spaces in column
names have been replaced with ‘_’. 
 Python3
# importing pandas package

import pandas as pd

  
# making data frame from csv file

data = pd.read_csv("employees.csv")

  

# replacing blank spaces with '_'

data.columns = 

    [column.replace(" ", "_") for column in data.columns]

  

# filtering with query method

data.query('Senior_Management == True', 

                           inplace=True)

  

# display

data

Output: 
As shown in the output image, the data now only have rows where Senior
Management is True. 

 
Example 2: Multiple conditions filtering In this example, Dataframe has been filtered
on multiple conditions. Before applying the query() method, the spaces in column
names have been replaced with ‘_’. 
 Python3
# importing pandas package

import pandas as pd

  

# making data frame from csv file

data = pd.read_csv("employees.csv")

  

# replacing blank spaces with '_'

data.columns = 

    [column.replace(" ", "_") for column in data.columns]

  

# filtering with query method

data.query('Senior_Management == True

           and Gender == "Male" and Team == "Marketing"

           and First_Name == "Johnny"', inplace=True)

  

# display

data

Output: 
As shown in the output image, only two rows have been returned on the basis of filters
applied. 
Example
Create a simple Pandas Series from a list:

import pandas as pd

a = [1, 7, 2]

myvar = pd.Series(a)

print(myvar)

Example
Create your own labels:

import pandas as pd

a = [1, 7, 2]

myvar = pd.Series(a, index = ["x", "y", "z"])

print(myvar)

Example
Create a simple Pandas Series from a dictionary:

import pandas as pd

calories = {"day1": 420, "day2": 380, "day3": 390}

myvar = pd.Series(calories)

print(myvar)

Visualize the Time Series 


Table of Contents

In [4]:
def plot_df(df, x, y, title="", xlabel='Date', ylabel='Number of Passengers', dpi=100):
plt.figure(figsize=(15,4), dpi=dpi)
plt.plot(x, y, color='tab:red')
plt.gca().set(title=title, xlabel=xlabel, ylabel=ylabel)
plt.show()
plot_df(df, x=df['Date'], y=df['Number of Passengers'], title='Number of US Airline passengers from 1949 to
1960')

 Since all the values are positive, we can show this on both sides of the Y axis to
emphasize the growth.

Decomposition of a Time Series 


Table of Contents

 Decomposition of a time series can be performed by considering the series as an


additive or multiplicative combination of the base level, trend, seasonal index and the
residual term.

 The seasonal_decompose in statsmodels implements this conveniently.


In [7]:
from statsmodels.tsa.seasonal import seasonal_decompose
from dateutil.parser import parse

# Multiplicative Decomposition
multiplicative_decomposition = seasonal_decompose(df['Number of Passengers'], model='multiplicative',
period=30)

# Additive Decomposition
additive_decomposition = seasonal_decompose(df['Number of Passengers'], model='additive', period=30)

# Plot
plt.rcParams.update({'figure.figsize': (16,12)})
multiplicative_decomposition.plot().suptitle('Multiplicative Decomposition', fontsize=16)
plt.tight_layout(rect=[0, 0.03, 1, 0.95])

additive_decomposition.plot().suptitle('Additive Decomposition', fontsize=16)


plt.tight_layout(rect=[0, 0.03, 1, 0.95])

plt.show()
Setting the Timezone
Make use the pytz.timezone() function to create a timezone object and assign it to a variable

Example
import pytz

from datetime import datetime

# Create a timezone object for US/Eastern

eastern_tz = pytz.timezone('US/Eastern')

now = datetime.now()

now_eastern = eastern_tz.localize(now)

print(now_eastern)

Output
2023-04-17 16:58:31.317459-04:00

Formatting Time with Timezone


Formatting becomes easier with the strftime() method of the datetime object.
Example
import pytz

from datetime import datetime

# Create a timezone object for US/Eastern

eastern_tz = pytz.timezone('US/Eastern')

now = datetime.now()

now_eastern = eastern_tz.localize(now)

# Add formatting

fmt = '%Y-%m-%d %H:%M:%S %Z%z'

now_str = now_eastern.strftime(fmt)

print(now_str)

Output
2023-04-17 16:59:06 EDT-0400

Import required libraries:

For various data processing cases in NLP, we need to import some libraries. In this case, we
are going to use NLTK for Natural Language Processing. We will use it to perform various
operations on the text.

Figure 13:
Importing the required libraries.
c. Sentence tokenizing:

By tokenizing the text with sent_tokenize( ), we can get the text as sentences.


tokenize the text as sentences.

Plot the frequency graph:

Let’s plot a graph to visualize the word distribution in our text.

Remove

punctuation marks:
Next, we are going to remove the punctuation marks as they are not very useful for us. We
are going to use isalpha( ) method to separate the punctuation marks from the actual text.
Also, we are going to make a new list called words_no_punc, which will store the words in
lower case but exclude the punctuation marks.

You might also like