Python [Post 07] | Tuple

A tuple is a collection which is ordered and unchangeable. It is similar to list, but a tuple is immutable unlike lists which are mutable.

It is created by placing items inside a parentheses (), separated by comma. Parentheses is optional.

# Creating Tuple

empty_tuple = ()
my_tup1 = 'N','S','E','W'
my_tup2 = ('North','South','East','West')

print(type(empty_tuple))
print(my_tup1)
print(my_tup2)

<class ‘tuple’>
(‘N’, ‘S’, ‘E’, ‘W’)
(‘North’, ‘South’, ‘East’, ‘West’)

Other way to create tuple by using the tuple() constructor. See below example.

my_tup3 = tuple((1,'South',5.5,('A','B','C'),[0,1,2]))

print(my_tup3)
print(type(my_tup3))

(1, ‘South’, 5.5, (‘A’, ‘B’, ‘C’), [0, 1, 2])
<class ‘tuple’>

# Creating a tuple having single value

my_tup4 = (4)
print(type(my_tup4)) # But the result is showing int, i.e. this is not a tuple

<class ‘int’>

To create a tuple having single value, Just include comma at last.

my_tup4 = (4,)
print(type(my_tup4)) # Now its a tuple

<class ‘tuple’>

Some Built-in Python Functions

my_tup5 = 1,2.5,3,4

print(type(my_tup5)) # Type
print(len(my_tup5)) # len Function - Gives the total length of the tuple.
print(max(my_tup5)) # max Function - Returns element from the tuple with maximum value.
print(min(my_tup5)) # min Function - Returns element from the tuple with minimum value.

<class ‘tuple’>
4
4
1

### Accessing Tuple Values – Indexing & Slicing

Use the index operator [] to access an item in a tuple. We can use a : to perform slicing which extracts chunk of more than one element as per input. In slicing last index is not included.

sides = 'East','West','North','South'
# Fetch the first element of list sides

print(sides[0])

East

# Fetch the last element of list sides

print(sides[-1])

South

# fetch elements start from index 1st till last

print(sides[1:])

(‘West’, ‘North’, ‘South’)

# fetch elements upto 2nd index, but 2nd is not included

print(sides [:2])

(‘East’, ‘West’)

# fetch element from 1st index to 3rd index

print(sides [1:3])

(‘West’, ‘North’)

# fetching values in case of nested tuple

my_tup = tuple((1,'South',5.5,('A','B','C'),[0,1,2]))

print(my_tup[3][0])
print(my_tup[3][2])

A
C

### Updating Tuples

Python Tuple is immutable i.e. the elements inside a tuple cannot be changed!

sides = ('East','West','North','South')

# Let's try to change the elements of lists sides

sides[0]= 1

TypeError Traceback (most recent call last)
<ipython-input-14-b1dd30231e62> in <module>()
3 # Let’s try to change the elements of lists sides
4
—-> 5 sides[0]= 1
TypeError: ‘tuple’ object does not support item assignment

### Deleting Tuples

Individual element in tuple cannot be removed. Entire tuple can be removed by using del statement.

# Removing tuple completely

del sides
sides # This will raise exception, as sides tuple removed

NameError Traceback (most recent call last)
<ipython-input-16-7623a01b7793> in <module>()
—-> 1 sides # This will raise exception, as sides tuple removed
NameError: name ‘sides’ is not defined

### Concatenation & Repetition of Tuples

sides = ('East','West','North','South')
modesides = ('North-East','North-East','South-East','South-West')

print(sides)
print(modesides)

(‘East’, ‘West’, ‘North’, ‘South’)
(‘North-East’, ‘North-East’, ‘South-East’, ‘South-West’)

# Concatenation

sides = sides + modesides
print(sides)

(‘East’, ‘West’, ‘North’, ‘South’, ‘North-East’, ‘North-East’, ‘South-East’, ‘South-West’)

# Repetition

sides = sides * 2
print(sides)

(‘East’, ‘West’, ‘North’, ‘South’, ‘North-East’, ‘North-East’, ‘South-East’, ‘South-West’, ‘East’, ‘West’, ‘North’, ‘South’, ‘North-East’, ‘North-East’, ‘South-East’, ‘South-West’)

### Tuple Method

Python includes following tuple methods.

Index() :

Returns the index of the first matched item.

