Python Module 2
Python Module 2
Module II
Building Python Programs: Data types, variables, operators. Control statements – branching
controls, simple if, if - else, if - elif -else; looping, while, for. Functions - defining, calling,
returning values, functions with default arguments, recursive functions, nested functions and
lamda functions. Strings - operation, string functions. Work with dates and times. (10 HRS)
x = "Hello World"
Data types
# DataType Output: int
Data types are the classification or categorization of data items. It represents the kind of value
x = 50
that tells what operations can be performed on a particular data. Since everything is an object
# DataType Output: float
in Python programming, data types are actually classes and variables are instances (object)
of these classes. The following are the standard or built-in data types in Python: x = 60.5
x = True
# Creating a String
x = memoryview(bytes( 6 ))
# with single Quotes
# DataType Output: NoneType
String1 = 'Welcome to the Geeks World'
x = None
print ( "String with the use of Single Quotes: " )
# Creating a String
The numeric data type in Python represents the data that has a numeric value. A numeric
# with double Quotes
value can be an integer, a floating number, or even a complex number. These values are
defined as Python int, Python float, and Python complex classes in Python. String1 = "I'm a Geek"
Complex Numbers – Complex number is represented by a complex class. It is specified print ( type (String1))
as (real part) + (imaginary part)j. For example – 2+3j # Creating String with triple
Python Tuple
String with the use of Single Quotes:
String Data Type Welcome to the Geeks World
Strings in Python are arrays of bytes representing Unicode characters. A string is a collection String with the use of Double Quotes:
I'm a Geek
of one or more characters put in a single quote, double-quote, or triple-quote. In python there
<class 'str'>
is no character data type, a character is a string of length one. It is represented by str class.
String with the use of Triple Quotes:
print ( List )
Accessing elements of String
# Creating a List with
In Python, individual characters of a String can be accessed by using the method of # the use of a String
Indexing. Negative Indexing allows negative address references to access characters from
List = [ 'GeeksForGeeks' ]
the back of the String, e.g. -1 refers to the last character, -2 refers to the second last character,
print ( "\nList with the use of String: " )
and so on.
print ( List )
Python3 # Creating a List with
# Python Program to Access # the use of multiple values
# characters of String
List = [ "Geeks" , "For" , "Geeks" ]
String1 = "GeeksForGeeks" print ( "\nList containing multiple values: " )
print ( "Initial String: " ) print ( List [ 0 ])
print (String1) print ( List [ 2 ])
# Printing First character # Creating a Multi-Dimensional List
print ( "\nFirst character of String is: " ) # (By Nesting a list inside a List)
print (String1[ 0 ])
List = [[ 'Geeks' , 'For' ], [ 'Geeks' ]]
# Printing Last character
print ( "\nMulti-Dimensional List: " )
print ( "\nLast character of String is: " )
print ( List )
print (String1[ - 1 ])
Output:
Output:
Multi-Dimensional List:
List Data Type [['Geeks', 'For'], ['Geeks']]
Lists are just like arrays, declared in other languages which is an ordered collection of data. It
is very flexible as the items in a list do not need to be of the same type. Python Access List Items
# list using index number print ( "\nTuple with the use of String: " )
# Creating a Tuple
Just like a list, a tuple is also an ordered collection of Python objects. The only difference
Output:
between a tuple and a list is that tuples are immutable i.e. tuples cannot be modified after it is
created. It is represented by a tuple class.
Initial empty Tuple:
Creating a Tuple ()
Tuple with nested tuples: Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will
((0, 1, 2, 3), ('python', 'geek'))
throw an error.
Python3
Note – The creation of a Python tuple without the use of parentheses is known as Tuple
# Python program to demonstrate boolean type
Packing.
print(type(True))
Access Tuple Items
print ( type ( False ))
In order to access the tuple items refer to the index number. Use the index operator [ ] to
print (type(true)) #gives error
access an item in a tuple. The index must be an integer. Nested tuples are accessed using
nested indexing.
<class 'bool'>
Python3 <class 'bool'>
# Python program to
tuple1 = tuple ([ 1 , 2 , 3 , 4 , 5 ])
Set Data Type in Python
# Accessing element using indexing In Python, a Set is an unordered collection of data types that is iterable, mutable and has no
print ( "First element of tuple" ) duplicate elements. The order of elements in a set is undefined though it may consist of
print (tuple1[ 0 ]) various elements.
# Accessing element from last Create a Set in Python
# negative indexing
Sets can be created by using the built-in set() function with an iterable object or a sequence
print ( "\nLast element of tuple" )
by placing the sequence inside curly braces, separated by a ‘comma’. The type of elements in
print (tuple1[ - 1 ])
a set need not be the same, various mixed-up data type values can also be passed to the set.
print ( "\nThird last element of tuple" )
# Python program to demonstrate
print (tuple1[ - 3 ])
# Creation of Set in Python
set1 = set ()
First element of tuple print ( "Initial blank Set: " )
1
print (set1)
Last element of tuple # Creating a Set with
5
# the use of a String
Third last element of tuple
set1 = set ( "GeeksForGeeks" )
3
print ( "\nSet with the use of String: " )
set1 = set ([ "Geeks" , "For" , "Geeks" ]) print (i, end = " " )
print ( "\nSet with the use of List: " ) # Checking the element
True
Create a Dictionary
Dictionary Data Type in Python
In Python, a Dictionary can be created by placing a sequence of elements within curly {}
Access Set Items braces, separated by ‘comma’. Values in a dictionary can be of any datatype and can be
Set items cannot be accessed by referring to an index, since sets are unordered the items has duplicated, whereas keys can’t be repeated and must be immutable. The dictionary can also
no index. But you can loop through the set items using a for loop, or ask if a specified value be created by the built-in function dict(). An empty dictionary can be created by just placing
is present in a set, by using the in the keyword. it in curly braces{}. Note – Dictionary keys are case sensitive, the same name but different
cases of Key will be treated distinctly.
Python3
# Python program to demonstrate Python3
# Accessing of elements in a set # Creating an empty Dictionary
print ( Dict )
Output:
Empty Dictionary:
{}
In order to access the items of a dictionary refer to its key name. Key can be used inside
"Hi " + "there, " + "Ken!"
square brackets. There is also a method called get() that will also help in accessing the 'Hi there. Ken!'
element from a dictionary.
Python3
Comparison operators
" " * 10 + "Python"
‘ Python' Logical operators
Identity operators
Variables Membership operators
Variables are containers for storing data values.
Bitwise operators
Creating Variables Python Arithmetic Operators
Python has no command for declaring a variable. Arithmetic operators are used with numeric values to perform common mathematical
A variable is created the moment you first assign a value to it. Variables do not need to be operations:
declared with any particular type, and can even change type after they have been set.
x = 5
y = "John"
print(x)
print(y)
x = 4 # x is of type int
print(x)
If you want to specify the data type of a variable, this can be done with casting. Python Assignment Operators
y = int(3) # y will be 3
You can get the data type of a variable with the type() function.
Variable names are case-sensitive.
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Logical operators are used to combine conditional statements: Bitwise operators are used to compare (binary) numbers:
2. if-else statement:
The if-else statement is used to execute one block of code if a condition is true and
another block of code if the condition is false.
if condition:
# Code to execute if condition is true
else:
# Code to execute if condition is false
Example:
temperature = 25
if temperature > 30:
print("It's hot outside.")
else:
print("It's not very hot outside.")
#output:
#It's not very hot outside.
Control statements
Control statements in programming are used to control the flow of a program based on
3. if-elif-else statement:
certain conditions or to repeat a block of code multiple times. Two common types of control
The if-elif-else statement allows you to check multiple conditions in sequence and
statements are branching control (if statements) and looping control (while and for loops).
execute different code blocks based on which condition is true.
Let's go through each of these control statements with their syntax and simple example
programs.
if condition1:
1. Simple if statement: # Code to execute if condition1 is true
elif condition2:
The if statement is used to execute a block of code if a specified condition is true. If # Code to execute if condition2 is true
the condition is false, the code block is skipped. else:
# Code to execute if neither condition1 nor condition2 is true
if condition:
# Code to execute if condition is true Example:
Example: score = 85
if score >= 90:
print("You got an A.")
elif score >= 80:
age = 18
print("You got a B.")
if age >= 18:
else:
print("You are eligible to vote.")
print("You got a C or below.")
#output:
for item in sequence: 0
# Code to execute for each item in the sequence 1
2
Example:
In this example, when i is 3, the break statement terminates the loop.
def greet_with_default(name="Guest"):
Example: print(f"Hello, {name}!")
Example:
Nested Functions:
greet("Bob")
# Output: Hello, Bob!
You can define a function inside another function. These are called nested functions or inner
functions.
You can use the return statement to return a value from a function. The function can return
def outer_function(x):
one or more values. def inner_function(y):
return y * 2
Syntax: return inner_function(x)
result = outer_function(3)
def add(a, b): print(result) # Output: 6
return a + b
If you do not know how many arguments that will be passed into your function,
If you do not know how many keyword arguments that will be passed into your function,
def my_function(*kids):
print("The youngest child is " + kids[2]) def my_function(**kid):
print("His last name is " + kid["lname"])
my_function("Emil", "Tobias", "Linus")
#output:The youngest child is Linus my_function(fname = "Tobias", lname = "Refsnes")
These are arguments that are passed to a function using their parameter names. In the examples above, you can see how to use these argument types in Python functions.
They allow you to specify values for specific parameters of a function. For arbitrary arguments, we use *args to accept multiple positional arguments.
Example: For keyword arguments, we specify the parameter names when calling the function.
greet(name="Alice", age=30)
# Output: Hello, Alice! You are 30 years old.
Strings - operation, string functions.
str1 = "Hello"
2. str.strip() : Removes leading and trailing whitespace from a string.
str2 = "World"
result = str1 + " " + str2
print(result) # Output: Hello World text = " Python "
stripped_text = text.strip()
print(stripped_text) # Output: "Python"
2. Length: You can find the length of a string using the len() function.
3. str.split() : Splits a string into a list of substrings based on a delimiter.
text = "Python"
length = len(text)
print(length) # Output: 6 text = "apple,banana,cherry"
fruits = text.split(",")
print(fruits) # Output: ['apple', 'banana', 'cherry']
index = text.index("Python")
print(index) # Output: 0
name = "Alice"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message) # Output: My name is Alice and I am 30 years old. These are some of the common string operations and functions in Python. Strings are
versatile, and Python provides many built-in functions to manipulate and work with them
effectively.
Common String Functions:
1. str.upper() and str.lower() : These functions return the uppercase and lowercase