0% found this document useful (0 votes)
4 views18 pages

Python Variable Declaration Guide

The document provides an introduction to Python programming, covering variable declaration, data types, conditional statements, arithmetic operations, control flow, functions, and collections such as lists, tuples, sets, and dictionaries. It includes examples of basic operations and manipulations, illustrating how to work with different data structures and perform numerical calculations. The content is structured as a Jupyter notebook, suitable for educational purposes.

Uploaded by

Dhivyabharathi A
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views18 pages

Python Variable Declaration Guide

The document provides an introduction to Python programming, covering variable declaration, data types, conditional statements, arithmetic operations, control flow, functions, and collections such as lists, tuples, sets, and dictionaries. It includes examples of basic operations and manipulations, illustrating how to work with different data structures and perform numerical calculations. The content is structured as a Jupyter notebook, suitable for educational purposes.

Uploaded by

Dhivyabharathi A
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction_to_Python.ipynb - Colab [Link]

 Declaring Variables

variable types supported:

1. int : integers
2. �oat : �oating point numbers
3. bool : Boolean types (True and False)
4. str : Textual data

var1 = 2 #integer
var2 = 3.7 #floating point number
var3 = True #boolean
var4 = "Python" #string

print("Value of var1= ",var1)


print("Value of var2= ",var2)
print("Value of var3= ",var3)
print("Value of var4= ",var4)

Value of var1= 2
Value of var2= 3.7
Value of var3= True
Value of var4= Python

type(var1)

int

type(var2)

float

type(var3)

bool

type(var4)

str

num=input("Enter a number")
#num=int(input("Enter a number: "))

Enter a number5

type(num)

1 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

type(num)

str

 Conditional Statements

# Checking a condition if the variable value is more than 1


if var1 > 1:
print( "Bigger than 1" )

Bigger than 1

x = 10
y = 12
# if x is greater than y
if x > y:
print ("x > y")
# if x is lesser than y
elif x < y:
print ("x < y")
else:
print ("x = y")

# Initialize
x = 20
# Assign True if x is more than 10 or assign False using ternary operator
isGreater = True if x > 10 else False

isGreater

True

 Arithmetic Operations

# Store a number
x = 1
y = 2
n = 3
p = 9
q = 4

# Add two stored numbers


addition = x + y
print("x + y =", addition)

# Multiply two numbers


multiplication = x * y
print("x * y =", multiplication)

2 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

print("x * y =", multiplication)

# Get nth power of y


power = y ** n
print("y ** n =", power)

# Convert an integer to float


float_x = float(x)
print("float(x) =", float_x)

# Get integer division of integers p and q


int_division = p / q
print("p / q =", int_division)

# Get fractional division of integers p and q


frac_division = float(p) / q
print("float(p) / q =", frac_division)

m=p//q #quotient
print(m)

m2=p%q #remainder
print(m2)

x + y = 3
x * y = 2
y ** n = 8
float(x) = 1.0
p / q = 2.25
float(p) / q = 2.25
2
1

 Generating Sequence Numbers

# Initializing the sequence of numbers starting from 1 and ending (not including) with
numbers = range( 1, 6 )
type(numbers)

range

 Control Flow Statements

# Iterate through the collection


for i in numbers:
print (i)

1
2
3
4

3 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

4
5

for j in range(1,10,2):
print(j)

1
3
5
7
9

# Initialize the value of 1


i = 1
# check the value of i to check if the loop will be continued or not
while i < 5:
print(i)
# Increment the value of i.
i = i+1
# print after the value of i
print('Done')

while i < 5:
print(i)
i=i+1
print("Done")

1
2
3
4
Done

 Numerical Manipulations

#Get integers from 0 to n-1:range(n)


print(list(range(5)))

#Get integers from p to q-1: range(p,q,step)


print(list(range(0,11,2)))

#Generate a set of integers using the range() command


#print(list(range(m,n,k)))
#generates integers from m to n-1 in intervals of k

print(list(range(2,10,2))) #generates what?


print(list(range(10,2,-2))) # ?
print(list(range(-10,-1,2)))
print(list(range(2*3)))