sides = 'EAST','West','North','East','South','East'

print(sides.index('East'))
print(sides.index('West'))

3
1

Count():

Returns the count of number of items passed as an argument.

print(sides.count('East'))

2


Thanks!

Happy Learning! Your feedback would be appreciated!

shobhitsingh.in
Github Code Link

Advertisements

Python [Post 06] | Dictionary

Python dictionary is an un-ordered collection of items. It consists of a key value pairs.

  • Python dictionary is un-ordered & cannot be sorted.
  • Value can be almost any Python object.
  • Value can be accessed by unique key in the dictionary.
  • Keys must be of an immutable data type. Example – strings, numbers or tuples.

Creating a dictionary is as simple as placing items inside curly braces {} separated by comma. An item has a key and the corresponding value expressed as a pair, key: value.

{‘key1′:’value1′,’key2′:’value2’}

# Examples of Python Dictionary:

# Dictionary having string keys & string value
my_dict0 = { "N": "North", "S": "South", "E": "East", "W": "West" }

# Dictionary having integer keys & string value
my_dict1 = { 1: 'North', 2: 'South', 3: 'East', 4: 'West'}

# Dictionary having string keys & integer value
my_dict2 = { 'North' : 1, 'South': 2, 'East': 3,'West':4}

# Dictionary having mixed keys & values
my_dict3 = { 'N' : 'North', 2: 'South', 'East': 3,'West':'W', "ComplexNumber":5+500j, 5.5:[1,2,3,4]}

# Nested Dictionary
my_dict4 = { 'Aphabets' : { 'A':{'Fruit':'Apple','Object':'Aeroplane'},'B':{'Fruit':'Banana','Object':'Ball'}} ,
'Numbers' : { 0: 'Zero', 1:'One', 2:'Two', 3:'Three', 4:'Four', 5:'Five', 6:'Six', 7:'Seven'}
}
print(my_dict0)
print(my_dict1)
print(my_dict2)
print(my_dict3)
print(my_dict4)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}
{1: ‘North’, 2: ‘South’, 3: ‘East’, 4: ‘West’}
{‘North’: 1, ‘South’: 2, ‘East’: 3, ‘West’: 4}
{‘N’: ‘North’, 2: ‘South’, ‘East’: 3, ‘West’: ‘W’, ‘ComplexNumber’: (5+500j), 5.5: [1, 2, 3, 4]}
{‘Aphabets’: {‘A’: {‘Fruit’: ‘Apple’, ‘Object’: ‘Aeroplane’}, ‘B’: {‘Fruit’: ‘Banana’, ‘Object’: ‘Ball’}}, ‘Numbers’: {0: ‘Zero’, 1: ‘One’, 2: ‘Two’, 3: ‘Three’, 4: ‘Four’, 5: ‘Five’, 6: ‘Six’, 7: ‘Seven’}}

Other way to create dictionary to use the dict() constructor to make a dictionary:

sides = dict(N="North", S="South", E="East",W="West")
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}

Access elements from a dictionary

# Fetching dictionary values by key

print(sides['N'])
print(sides.get('S'))

North
South

# Nested Dictionary
my_dict = { 'Aphabets' : { 'A':{'Fruit':'Apple','Object':'Aeroplane'},'B':{'Fruit':'Banana','Object':'Ball'}} ,
'Numbers' : { 0: 'Zero', 1:'One', 2:'Two', 3:'Three', 4:'Four', 5:'Five', 6:'Six', 7:'Seven'}
}

smy_dict['Aphabets']['A']['Object']

‘Aeroplane’

my_dict4['Numbers'][5]

‘Five’

In Python dictionary no duplicate key is allowed.

# Creating a dictionary having duplicate keys

sides ={ "N": "East", "S": "South", "N": "West", "N": "North" }
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’}

When duplicate keys found during dictionary creation, the last assignment is final one. See above example.

### Updating Dictionary

Adding a new key-value pair, modifying an existing key-value pair, or deleting an existing key-value pair.

# Creating a new dictionary

sides = dict(N="North", S="South", E="East",W="West")
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}

Adding a new key:value pairs to existing dictionary

sides['NE'] = 'North-East'
sides['NW'] = 'North-West'
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North-East’, ‘NW’: ‘North-West’}

Updating key:value pair

