Python Lab File Example
Python Lab File Example
number = 10
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
if number > 0:
print('Positive number')
else:
print('Negative number')
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
total = 0
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!')
print('Outside function')
Run Code
Output
Hello World!
Outside function
When the function is called, the control of the program goes to the
function definition.
The control of the program jumps to the next statement after the function
call.
# Output: Sum: 9
Run Code
Output
# class attribute
name = ""
age = 0
# access attributes
print(f"{parrot1.name} is {parrot1.age} years old")
print(f"{parrot2.name} is {parrot2.age} years old")
Run Code
Output
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!!")
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...")
Output
Rendering Square...
Rendering Circle...
Output
In the above example, we have defined the class named Bike with two
attributes: name and gear .
print(result)
Output
<map 0x7fafc21ccb00>
{16, 1, 4, 9}
Passing Multiple Iterators to map() Using Lambda
num1 = [4, 5, 6]
num2 = [5, 6, 7]
print(list(result))
Run Code
Output
Numpy Constants
import numpy as np
radius = 2
circumference = 2 * np.pi * radius
print(circumference)
Output
12.566370614359172
Output:
import csv
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})
player_name,fide_rating
Magnus Carlsen,2870
Fabiano Caruana,2822
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")
data.columns =
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
data = pd.read_csv("employees.csv")
data.columns =
data.query('Senior_Management == 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]
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)
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.
# 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])
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
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
eastern_tz = pytz.timezone('US/Eastern')
now = datetime.now()
now_eastern = eastern_tz.localize(now)
# Add formatting
now_str = now_eastern.strftime(fmt)
print(now_str)
Output
2023-04-17 16:59:06 EDT-0400
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:
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.