4 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

print range

 Functions

def addElements( a, b ):
return a + b

result = addElements( 2.3, 4.5 )


result

6.8

result = addElements( "python", "demonstration" )


result

'pythondemonstration'

def addElements( a, b = 4 ):
return a + b

addElements(2)

addElements( 2, 5 )

Collections:

 Lists

It can contain words as well as numbers. A list is mutable, which means that it can be altered
by adding or removing elements to and from the list.

## Create an empty list


emptyList = []

batsmen = ['Rohit', 'Dhawan', 'Kohli', 'Rahane', 'Rayudu', 'Dhoni']

batsmen[0]

'Rohit'

5 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

#slicing
batsmen[0:2]

['Rohit', 'Dhawan']

##accessing last element


batsmen[-1]

'Dhoni'

#how many elements in the list


len(batsmen)

bowlers = ['Bumrah', 'Shami', 'Bhuvi', 'Kuldeep', 'Chahal']

all_players=batsmen + bowlers

all_players

['Rohit',
'Dhawan',
'Kohli',
'Rahane',
'Rayudu',
'Dhoni',
'Bumrah',
'Shami',
'Bhuvi',
'Kuldeep',
'Chahal']

'Bumrah' in bowlers

True

'Kohli' in bowlers

False

#finding the index of an item in the list


all_players.index('Dhoni')

all_players.reverse()

all_players

6 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

all_players

['Chahal',
'Kuldeep',
'Bhuvi',
'Shami',
'Bumrah',
'Dhoni',
'Rayudu',
'Rahane',
'Kohli',
'Dhawan',
'Rohit']

 List Comprehension

#Creating a new list from an existing list


L1=[1,2,3,4,5]
L2=[i**2 for i in L1] #loop within a list to generate a new list of square of numbers

L2

[1, 4, 9, 16, 25]

#Detailed explanation
L1=[1,2,3,4,5]
L2=[]

for i in L1:
[Link](i**2)

L2

[1, 4, 9, 16, 25]

from math import *


theta=[0,pi/2,pi,3*pi/2,2*pi] #lists
L3=[sin(x) for x in theta] #generates list of sin values for each entry in the theta l

L3

[0.0, 1.0, 1.2246467991473532e-16, -1.0, -2.4492935982947064e-16]

#Logical structures inside lists


L4=[n**2 for n in L1 if n<=10] #generates squares of numbers in L1 upto the speci
print(L4)

#L4=[]
#for i in L1:
# if i<=10:
# [Link](i**2)

7 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

# [Link](i**2)
#L4

[1, 4, 9, 16, 25]

#Creating a list of pairs of numbers from two lists


L5=[1,2,3]
L6=[4,5,6]
L7=[(i,j) for i in L5 for j in L6] #generates the list of pairs [(1,4),(1,5),.....]

L7

#L7=[]
#for i in L5:
# for j in L6:
# [Link]((i,j))

#L7