sides['NE'] = 'North East'
sides['NW'] = 'North West'
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North East’, ‘NW’: ‘North West’}

sides['NE']

‘North East’

Deleting an existing key:value pair

print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North East’, ‘NW’: ‘North West’}

del sides ['N'] # Remove the provided Key
print(sides)

{‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North East’, ‘NW’: ‘North West’}

del sides ; # delete dictionary completely

### Dictionary Methods

Python Dictionary provides so many methods. See below some examples

sides = dict(N="North", S="South", E="East",W="West")
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}

Get()

It return Value for Key.

print(sides.get('S'))

South

Items(), Keys () & Value()

Item – It return the list with all dictionary keys with values.
Keys – It return list of dictionary dict’s keys.
Value – It returns list of dictionary dict’s values.

print(sides.items())
print(sides.keys())
print(sides.values())

dict_items([(‘N’, ‘North’), (‘S’, ‘South’), (‘E’, ‘East’), (‘W’, ‘West’)])
dict_keys([‘N’, ‘S’, ‘E’, ‘W’])
dict_values([‘North’, ‘South’, ‘East’, ‘West’])

Copy()

It creates the copy of the dictionary into other dictionary.

new_sides = {}
new_sides = sides.copy()
print(new_sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}

Update()

Adds dictionary key-values pairs to another dictionary.

sides = dict(N="North", S="South", E="East",W="West")
some_more_sides = dict(NE="North-East", SE="South-East")

print(sides)
print(some_more_sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’}
{‘NE’: ‘North-East’, ‘SE’: ‘South-East’}

sides.update(some_more_sides)
print(sides)

{‘N’: ‘North’, ‘S’: ‘South’, ‘E’: ‘East’, ‘W’: ‘West’, ‘NE’: ‘North-East’, ‘SE’: ‘South-East’}

Clear()

Removes all elements of dictionary.

some_more_sides.clear(); # Remove all entries in dictionary
print(some_more_sides)

{}


Thanks!

Happy Learning! Your feedback would be appreciated!

shobhitsingh.in

Github Code Link

Python [Post 03] | Numbers

Folks,
In this blog we will explore different Python numeric types, arithmetic operations, mathematical fuctions, variable assignment & number conversion.

For Python Overview & Basic – Refer this Blog Post

Python has mainly three diffrent of numeric types.

  • int
  • float
  • complex

Integers (int)


Int/Integer, is basically a whole number (+ve or -ve), without decimals & of unlimited length.

Example of Integers: -5, 500, 20001543646546231654646465465454544545454554

 

# Integer Example 1
print(-5)
type(5)

-5
int

# Integer Example 2
print(500)
type(500)

500
int

# Integer Example 3
print(20001543646546231654646465465454544545454554)
type(20001543646546231654646465465454544545454554)

20001543646546231654646465465454544545454554
int

Float


Floating point numbers is a number, (+ve or -ve), represent real numbers and they have a decimal points in them, or use an exponential (e) to define the number.

Exampe of Floats: -5.5 , 500.5, 5E2

5E2 (5 times 10 to the power of 2) is also an example of a floating point number in Python.

# Float Example 1
print(-5.5)
type(-5.5)

-5.5
float

# Float Example 2
print(500.5)
type(500.5)

500.5
float

# Float Example 3
print(5E2)
type(5E2)

500.0
float

Complex Number


Numbers in the form of (a + bj), where a and b are floats and j represents the square root of -1. Real part of the number is a, and the imaginary part is b.

Exampe of Complex Number: 5+500j

# Complex Example 1
5+500j

(5+500j)

type(5+500j)

complex

Artithmetic Operations


# Additon of numbers
5+5

10

# Substraction of numbers
10-5

5

# Multiplication of numbers
10*5

50

# Division of nuumbers
10/5

2.0

# Floor Divison (// operator truncates the decimal without rounding)
10//4

2

# Exponent
5**2

25

# Modulus (% operator returns the remainder after division)
5%2

1

Mathematical Fuctions


Python also have some functions that perform mathematical calculations

# importing "math" for mathematical operations
import math
# Ceil Function
print (math.ceil(5.6))

6

# Floor Function
print (math.floor(5.6))

5

# Exponential Function
print (math.exp(5))

148.4131591025766

# Square Root Function
print (math.sqrt(16))

4.0

# Factorial Function
print (math.factorial(5))

120

# Absolute Function - Positive Number
print(abs(-5))

5

# Round Function - Number rounded to n digits from the decimal point
print(round(5.56))

# Round Function with 2nd argument for how many digits to round
print(round(5.56,1))

6
5.6

# Minimun Function - Finds smallest of its arguments
print (min(5,10,2,22))

2

# Mamimun Function - Finds largest of its arguments
print (min(5,10,2,22))

2

Variable Assignemnt


# Create an object/Variable called "length" and assign it the number 50
length = 50
print(length)

50

# Reassignment - Overrites value
length = 10
print(length)

10

length = 10
width = 5.6
height = 10.6

print(length * width * height)

593.6

Numerical Type Conversion


# Example 1:
height = 10.6
type(height)

float

# Let's convert this variable into int
height= int(height)
print(height)
type(height)

10
int

# Example 1:
length = 10
type(length)

int

# Let's convert this variable into foat
length= float(length)
print(length)
type(length)

10.0
float


Thanks!

Happy Learning! Your feedback would be appreciated!

shobhitsingh.in
Guthub Code

Python [Post 02] | Variables

In Python a variable is created when we assign value to it. It does not required any explicit declaration. Use the assignment operator = to assign the value to a variable.

Variable Names Rules

  • Must start with a letter or the underscore character. Cannot start with a number.
  • Can only contain alpha-numeric characters and underscores (A-z, 0-9, & _ ).
  • Variable names are case-sensitive.
  • Avoid using Python Built-keywords. Like str, type, list etc.
#Example:

name = "John" # String Variable Assignment
age = 50 # Integer Variable Assignment
height = 150.50 # Float Variable Assignment

Using Python’s built-in function type() you can check what type of object is assigned to a variable.

Here are the list of Python data type:

  • int
  • float
  • str
  • list
  • tuple
  • dict
  • set
  • bool
# Exapmple

type(name)

str

## Dynamic Typing

In Python you can reassign variables to different data types. Python is very flexible in assigning data types.

# Example, Here Integer Assignment

x=50
type(x)

int

x="Hello, World!" # Re-assigned X Now String Assignment
type(x)

str

x=12.20+4j # Re-assigned X Now String Assignment
type(x)

complex

x=(1,2,3,4,5) # Re-assigned X Now Tuple Assignment
type(x)

tuple

## Re-assigning Variables

Python allow you to reassign variables with a reference to the same object.

a=50
print(a)

50

a = a + a
print(a)

100

a += 50
print(a)

150

a -= 10
print(a)

140

a *= 2
print(a)

280

a /= 5
print(a)

56.0

# Multiple Assignment

Python allows you to assign a value to multiple variables simultaneously.

# Example 1

length = width = height = 50
print (length)
print (width)
print (height)

50
50
50

# Example 2

length, width, height = (10,50,60)
print (length)
print (width)
print (height)

10
50
60


Thanks!

Happy Learning! Your feedback would be appreciated!

shobhitsingh.in

GitHub Code

How to send email using Python.

How to send email using Python.

Folks,

In this blog we will explore how send email to single/multiple email id using python Script.


Python Script: See detailed comments in the Python Script.


# import the smtplib module.
import smtplib

# from user details
from_user_email_id =  [provide_your_email_id_here]
from_user_email_pwd = [provide_your_email_id_password]

# Email Subject
email_subject = [provide_your_email_subject]

# To user email ids
to_user_email_id = [provide_list_of_to_email_ids_comma_seperated]

# set up the SMTP server
s = smtplib.SMTP(host=[provide_smtp_host_address_here], port=[provide_smtp_port_here]])
s.ehlo()
s.starttls()
s.ehlo

# login the SMTP server using from email id and password.
s.login(from_user_email_id, from_user_email_pwd)

# Preparing email message header and body.
email_header = 'To:' + ", ".join(to_user_email_id)  + '\n' + 'From: ' + from_user_email_id + '\n' + 'Subject: ' +  email_subject + '  \n'
email_body = email_header + [provide_here_email_text]

# sending email
s.sendmail(from_user_email_id, to_user_email_id, email_body)

s.close()

 

After providing all the required information & save your fileĀ  in .py extension. Refer below example.

email

Execute Script:

execute

Result:

email4


Thanks!

Happy Learning! Your feedback would be appreciated!