[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

#Sum of integers without for loop


n = int(input("Enter the value of n: n= "))
x=range(1,n+1)
print(sum(x))

#alternate
#print(sum(range(1,n+1)))

Enter the value of n: n= 10


55

 Tuples

A tuple is an immutable list, i.e., it cannot be changed...elements cannot be inserted or


deleted from a tuple.

odiDebut = ( 'Kohli', 2008 )

odiDebut

('Kohli', 2008)

odiDebut[0]

'Kohli'

tup1[1] = 2009

8 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

---------------------------------------------------------------------------
NameError Traceback (most recent call
last)
/tmp/[Link] in <cell line: 0>()
----> 1 tup1[1] = 2009

NameError: name 'tup1' is not defined

players = tuple( all_players )

players

('Chahal',
'Kuldeep',
'Bhuvi',
'Shami',
'Bumrah',
'Dhoni',
'Rayudu',
'Rahane',
'Kohli',
'Dhawan',
'Rohit')

 Set

A set is an unordered (indexing has no meaning) collection of unique elements (without


duplicates) de�ned with curly brackets {}.

setOfNumbers = {6,1,1,2,4,5}

setOfNumbers

{1, 2, 4, 5, 6}

wc2011 = {"Dhoni", "Sehwag", "Tendulkar", "Gambhir", "Kohli", "Raina", "Yuvraj"


wc2015 = {"Dhoni", "Dhawan", "Rohit", "Rahane", "Kohli", "Raina", "Rayudu", "Jadeja"

[Link]( wc2015 )

{'Dhawan',
'Dhoni',
'Gambhir',
'Jadeja',
'Kohli',
'Rahane',

9 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

'Rahane',
'Raina',
'Rayudu',
'Rohit',
'Sehwag',
'Tendulkar',
'Yusuf',
'Yuvraj'}

[Link]( wc2015 )

{'Dhoni', 'Kohli', 'Raina'}

[Link]( wc2011 )

{'Dhawan', 'Jadeja', 'Rahane', 'Rayudu', 'Rohit'}

 Dictionary

An unordered collection of items. Each item has a key, value pair. It is unordered, changeable
and indexed.

wcWinners = { 1975:"West Indies",1979:"West Indies",1983:"India",1987:"Australia"

wcWinners[1983]

'India'

[Link]()

dict_values(['West Indies', 'West Indies', 'India', 'Australia',


'Pakistan', 'Srilanka', 'Australia', 'Australia', 'Australia', 'India',
'Australia', 'England'])

set([Link]())

{'Australia', 'England', 'India', 'Pakistan', 'Srilanka', 'West Indies'}

wcWinners[2023]='Australia'

wcWinners

{1975: 'West Indies',


1979: 'West Indies',
1983: 'India',
1987: 'Australia',
1991: 'Pakistan',
1996: 'Srilanka',

10 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

1996: 'Srilanka',
1999: 'Australia',
2003: 'Australia',
2007: 'Australia',
2011: 'India',
2015: 'Australia',
2019: 'England',
2023: 'Australia'}

 Strings

string0 = 'python'
string1 = "machine learning"

string2 = """This is a
multiline string"""

# Converting to upper case


X=[Link]()
print(X)

PYTHON

# Similarly [Link]() can be used to convert to lower case.


[Link]()

'python'

tokens = [Link](' ')


tokens

['machine', 'learning']

#n-th item in list: string0[n-1]


print(string0[0])

#n-th item from the end


print(string1[-1])

p
g

#m-th to n-th items in list:string0[m-1:n]


print(string0[0:3])

#m-th to n-th items from the end: string01[-m:-(n+1):-1]

pyt

11 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

str1='firefox is the name of the mozilla browser'

#Task: verify if the word mozilla is in the above string using 'find' command
result1=[Link]('mozilla')
print(result1)

result2=[Link]('tiger')
print(result2)

27
-1

 Functional Programming

Example 1: Map

intList = [1,2,3,4,5,6,7,8,9]

# Create an empty list.


squareList = []
# Loop through the intList, square every item and append to result list squareList.
for x in intList:
[Link](pow( x, 2 ))

print(squareList)

[1, 4, 9, 16, 25, 36, 49, 64, 81]

def square_me(x):
return x * x

for i in range(1,5):
y=square_me(i)
print(y)

12 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

1
4
9
16

squareList = map(square_me, intList)

type(squareList)

map

list(squareList)

[1, 4, 9, 16, 25, 36, 49, 64, 81]

squareList = map(lambda x: x*x, intList)


list(squareList)

[1, 4, 9, 16, 25, 36, 49, 64, 81]

Example 2: Filter

evenInts = filter( lambda x : x % 2 == 0, intList )

list(evenInts)

[2, 4, 6, 8]

 Modules and Packages

import math

#square root of a number


[Link](144)

from random import sample

sample( range(0, 11), 3)

[1, 8, 6]

import random
randomList = [Link]( range(0, 100), 20)
randomList

[51, 70, 67, 89, 24, 68, 63, 88, 42, 1, 31, 19, 40, 59, 76, 90, 93, 56,
96, 18]

13 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

96, 18]

from statistics import mean, median

def demo_mean_med( listNum ):


return mean(listNum), median(listNum)

mean, median = demo_mean_med( randomList )

print( "Mean: ", mean, " Median: ", median)

Mean: 57.05 Median: 61.0

 Error and exceptions handling

Errors: the mistakes or faults that cause program to behave unexpectedly

• Syntax error
• Semantic or logical error
• Errors due to exceptional cases

#Syntax error (symptomatic)


#due to violation of language syntax.....immediate termination
name = input("Enter your name: ")
age = int(input("Enter your age: "))
if age < 0 #invalid syntax
print("You have entered a negative age")

#Semantic or logical errors (symptomatic or asymptomatic)


'''due to an improper use of program statements
some / all part of the code will execute with an erroneous output.'''

r = input("Enter the radius of a circle: ")


c = 2 * 3.1415 * r
print("Circumference of the circle: ", c)

num1 = input('Enter first number:')


num2 = input('Enter second number:')
sum = num1 + num2
print('The sum of', num1, 'and', num2, 'is', sum)

#Exceptions: when program is syntactically correct but code resulted in an error due t

num1 = int(input('Enter first number:'))


num2 = int(input('Enter second number:'))
q = num1 / num2
print(num1, '/', num2, '=', q)

14 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

print(num1, '/', num2, '=', q)

#ZeroDivisonError: divison by zero

#occurrence of an Exception - an unexpected event occurred in between execution of the

#trying to access beyond list limits


lst=[1,2,3,4]
print(lst[4])

#trying to convert an inappropriate type


a=int(lst)

#referencing a non-existing variable


print(x)

#mixing data types without type casting


quotient='10'//2

 Other exceptions

NameError: variable not found

AttributeError: attribute reference fails

TypeError: operand doesn’t have correct type

ValueError: operand type okay, but value is illegal

IOError: IO system reports malfunction (e.g. �le not found)

• Exceptions can be handled using a statement.


• The critical operation that can raise an exception is placed inside the clause.
• The code that handles the exceptions is written in the *except *clause.
• We can thus choose what operations to perform once we have the exception.

try:
#statements from which exceptions can rise
except:
#codes to handle the exception

try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("a/b = ", a/b)
except:
print("There is some error in the input.")

15 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

print "There is some error in the input."


print("Done")

#Better solution

try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("a/b = ", a/b)
except Exception as e:
print("There is some error in the input.")
print(e)
print("Done")

#Exception : keyword generalized for all exceptions.

#Catching specific exceptions

try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("a/b = ", a/b)
except ValueError:
print("Could not convert to a number.")
except ZeroDivisionError:
print("Can't divide by zero")
except:
print("Something went wrong.")
print("Done")

try:
# do something
except ValueError:
# handle ValueError exception
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
# TypeError and ZeroDivisionError
except:
# handle all other exceptions

#Only one will be executed in case an exception occurs

#Throwing an exception explicitly

try:
num = int(input("Enter an even number: "))
if num % 2 != 0:
raise ValueError("That is not a positive number!")
except ValueError as ve:
print(ve)
print('Done')

16 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

# program to print the reciprocal of even numbers


try:
num = int(input("Enter an even number: "))
if num % 2 != 0:
raise Exception()
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)

try:
# statements from which exceptions can rise
except:
# exception handling
else:
# this will execute only if there is no exception raised
finally:
# this will always execute after try and / or catch

def recip(num):
try:
if num % 2 != 0:
raise Exception()
except:
print("Not an even number!")
return
else:
reciprocal = 1/num
print(reciprocal)
finally:
print("finally cleaning")
print("All went smoothly")

Surround section of code potentially dangerous with :.

If the code in works - code in skipped

If the code in fails - execution jumps to block.

If the code in runs smoothly - execution jumps to block.

block always executed after completion of block, block or block.

block - to keep a block of code with the risk of having exceptional cases.

block - to handle the errors / exceptional cases.

block - to clean up.

17 of 18 29/07/25, 22:20
Introduction_to_Python.ipynb - Colab [Link]

18 of 18 29/07/25, 22:20

You might also like