0% found this document useful (0 votes)
21 views79 pages

Uml Lab Manul

The document is a lab manual for a Skill Enhancement Course on Python for B.Tech II Year students at Malineni Lakshmaiah Women’s Engineering College. It covers the history, features, and applications of Python, along with a detailed syllabus that includes various programming concepts, sample experiments, and installation instructions for Anaconda and Jupyter Notebook. The manual emphasizes practical programming skills through hands-on experiments related to data types, control flow, functions, and object-oriented programming.

Uploaded by

Dad's Princess
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views79 pages

Uml Lab Manul

The document is a lab manual for a Skill Enhancement Course on Python for B.Tech II Year students at Malineni Lakshmaiah Women’s Engineering College. It covers the history, features, and applications of Python, along with a detailed syllabus that includes various programming concepts, sample experiments, and installation instructions for Anaconda and Jupyter Notebook. The manual emphasizes practical programming skills through hands-on experiments related to data types, control flow, functions, and object-oriented programming.

Uploaded by

Dad's Princess
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 79

MALINENI LAKSHMAIAH WOMEN’S ENGINEERING COLLEGE

(Approved by AICTE NEW DELHI & Affiliated to JNTU KAKINADA)

AN ISO 9001:2008 Certified Institution


PULLADIGUNTA (V), VATTI CHERUKURU (M), GUNTUR DIST. A.P -522017

(AUTONOMOUS)

Department of Computer Science & Engineering


B.Tech II Year I Semester
Academic Year 2024-2025
Skill Enhancement Course [Python] Lab Manual
SEC Lab Syllabus
UNIT-1:
History of Python Programming Language, Thrust Areas of Python,
Installing Anaconda Python Distribution, Installing and Using Jupyter
Notebook. Parts of Python Programming Language: Identifiers, Keywords,
Statements and Expressions, Variables, Operators, Precedence and
Associativity, Data Types, Indentation, Comments, Reading Input, Print
Output, Type Conversions, the type () Function and Is Operator, Dynamic
and Strongly Typed Language. Control Flow Statements: if statement, if-
else statement, if...elif...else, Nested if statement, while Loop, for Loop,
continue and break Statements, Catching Exceptions Using try and except
Statement.
Sample Experiments:
1. Write a program to find the largest element among three Numbers.
2. Write a Program to display all prime numbers within an interval
3. Write a program to swap two numbers without using a temporary
variable.
4. Demonstrate the following Operators in Python with suitable examples.
i) Arithmetic Operators ii) Relational Operators iii) Assignment Operatorsiv)
Logical Operators v) Bit wise Operators vi) Ternary Operator vii)
Membership Operatorsviii) Identity Operators
5. Write a program to add and multiply complex numbers
6. Write a program to print multiplication table of a given number.

UNIT-2:

Functions: Built-In Functions, Commonly Used Modules, Function Definition and Calling the
function, return Statement and void Function, Scope and Lifetime of Variables, Default Parameters,
Keyword Arguments, *args and **kwargs, Command Line Arguments. Strings: Creating and
Storing Strings, Basic String Operations, Accessing Characters in String by Index Number, String
Slicing and Joining, String Methods, Formatting Strings. Lists: Creating Lists, Basic List
Operations, Indexing and Slicing in Lists, Built-In Functions Used on Lists, List Methods, del
Statement.

Sample Experiments:
1. Write a program to define a function with multiple return values.
2. Write a program to define a function using default arguments.
3. Write a program to find the length of the string without using any library functions.
4. Write a program to check if the substring is present in a given string or not.
5. Write a program to perform the given operations on a list:
i. addition ii. Insertion iii. slicing
6. Write a program to perform any 5 built-in functions by taking any list.
Unit-3:

Dictionaries: Creating Dictionary, Accessing and Modifying key : value Pairs in Dictionaries, Built-
In Functions Used on Dictionaries, Dictionary Methods, del Statement.
Tuples and Sets: Creating Tuples, Basic Tuple Operations, tuple() Function, Indexing and Slicing
in Tuples, Built-In Functions Used on Tuples, Relation between Tuples and Lists, Relation between
Tuples and Dictionaries, Using zip() Function, Sets, Set Methods, Frozenset.
Sample Experiments:
1. Write a program to create tuples (name, age, address, college) for at least two
members and concatenate the tuples and print the concatenated tuples.
2. Write a program to count the number of vowels in a string (No control flow allowed).
3. Write a program to check if a given key exists in a dictionary or not.
4. Write a program to add a new key-value pair to an existing dictionary.
5. Write a program to sum all the items in a given dictionary.

UNIT-4:

Files: Types of Files, Creating and Reading Text Data, File Methods to Read and Write Data,
Reading and Writing Binary Files, Pickle Module, Reading and Writing CSV Files, Python os and
os.path Modules.
Object-Oriented Programming: Classes and Objects, Creating Classes in Python, Creating
Objects in Python, Constructor Method, Classes with Multiple Objects, Class Attributes Vs Data
Attributes, Encapsulation, Inheritance, Polymorphism.

Sample Experiments:
1. Write a program to sort words in a file and put them in another file. The output file should have
only lower-case ` words, so any upper-case words from source must be lowered.
2. Python program to print each line of a file in reverse order.
3. Python program to compute the number of characters, words and lines in a file.
4. Write a program to create, display, append, insert and reverse the order of the items
in the array.
5. Write a program to add, transpose and multiply two matrices.
6. Write a Python program to create a class that represents a shape. Include methods to calculate its
area and perimeter. Implement subclasses for different shapes like circle, triangle, and square.

SKILL ENHANCEMENT COURSE ON PYTHON UNIT – 1

What is Programming Language?


 Programming Language is a collection of rules that command a computer,
devices and applications to work according to the written codes.
 The programing language enables us to write efficient programs and develop
online solutions such as- mobile applications, web applications, and games, etc.
 Programming is used to automate, maintain, assemble, measure and interpret the
processing of the data and information. It helps in accelerating the input and output
of the devices or applications.

What is Python?
 Python is a general purpose and powerful programming language.
 Python is considered as one of the most versatile programming language as it can
be used to develop almost any kind of application including desktop application ,
web applications , CAD , Image processing and many more.

History of Python Programming Language:


Python, a high-level, interpreted programming language, was created by Guido van Rossum
and first released in 1991. It was designed to emphasize code readability and simplicity,
enabling programmers to write clear and logical code for small and large-scale projects.
Python's design philosophy encourages code readability with its notable use of significant
whitespace.

Key Milestones:
 Late 1980s: Guido van Rossum began working on Python as a successor to the ABC
programming language.
 1991: Python 0.9.0 was released, featuring classes, exception handling, and functions.
 2000: Python 2.0 introduced list comprehensions, a garbage collection system, and
a full-fledged cycle-detecting garbage collector.
 2008: Python 3.0 was released, intended to fix design flaws in the language
and reduce redundancy. It was not backward compatible with Python 2.x.
 2020: Python 2 reached the end of its life, emphasizing the transition to Python 3.
Thrust Areas of Python:
Python has become one of the most popular programming languages due to its versatility
and ease of use. The thrust areas where Python excels include:
 Web Development: Frameworks like Django, Flask, and Pyramid facilitate rapid
development and clean design.
 Data Science and Analytics: Libraries such as Pandas, NumPy, and Matplotlib make
Python a powerful tool for data analysis and visualization.
 Artificial Intelligence and Machine Learning: TensorFlow, Keras, and Scikit-Learn
are widely used for developing AI and ML models.
 Automation and Scripting: Python's simplicity makes it ideal for writing scripts to
automate repetitive tasks.
 Game Development: Libraries like Pygame help in creating simple games and
multimedia applications.
 Desktop GUI Applications: Frameworks like Tkinter, PyQt, and Kivy enable the
development of user-friendly graphical interfaces.
 Internet of Things (IoT): Python is used in IoT applications due to its ease of use and
the availability of numerous libraries.

Installing Anaconda Python Distribution


Anaconda is a popular distribution of Python and R for scientific computing and data science.
It includes a wide range of packages and tools, simplifying package management and
deployment.
Installation Steps:
1. Download Anaconda:
 Go to the Anaconda Distribution page.
 Choose the appropriate version for your operating system (Windows,
macOS, Linux) and download the installer.
2. Install Anaconda:
 Run the installer and follow the prompts.
 On Windows, you may need to check the box to add Anaconda to your PATH
environment variable.

3. Verify Installation:
 Open a terminal (or Anaconda Prompt on Windows) and type conda --version.
 This should display the version of Conda installed.

Installing and Using Jupyter Notebook


Jupyter Notebook is an open-source web application that allows you to create and share
documents containing live code, equations, visualizations, and narrative text.
Installation Steps:
1. Install Jupyter Notebook:
 If you have Anaconda installed, Jupyter Notebook is already included. To install it
separately, you can use the following command:
 “conda install jupyter”
2. Starting Jupyter Notebook:
 Open a terminal (or Anaconda Prompt on Windows) and type:
 “jupyter notebook”
 This will start the Jupyter Notebook server and open a new tab in your
default web browser.

3. Using Jupyter Notebook:


 In the browser, navigate to the directory where you want to create or
open a notebook.
 Click "New" and select "Python 3" to create a new notebook.
 You can now write and execute Python code in the notebook cells. Each cell
can contain code, text, or Markdown.
4. Basic Operations:
 Running a Cell: Press 'Shift + Enter' to run the current cell and move to the
next one.
 Inserting Cells: Use the 'Insert' menu or keyboard shortcuts to insert new
cells above or below the current one.
 Saving Notebooks: Click on the disk icon or use 'Ctrl + S' to save your work.
 Exporting Notebooks: You can export notebooks to various formats (e.g., HTML,
PDF) via the 'File' menu.

What Happened In Background?

 When a Python program executes, a bytecode compiler translates source code


into bytecode.
 This bytecode is stored in RAM and not visible to us.
 After the bytecode is produced, it is then processed by the PVM (Python
Virtual Machine a.k.a Python Runtime or Python interpreter).
 So the Python compiler produces bytecode in bulk while the Python interpreter
inside PVM performs line-by-line execution of the bytecode.

Example: (firstcode.py)
print("Hello User")
print("Python Rocks")

 Now open the command prompt , move to the folder My Python Codes and type
the following command:
python firstcode.py

Features of Python:
• Simple

• Dynamically Typed

• Robust

• Supports multiple programming paradigms

• Compiled as well as Interpreted

• Cross Platform

• Extensible

• Embedded

• Extensive Library
Simple:

• Python is very simple

• As compared to other popular languages like Java and C++, it is easier to code
in Python.

• Python code is comparitively 3 to 5 times smaller than C/C++/Java code.

• Example to Print Hello world!

• IN C: #include <stdio.h>

int main(){
printf("Hello world!");
return 0;
}

• IN JAVA: public class HelloWorld{


public static void main( String[] args )
{ System.out.println( "Hello world!" );
}

• IN PYTHON: print('Hello world!')

Dynamically Typed:
Robust:

• Python has very strict rules which every program must compulsorily follow and if
these rules are violated then Python terminates the code by generating
“Exception”.

• In Python if we write the same code then it will generate Exception terminating
the code.

• Due to this other running programs on the computer do not get affected and
the system remains safe and secure.

Supports Multiple Programming Paradigms:

• Python supports both procedure-oriented and object-oriented programming


which is one of the key python features.

• In procedure-oriented languages, the program is built around procedures or


functions which are nothing but reusable pieces of programs.

• In object-oriented languages, the program is built around objects which combine


data and functionality.

Compiled As Well As Interpreted:


• Python uses both a compiler as well as interpreter for converting our source
and running it.

• However, the compilation part is hidden from the programmer, so mostly people
say it is an interpreted language.

Cross Platform:

• Let’s assume we’ve written a Python code for our Windows machine.

• Now, if we want to run it on a Mac, we don’t need to make changes to it for the same.

• In other words, we can take one code and run it on any machine, there is no need
to write different code for different machines.

• This makes Python a cross platform language.

Extensible:
• Python allows us to call C/C++/Java code from a Python code and thus we say it is an
extensible language.
• We generally use this feature when we need a critical piece of code to run very fast.

• So we can code that part of our program in C or C++ and then use it from our
Python program.

Embedded:

• We just saw that we can put code in other languages in our Python source code.

• However, it is also possible to put our Python code in a source code in a


different language like C++.

• This allows us to integrate Python feature into our program of the other language.

Extensive Library:

• The Python Standard Library is huge indeed.

• It can help you do various things like Database Programming, E-mailing, GUI
Programming etc.

PARTS OF PYTHON PROGRAMMING LANGUAGE:


Identifiers: Identifier is the name given to entities like class, functions, variables, modules
and any other object in Python.
Rules for identifiers:
 Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to
Z) or digits (0 to 9) or an underscore (_).
 No special character except underscore is allowed in the name of a variable.
 It must compulsorily begin with a underscore ( _ ) or a letter and not with a digit.
Although after the first letter we can have as many digits as we want. So 1a is
invalid, while a1 or _a or _1 is a valid name for an identifier.
 Identifiers are case sensitive, so pi and Pi are two different identifiers.

 Keywords cannot be used as identifiers

 Identifier can be of any length.

Keywords: A word in a programming language which has a fixed meaning and cannot be
redefined by the programmer or used as identifiers
How many reserved words are there in Python?

 Python contains 33 reserved words or keywords in Python 3.6.5 version.


 The list is mentioned on the next slide
 We can get this list by using help() in Python Shell
Some Important Observations:

 Except False, True and None all the other keywords are in lowercase.

 We don’t have else if in Python, rather it is elif.

 There are no switch and do-while statements in Python.

Statements and Expression:


 A statement is an instruction that the Python interpreter can execute. We have
only seen the assignment statement so far. Some other kinds of statements that
we’ll see shortly are “while statements, for statements, if statements, and import
statements”. (There are other kinds too!)

 An expression is a combination of values, variables, operators, and calls to


functions. Expressions need to be evaluated. If you ask Python to print an
expression, the interpreter evaluates the expression and displays the result.

 If we take a look at this same example in the Python shell, we will see one of
the distinct differences between statements and expressions.

 Note that when we enter the assignment statement, y = 3.14, only the
prompt is returned. There is no value. This is due to the fact that statements,
such as the assignment statement, do not return a value. They are simply
executed.

 On the other hand, the result of executing the assignment statement is the creation
of a reference from a variable, y, to a value, 3.14. When we execute the print
function working on y, we see the value that y is referring to. In fact, evaluating y by
itself results in the same response.
Variables:
 Variables are nothing but reserved memory locations to store values.
 It means that when you create a variable, you reserve some space in the memory.
 Based on the data type of a variable, the interpreter allocates memory and
decides what can be stored in the reserved memory.
 Therefore, by assigning different data types to the variables, you can store
integers, decimals or characters in these variables.
 Python variables do not need explicit declaration to reserve memory space.
 The declaration happens automatically when you assign a value to a variable.
The equal sign (=) is used to assign values to variables.
 The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable.

For example:

 Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and
name variables, respectively. This produces the following result :

 Python allows you to assign a single value to several variables simultaneously.

For example: a = b = c = 1
 Here, an integer object is created with the value 1, and all the three variables
are assigned to the same memory location. You can also assign multiple
objects to multiple variables.

For example: a, b, c = 1, 2, "john"


 Here, two integer objects with values 1 and 2 are assigned to the variables a and b
respectively, and one string object with the value "john" is assigned to the variable
c.
Variable Scopes: The scope of a variable refers to the places from where we can see or
access a variable. In Python, there are 4 types of scopes in short we pronounce it as LEGB:

 Local : Inside a function body

 Enclosing: Inside an outer function’s body.

 Global: At the module level

 Built In: At the interpreter level

Global Variable:

 A variable which is defined in the main body of a file.

 It will be visible throughout the file.

Local Variable:

 A variable which is defined inside a function is local to that function.

 It is accessible from the point at which it is defined until the end of


the function.

 It exists for as long as the function is executing.

 Even the parameter in the function definition behave like local variables

 When we use the assignment operator (=) inside a function, it’s default
behaviour is to create a new local variable – unless a variable with the
same name is already defined in the local scope.
Example:
Operators: Python language supports the following types of operators:
 Arithmetic Operators
 Comparison (Relational)
Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Arithmetic Operators:
Arithmetic operators are used to perform mathematical functions such as addition,
subtraction, division, multiplications etc. are supported by python follows:

Example:
Relational Operators:

 Relational operators are also known as conditional or comparison operators.


 Relational operators are used for comparing two expression and result in either
True or False.
 Basically, relational operators determine the relation among different operands.
 These operators are used in conditional programing with if, elif, while etc.

Example:

Unary Operators:

 The operator that act one operand are referred to as Unary Operator.
 Basically, Unary operator contains 1 operand and 1 operator. Examples: + 4, – 5
Assignment Operators:

 Assignment operators are used to assigning values to a variables.


 You can use assignment operator with other operators then it is called
Augmented Assignment Operator and Shorthand Assignment Operator.

Example:

Logical Operators:

 Logical operators are used in control statements when you want to check more
than one expression in a single statement.
 They return the result as True or False.
 Python supported 3 types of logical operators i.e. and, or, not.
Bitwise Operators:
 Bitwise operators are work on bits and perform bit by bit operations.
 It firsts covert the number into binary (bits form) then working on bits.
 There are 6 bitwise operators in Python:

Example:
Membership Operators:
 Membership operators are used to check if a value exists in a sequence or not.
 They return the result as True or False.
 There are 2 membership operators in python :
 in : returns True if a values is found in a sequence.
 not in : returns True if a value is not found in a
sequence. Examples:

Identity Operators:
 Identity operators are used to check whether two values are on the same part of
the memory or not.
 They return the result as True or False.
 There are 2 membership operators in python :
 is : returns True if two operands are identical.
 is not: returns True if two operands are not
identical. Examples:
Operator Precedence:
When an expression or statement involves multiple operators then it will be resolve using the
following operator precedence chart:

Expressions:
 Any logical sentence of code that we write during programming, is called expression.
 An expression is valid combination of operators and
operands. Examples:

Binary Operators:

 Operators that act upon two operands are refers to as Binary Operators.
 Binary operators further classified into many operators like:
Arithmetic Operators, Logical Operators, Relational Operators
etc.
Precedence and Associativity of Operators:
 In Python, operator precedence determines the order in which operations
are performed.
 Operators with higher precedence are evaluated before operators with
lower precedence.
 If operators have the same precedence, their associativity determines the order
of evaluation.
 Here is a list of Python operators from highest to lowest precedence, along with
their associativity:

1. Parentheses `( )`:
• Description: Used for grouping expressions.
• Associativity: N/A

2. Exponentiation `**`:

• Description: Raises a number to the power of another.


• Associativity: Right-to-left

3. Unary `+`, `-`, `~`:


• Description: Unary plus, unary minus, and bitwise NOT.
• Associativity: Right-to-left

4. Multiplication `*`, Division `/`, Floor Division `//`, Modulus `%`:

• Description: Arithmetic operations.


• Associativity: Left-to-right

5. Addition `+`, Subtraction `-`:


• Description: Arithmetic operations.
• Associativity: Left-to-right

6. Bitwise Shift `<<`, `>>`:

• Description: Bitwise left shift and right shift.


• Associativity: Left-to-right

7. Bitwise AND `&`:


• Description: Bitwise AND.
• Associativity: Left-to-right

8. Bitwise XOR `^`:

• Description: Bitwise XOR.


• Associativity: Left-to-right
9. Bitwise OR `|`:
• Description: Bitwise OR.
• Associativity: Left-to-right

10. Comparison `==`, `!=`, `>`, `<`, `>=`, `<=`, `is`, `is not`, `in`, `not in`:

• Description: Comparison operations.


• Associativity: Left-to-right

11. Logical NOT `not`:


• Description: Logical NOT.
• Associativity: Right-to-left

12. Logical AND `and`:

• Description: Logical AND.


• Associativity: Left-to-right

13. Logical OR `or`:


• Description: Logical OR.
• Associativity: Left-to-right

14. Conditional Expression `if - else`:

• Description: Ternary conditional operator.


• Associativity: Right-to-left

15. Assignment `=`, `+=`, `-=`, `*=`, `/=`, `//=`, `%=`, `**=`, `&=`, `|=`, `^=`, `>>=`, `<<=`:
• Description: Assignment operations.
• Associativity: Right-to-left

16. Lambda `lambda`:

• Description: Lambda expression.


• Associativity: Right-to-left

Explanation:
• Parentheses have the highest precedence and can be used to override the
default precedence rules.
• Exponentiation is right associative, meaning expressions are evaluated from right
to left.
• Unary operators are also right associative.
• Multiplication, Division, Floor Division, Modulus, as well as Addition and
Subtraction, follow left-to-right associativity.
• Bitwise and Logical operators follow similar rules of associativity.
• Conditional expressions and assignment operators are right associative.
• Lambda expressions are right associative as well.
This program helps illustrate how different operators are evaluated based on their precedence
and associativity Follows:
Example:
# Parentheses - highest precedence
result = (2 + 3) * 4

print(f"Result of (2 + 3) * 4 is {result}")

# Exponentiation - right-to-left associativity


result = 2 ** 3 ** 2

print(f"Result of 2 ** 3 ** 2 is {result}")

# Unary operators - right-to-left associativity


result = -3 + 5

print(f"Result of -3 + 5 is {result}")

# Multiplication, Division, Floor Division, Modulus - left-to-right associativity result

= 10 / 2 * 3

print(f"Result of 10 / 2 * 3 is {result}")

# Addition, Subtraction - left-to-right associativity


result = 10 - 2 + 3

print(f"Result of 10 - 2 + 3 is {result}")

# Bitwise shift operators - left-to-right associativity


result = 1 << 2 >> 1

print(f"Result of 1 << 2 >> 1 is {result}")


# Bitwise AND - left-to-right associativity
result = 5 & 3

print(f"Result of 5 & 3 is {result}")

# Bitwise XOR - left-to-right associativity


result = 5 ^ 3

print(f"Result of 5 ^ 3 is {result}")

# Bitwise OR - left-to-right associativity result = 5 | 3

print(f"Result of 5 | 3 is {result}")

# Comparison operators - left-to-right associativity


result = 5 > 3 == True

print(f"Result of 5 > 3 == True is {result}")

# Logical NOT - right-to-left associativity result


= not False

print(f"Result of not False is {result}")

# Logical AND - left-to-right associativity result


= True and False

print(f"Result of True and False is {result}")

# Logical OR - left-to-right associativity


result = True or False

print(f"Result of True or False is {result}")


# Conditional expression - right-to-left associativity
result = 5 if True else 10

print(f"Result of 5 if True else 10 is {result}")

# Assignment operators - right-to-left associativity


a = b = c = 10

print(f"Values after a = b = c = 10: a={a}, b={b}, c={c}")

# Lambda expression - right-to-left associativity


result = (lambda x: x + 1)(5)

print(f"Result of (lambda x: x + 1)(5) is {result}")


Data Types:
 Although a programmer is not allowed to mention the data type while creating
variables in his program in Python, but Python internally allots different data types
to variables depending on their declaration style and values.
 Overall Python has 14 data types and these are classified into 6 categories are:
- Numeric Types
- Boolean Type
- Sequence Types
- Set Types
- Mapping Type
- None Type

 Some Very Important Points Before we explore more about these data types, let
us understand following important points regarding Python’s data types:
1. DATA TYPES IN PYTHON ARE DYNAMIC

2. SIZE OF THE DATA TYPE IS ALSO DYNAMICALLY MANAGED

3. DATA TYPES ARE UNBOUNDED

DATA TYPES IN PYTHON ARE DYNAMIC

 The term dynamic means that we can assign different values to the same variable
at different points of time.
 Python will dynamically change the type of variable as per the value given.
SIZE OF THE DATA TYPE IS ALSO DYNAMICALLY MANAGED

• In Python the size of data types is dynamically managed.


• Like C/C++/Java language, variables in Python are not of fixed size.
• Python makes them as big as required on demand.
• There is no question of how much memory a variable uses in Python because
this memory increases as per the value being assigned.
• Python starts with initial size for a variable and then increases its size as needed up
to the RAM limit
• This initial size for int is 24 bytes and then increases as the value is increased
• If we want to check the size of a variable, then Python provides us a function called
getsizeof() .
• This function is available in a module called sys

DATA TYPES ARE UNBOUNDED

• Third important rule to remember is that, in Python data types like integers
don’t have any range i.e. they are unbounded.
• Like C /C++ /Java they don’t have max or min value.
• So an int variable can store as many digits as we want.

Write a Python program that demonstrates all the mentioned data types and their
categories:
# Demonstrating Data Types in Python
# Numeric Types
# Integer
int_var = 10
print(f"Integer: {int_var}, Type: {type(int_var)}")

# Float
float_var = 10.5
print(f"Float: {float_var}, Type: {type(float_var)}")
# Complex
complex_var = 1 + 2j
print(f"Complex: {complex_var}, Type: {type(complex_var)}")

# Boolean Type
bool_var = True
print(f"Boolean: {bool_var}, Type: {type(bool_var)}")

# Sequence Types
# String
str_var = "Hello, Python!"
print(f"String: {str_var}, Type: {type(str_var)}")

# List
list_var = [1, 2, 3, 4, 5]
print(f"List: {list_var}, Type: {type(list_var)}")

# Tuple
tuple_var = (1, 2, 3, 4, 5)
print(f"Tuple: {tuple_var}, Type: {type(tuple_var)}")

# Range
range_var = range(5)
print(f"Range: {range_var}, Type: {type(range_var)}, List of Range: {list(range_var)}")

# Set Types
# Set
set_var = {1, 2, 3, 4, 5}
print(f"Set: {set_var}, Type: {type(set_var)}")

# Frozen Set
frozenset_var = frozenset([1, 2, 3, 4, 5])
print(f"Frozen Set: {frozenset_var}, Type: {type(frozenset_var)}")

# Mapping Type
# Dictionary
dict_var = {"name": "John", "age": 25}
print(f"Dictionary: {dict_var}, Type: {type(dict_var)}")

# None Type
none_var = None
print(f"None: {none_var}, Type: {type(none_var)}")

# Byte Types
# Bytes
bytes_var = b"Hello"
print(f"Bytes: {bytes_var}, Type: {type(bytes_var)}")

# Bytearray
bytearray_var = bytearray([1, 2, 3])
print(f"Bytearray: {bytearray_var}, Type: {type(bytearray_var)}")

# Memoryview
memoryview_var = memoryview(bytearray_var)
print(f"Memoryview: {memoryview_var}, Type: {type(memoryview_var)}")
Explanation of Data Types and Categories:
1. Numeric Types:
- Integer (`int`): Whole numbers, positive or negative, without decimals.
- Float (`float`): Numbers, positive or negative, containing one or more decimals.
- Complex (`complex`): Complex numbers with a real and imaginary part.

2. Boolean Type:
- Boolean (`bool`): Represents one of two values: `True` or `False`.

3. Sequence Types:
- String (`str`): Sequence of characters.
- List (`list`): Ordered collection of items, which can be of different types.
- Tuple (`tuple`): Ordered, immutable collection of items.
- Range (`range`): Represents a sequence of numbers, commonly used in for-loops.

4. Set Types:
- Set (`set`): Unordered collection of unique items.
- Frozen Set (`frozenset`): Immutable version of a set.

5. Mapping Type:
- Dictionary (`dict`): Unordered collection of key-value pairs.

6. None Type:
- None (`NoneType`): Represents the absence of a value.

7. Byte Types:
- Bytes (`bytes`): Immutable sequence of bytes.
- Bytearray (`bytearray`): Mutable sequence of bytes.
- Memoryview (`memoryview`): Allows memory access to an object that supports
the buffer protocol (like `bytearray`).
Indentation in Python:
 Indentation is a fundamental aspect of Python programming.
 Unlike many other programming languages that use braces `{}` or keywords
to denote blocks of code.
 Python uses indentation to define the structure and hierarchy of the code.
 Proper indentation is crucial because it indicates which statements belong to
which block, such as loops, conditionals, functions, and classes.
 Here's an explanation of how indentation works in Python, along with an
example program that demonstrates various constructs requiring indentation:

Rules of Indentation:
1. Consistency:
- Indentation must be consistent throughout the code.
- Typically, four spaces per indentation level is the standard convention, although
tabs can also be used.
- Mixing tabs and spaces is not allowed.
2. Blocks of Code:
- Indentation is used to define blocks of code that belong together.
- For example, the body of a function, loop, or conditional statement.
3. `:` Colon:
- A colon at the end of a statement.
- (e.g., `if`, `for`, `while`, `def`, `class`) indicates that the following indented lines form
a block of code.

Example Program Demonstrating Indentation:


1. Function Definition:

The function `main` is defined, and its body is indented with four spaces.

2. Conditional Statement:

The `if` and `else` blocks are indented, indicating the code that belongs to each block.

3. Loop:

The `for` loop and the nested `if` statement inside the loop are indented appropriately.

4. Class Definition:

The class `ExampleClass` and its methods are defined with proper indentation.
5. Calling Functions and Creating Objects:

These statements are not indented, as they are not part of any block of code.

Common Mistakes to Avoid:


1. Inconsistent Indentation:

1. Mixing Tabs and Spaces:

Following these guidelines will help ensure your Python code is correctly structured and easy
to read. Indentation is not just a stylistic choice in Python; it is a syntactical requirement.

Comments in Python:
• Comments are statements in our program which are ignored by the compiler
or interpreter i.e they are not executed by the language.

• We generally create comments to let developers understand our code’s logic.


• This is a necessary practice, and good developers make heavy use of
the comment system.
• Without it, things can get confusing.
• Python provides 2 types of comments:
• Single Line Comment ( official way of comment)
• MultiLine Comment ( unoffcial way)
1. Single Line Comment:
- Single-line comments in Python are created using the `#` symbol.
- Everything following this symbol on the same line is considered a comment and
is ignored by the Python interpreter.
2. Multi-Line Comment:
- Python does not have a distinct syntax for multi-line comments like some
other languages (e.g., `/* ... */` in C/C++).
- Instead, multi-line comments can be created using multiple single-line comments
or by using multi-line strings (triple quotes), although the latter is technically not a
comment but a string.
- When not assigned to a variable or used in an expression, these strings are ignored
by the interpreter.

Example Demonstrating Both Types of Comments:

Key Points:

• Use `#` for single-line comments.


• Use triple quotes `""" ... """` for multi-line comments, even though they
are technically strings. This method is not official but commonly used.
• Keep your comments clear and concise to improve the readability of your code.
Reading Input and Printing Output in Python:
In Python, you can use the `input()` function to read input from the user and the `print()`
function to display output. Here's a detailed explanation and example of how to use these
functions:

1. Reading Input:
• The `input()` function reads a line from the input (usually from the user)
and returns it as a string.
• If you need to convert the input to another data type, you must explicitly cast it.

Example:

2. Printing Output
• The `print()` function prints the specified message to the screen or other
standard output device.
• You can use it to print strings, numbers, variables, or a combination of
these. Example:
The `type()` Function in Python:
• The `type()` function in Python is used to determine the type of an object.
• It returns the type of the specified object.
• This is particularly useful for debugging and ensuring that variables are of
the expected type.
Syntax: type(object)
#`object`: The object whose type you want to determine.

Example: Here's an example program that demonstrates how to use the `type()` function to
check the types of various objects:
# Integer

num = 10

print(f"Value: {num}, Type: {type(num)}")

# Float

num_float = 10.5

print(f"Value: {num_float}, Type: {type(num_float)}")

# String

text = "Hello, Python!"

print(f"Value: '{text}', Type: {type(text)}")

# List

my_list = [1, 2, 3, 4, 5]

print(f"Value: {my_list}, Type: {type(my_list)}")

# Tuple

my_tuple = (1, 2, 3, 4, 5)

print(f"Value: {my_tuple}, Type: {type(my_tuple)}")

# Set
my_set = {1, 2, 3, 4, 5}

print(f"Value: {my_set}, Type: {type(my_set)}")

# Dictionary

my_dict = {"name": "John", "age": 25}


print(f"Value: {my_dict}, Type: {type(my_dict)}")

# Boolean

flag = True

print(f"Value: {flag}, Type: {type(flag)}")

# None

none_value = None

print(f"Value: {none_value}, Type: {type(none_value)}")

# Function

def my_function():

return "Hello, World!"

print(f"Value: {my_function}, Type: {type(my_function)}")

# Class

class MyClass:

pass

my_instance = MyClass()

print(f"Value: {my_instance}, Type: {type(my_instance)}")

• Debugging: Checking the type of variables during debugging to ensure they are of
the expected type.
• Type Checking: Validating input types in functions or methods to ensure
correct usage.
• Dynamic Typing: Understanding how Python dynamically assigns types to variables
based on the assigned values.
• The `type()` function is a powerful tool for introspecting objects and
understanding the types of variables in your Python programs.
Dynamic and Strongly Typed Language:
Python is both a dynamic and strongly typed language. Here's what these terms mean and
how they apply to Python:
1. Dynamic Typing:
• In a dynamically typed language, the type of a variable is determined at
runtime, not in advance.
• This means you do not have to declare the type of a variable when you create it.
• Instead, the type is inferred from the value you assign to it.
• Variables can also change type during the execution of the program.
• You do not declare types explicitly.
• Types are determined at runtime.
• Variables can change type as the program
runs. Example:

2. Strong Typing:
• In a strongly typed language, once a variable is assigned a type,
operations involving incompatible types will result in an error.
• Python does not perform implicit type conversion, meaning you cannot mix
types without explicitly converting them.
• Python does not perform implicit type conversion.
• Operations on incompatible types will raise errors.
• Explicit conversion is necessary when dealing with different

types. Example:
Type Conversion in Python:
Type conversion is the process of converting one data type to another. In Python, there are
two types of type conversion:
1. Implicit Type Conversion: Automatically performed by Python.
1. Explicit Type Conversion: Manually performed by the programmer.

1. Implicit Type Conversion:


• Implicit type conversion is automatically performed by the Python interpreter.
• In this type of conversion, Python automatically converts one data type to
another without any user involvement.
• This typically happens when mixing different types in an expression.
• Python automatically converts one data type to another. It usually happens
during operations involving mixed data types.
Example:

• In the above example, the integer `a` is implicitly converted to a float when added
to the float `b`, resulting in a float `c`.

2. Explicit Type Conversion:


• Explicit type conversion, also known as type casting, is when the
programmer manually converts one data type to another using Python's
built-in functions.
• Commonly used type conversion functions include:

- int()
- float()
- str()
- list()
- tuple()
- set()
- dict()
• The programmer manually converts one data type to another using functions like
`int()`, `float()`, `str()`, etc.
Example:

Introduction to Decision Control Statements:


• Till now we have learn that the code in a python program is executed
sequentially from the first line of the program to its last line.
• That is, the second statement is executed after the first, the third statement is
executed after the second, so on and so forth. This method is known as sequential
control flow.
• However , in some cases we want to either execute only a selected set of
statements ( selection control) or execute a set of statements repeatedly
(interactive control )
• The decision control statements can alter the flow of a sequence of instruction, such
type of conditional processing provided by the decision control statements extends
the usefulness of program.
• Decision Control Statements in Python are those statements which decide
the execution flow of our program.
• In other words, they allow us to decide whether a particular part of our
program should run or not based upon certain condition.
• The 4 decision control statements in Python are:
- if
- if….else
- if…elif…else
- nested if
if statements:
• An if statement consists of a boolean expression followed by one or more statements.
• The if the statement in Python is similar to other languages like in Java, C, C++, etc.
• It is used to decide whether a certain statement or block of statements will
be executed or not.
• If a certain condition is true then a block of statement is executed otherwise not.

Example:

if...else statements:
• An if statement can be followed by an optional else statement, which executes
when the boolean expression is FALSE.
• The if..else statement evaluates test expression and will execute body of if only
when test condition is True.
• If the condition is False, body of else is executed.
• Indentation is used to separate the blocks.
Example:

if...elif else statements:


• An if statement can be followed by any no of elif statements to check
multiple conditions and an optional else statement, which executes when
the boolean expression is FALSE.
• The elif is short for else if. It allows us to check for multiple expressions.
• If the condition for if is False, it checks the condition of the next elif block and so on.
• If all the conditions are False, body of else is executed.

Example:

Nested if statements:
• You can use one if or else if statement inside another if or else if statement(s).
• We can have a if...elif...else statement inside another if...elif...else statement.
• This is called nesting in computer programming.
• Any number of these statements can be nested inside one another.
• Indentation is the only way to figure out the level of nesting
Example:

Programs that you have to Practice:


1. Write a Program to Check Whether the entered Number is Positive or Negative
2. Write a program to convert days into years, weeks and days.(non leap year\n")
3. Wrte a program to find sum of n natural numbers
4. Write a program to print the denominations for the given no.of seconds in
the following format H:M:S
5. Write a program to enter length and breadth of a rectangle and find its area.
(lb) perimeter. 2(l+b)
6. Write a program to find area and circumference
7. Python program to convert the temperature in degree centigrade to Fahrenheit
8. Write a Program to Write a Program Two Numbers With using temp 2. without
using temp (2)
9. Write a Program to Check Whether a Character is a Vowel or Consonant
10. Write a Program to Find the Largest Number Among Three Numbers
11. Write a program to print last digit and second last digit of a number Sample
input: 12345 o/p: last = 5 second last = 4
12. Write a Program to Check Leap Year
Iterative Statements:
• There may be a situation when we need to execute a block of code several number
of times.
• For such situations , Python provides the concept of loop
• A loop statement allows us to execute a statement or group of statements
multiple times
• The 2 popular loops provided by Python are:
1. The while Loop
2. The for Loop
• Recall that Python doesn’t provide any do..while loop like other languages

While Loop:
The while loop in Python is used to repeatedly execute a block of code as long as a specified
condition is true. The syntax of a while loop is:

• First the condition is evaluated. If the condition is true then statements in the while
block is executed.

• After executing statements in the while block the condition is checked again and if
it is still true, then the statements inside the while block is executed again.
• The statements inside the while block will keep executing until the condition is true.
• Each execution of the loop body is known as iteration.
• When the condition becomes false loop terminates and program control comes out
of the while loop to begin the execution of statement following it.
Example:
Another Form of “while” Loop:
• In Python, just like we have an else with if, similarly we also can have an else part
with the while loop.
• The statements in the else part are executed, when the condition is not
fulfilled anymore.
• Many programmer’s have a doubt that If the statements of the additional else
part were placed right after the while loop without an else, they would have
been executed anyway, wouldn't they.
• Then what is the use of else
• To understand this , we need to understand the break
statement, Example:

“break” Statement:
• Normally a while loop ends only when the test condition in the loop becomes false.
• However , with the help of a break statement a while loop can be left prematurely,
• Now comes the crucial point: If a loop is left by break, the else part is not executed.

Example:
“continue” Statement:
• The continue statement in Python returns the control to the beginning of the
while loop.
• It rejects all the remaining statements in the current iteration of the loop and
moves the control back to the top of the loop.

Example:

“pass” Statement:
• In Python, the pass statement is a no operation statement.
• That is nothing happens when pass statement is executed.

Example:
For Loop:
• Like the while loop the for loop also is a programming language statement, i.e.
an iteration statement, which allows a code block to be executed multiple
number of times.
• There are hardly programming languages without for loops, but the for loop exists
in many different flavours, i.e. both the syntax and the behaviour differs from
language to language.
Different Flavors Of “for” Loop:
⚫ Count-controlled for loop (Three-expression for loop):
This is by far the most common type. This statement is the one used by C , C++
and Java . Generally it has the form:
for (i=1; i <= 10; i++) #This kind of for loop is not implemented in Python!

⚫ Numeric Ranges
This kind of for loop is a simplification of the previous kind. Starting with a start
value and counting up to an end value, like
for i = 1 to 100 #Python doesn't use this either.

• The for loop in Python can iterate over string , list, tuple , set,frozenset,
bytes,bytearray and dictionary
• The first item in the collection is assigned to the loop variable.
• Then the block is executed.
• Then again the next item of collection is assigned to the loop variable,
and the statement(s) block is executed
• This goes on until the entire collection is exhausted.

Example:
“range” Function:
⚫ The range() function is an in-built function in Python, and it returns a range object.
⚫ This function is very useful to generate a sequence of numbers in the form of a List.
⚫ The range( ) function takes 1 to 3 arguments.
⚫ We can use range() and for together for iterating through a list of numeric values.
⚫ We can use 2 argument range() with for also for iterating through a list of numeric
values between a given range

Exception:
• Exception are errors that occur at runtime.
• In other words, if our program encounters an abnormal situation during its
execution it raises an exception.
• For example, the statement a=10/0 will generate an exception because Python
has no way to solve division by 0.

What Python Does When An Exception Occurs?


• Whenever an exception occurs , Python does 2 things :
– It immediately terminates the code
– It displays the error message related to the exception in a technical way
• Both the steps taken by Python cannot be considered user friendly because
– Even if a statement generates exception , still other parts of the program
must get a chance to run
– The error message must be simpler for the user to understand.
As we can observe, in the second run the
code generated exception because Python
does not know how to handle division by 0.
Moreover it did not even calculated the
sum of 10 and 0 which is possible

In this case since it is not possible for


Python to covert “2a” into an integer, so it
generated an exception. But the message
it displays is too technical to understand

How to Handle Such Situations?


• If we want our program to behave normally, even if an exception occurs, then
we will have to apply Exception Handling.
• Exception handling is a mechanism which allows us to handle errors gracefully
while the program is running instead of abruptly ending the program execution.

• Python provides 5 keywords to perform Exception Handling:


– try
– except
– else
– raise
– finally
Exception Handling Syntax:
Improved Version of Previous Example Code:

A Very Important Point: -

• Amongst all the exceptions mentioned in the previous slides, we cannot handle
SyntaxError exception, because it is raised by Python even before the program
starts execution.
• A try statement may have more than one except clause for different exceptions.
• But at most one except clause will be executed
SAMPLE EXPERIMENTS:
1. Write a program to find the largest element among three numbers.

1. Write a program to display all prime numbers within an interval.

2. Write a program to swap two numbers without using a temporary variable.


3. Demonstrate the following operators in Python with suitable examples.
i) Arithmetic Operators:

ii) Relational Operators:

iii) Assignment Operators:


iv) Logical Operators:

v) Bitwise Operators:

vi) Ternary Operator:

vii) Membership Operators:


viii) Identity Operators:

2. Write a program to add and multiply complex numbers.

3. Write a program to print the multiplication table of a given number.

Page 64
UNIT – 3

Dictionaries in Python:

Page 65
 Python dictionary is an unordered collection of items.

 The collections we have studied till now like list , tuple and string are all ordered

collections as well as can hold only one value as their element

 On the other hand dictionary is an unordered collection which holds the data in a key:

value pair.

1. Creating a Dictionary

• A dictionary in Python is an unordered collection of key-value pairs.

• Keys are unique, and values can be any data type.

Example:

# Creating a dictionary

person = {

"name": "John",

"age": 25,

"city": "New York"

print(person)

Output:

{'name': 'John', 'age': 25, 'city': 'New York'}

Explanation:

- Here, `"name"`, `"age"`, and `"city"` are the keys.

- `"John"`, `25`, and `"New York"` are the corresponding values.

- Keys are used to access values.

2. Accessing and Modifying Key-Value Pairs

Page 66
• You can access the value using the key and modify it similarly.

Example:

# Accessing a value

print(person["name"]) # Output: John

# Modifying the value of a key

person["age"] = 26

print(person)

Output:

{'name': 'John', 'age': 26, 'city': 'New York'}

Explanation:

- We accessed the value of the key `"name"`

- Modified the value of `"age"` to `26`.

3. Built-In Functions Used on Dictionaries

• Some useful built-in functions are:

- `len(dictionary)`: Returns the number of key-value pairs in the dictionary.

- `dictionary.keys()`: Returns all the keys in the dictionary.

- `dictionary.values()`: Returns all the values in the dictionary.

- `dictionary.items()`: Returns all key-value pairs as tuples.

Example:

print(len(person)) # Output: 3

print(person.keys()) # Output: dict_keys(['name', 'age', 'city'])

print(person.values()) # Output: dict_values(['John', 26, 'New York'])

print(person.items())

Page 67
# Output: dict_items([('name', 'John'), ('age', 26), ('city', 'New York')])

Explanation:

- `len()` counts the number of items (key-value pairs).

- `keys()`, `values()`, and `items()` provide a way to retrieve keys, values, or both.

4. Dictionary Methods

• Some common dictionary methods are:

- `get()`: Safely access a value (won't throw an error if the key doesn't exist).

- `update()`: Adds or updates multiple key-value pairs at once.

- `pop()`: Removes a key and returns its value.

Example:

# Using get()

print(person.get("city")) # Output: New York

# Using update()

person.update({"country": "USA", "occupation": "Engineer"})

print(person)

# Output: {'name': 'John', 'age': 26, 'city': 'New York', 'country': 'USA', 'occupation':

'Engineer'}

# Using pop()

person.pop("age")

print(person)

# Output: {'name': 'John', 'city': 'New York', 'country': 'USA', 'occupation': 'Engineer'}

Explanation:

- `get()` is safer than directly accessing values since it doesn't raise an error if the key doesn't exist.

Page 68
- `update()` allows us to update multiple fields in one call.

- `pop()` removes a key-value pair.

5. The `del` Statement

- `del`: Deletes a key-value pair or the entire dictionary.

Example:

# Deleting a key-value pair

del person["city"]

print(person) # Output: {'name': 'John', 'country': 'USA', 'occupation': 'Engineer'}

# Deleting the entire dictionary

del person #NameError: name 'person' is not defined

Tuples in Python:

1. Creating Tuples

• Tuples are immutable sequences of data. Once created, their elements cannot be changed.

Example:

# Creating a tuple

my_tuple = ("John", 25, "New York")

print(my_tuple) # Output: ('John', 25, 'New York')

Explanation:

- Tuples can store multiple data types, and their values are enclosed in parentheses `()`.

2. Basic Tuple Operations

- Accessing Elements: Like lists, you can access tuple elements using indices.

- Concatenation: You can join two or more tuples.

Example:

Page 69
# Accessing elements

print(my_tuple[0]) # Output: John

# Slicing

print(my_tuple[1:3]) # Output: (25, 'New York')

# Concatenating tuples

new_tuple = my_tuple + ("Engineer",)

print(new_tuple) # Output: ('John', 25, 'New York', 'Engineer')

Explanation:

- Tuples are indexed just like lists.

- Concatenation adds elements to the tuple, creating a new one.

5 | P a g e By S.Jayashankar (Technical Trainer)

3. Relation Between Tuples, Lists, and Dictionaries

- Tuples vs Lists: Tuples are immutable, while lists are mutable.

- Tuples and Dictionaries: Tuples can be used as dictionary keys, but lists cannot because

tuples are immutable.

Example:

my_dict = {("John", 25): "New York"}

print(my_dict) # Output: {('John', 25): 'New York'}

Explanation:

- We used a tuple as a key in the dictionary because tuples are hashable.

4. Using `zip()` Function

- The `zip()` function combines two or more iterables (like lists or tuples) into pairs of tuples.

Example:

Page 70
names = ("Alice", "Bob")

ages = (24, 27)

zipped = zip(names, ages)

print(list(zipped)) # Output: [('Alice', 24), ('Bob', 27)]

Explanation:

- The `zip()` function returns an iterator that pairs the elements of the passed iterables.

6 | P a g e By S.Jayashankar (Technical Trainer)

Sets and Frozensets in Python

1. Creating Sets

- A set is an unordered collection of unique elements.

Example:

# Creating a set

my_set = {1, 2, 3, 4, 4}

print(my_set) # Output: {1, 2, 3, 4} (duplicate is removed)

Explanation:

- Sets automatically remove duplicates. They are defined using curly braces `{}`.

2. Set Methods

- `add()`: Adds an element to the set.

- `remove()`: Removes an element (raises an error if the element is not found).

- `discard()`: Removes an element (does not raise an error if the element is not found).

Example:

# Adding elements

my_set.add(5)

Page 71
print(my_set) # Output: {1, 2, 3, 4, 5}

# Removing elements

my_set.remove(2)

print(my_set) # Output: {1, 3, 4, 5}

Explanation:

- The set is modified in place using the `add()` and `remove()` methods.

7 | P a g e By S.Jayashankar (Technical Trainer)

3. Frozenset

- A `frozenset` is an immutable version of a set, meaning its elements cannot be changed

once assigned.

Example:

# Creating a frozenset

my_frozen_set = frozenset([1, 2, 3, 3])

print(my_frozen_set) # Output: frozenset({1, 2, 3})

Explanation:

- `frozenset` is immutable and, like a set, automatically removes duplicates.

Sample Experiments

1. Write a program to create tuples (name, age, address, college) for at least two

members and concatenate the tuples and print the concatenated tuples.

Source Code:

# Creating tuples for two members

person1 = ("Alice", 24, "New York", "NYU")

person2 = ("Bob", 22, "San Francisco", "SFSU")

Page 72
# Concatenating tuples

combined_tuple = person1 + person2

print(combined_tuple)

Output: ('Alice', 24, 'New York', 'NYU', 'Bob', 22, 'San Francisco', 'SFSU')

Explanation:

- We created two tuples `person1` and `person2` and concatenated them using `+`.

8 | P a g e By S.Jayashankar (Technical Trainer)

2. Write a program to count the number of vowels in a string (No control flow allowed).

Source Code:

# Given string

string = "Hello, World!"

# Count the number of vowels

vowels = 'aeiouAEIOU'

vowel_count = sum(1 for char in string if char in vowels)

print(f"Number of vowels: {vowel_count}")

Output: Number of vowels: 3

Explanation:

- The `sum()` function counts the number of vowels in the string by using a generator expression.

3. Write a program to check if a given key exists in a dictionary or not.**

Source Code:

# Dictionary

my_dict = {"name": "Alice", "age": 24, "city": "New York"}

# Check if key exists

Page 73
key_to_check = "age"

if key_to_check in my_dict:

print(f"'{key_to_check}' exists in the dictionary")

else:

print(f"'{key_to_check}' does not exist in the dictionary")

Output: 'age' exists in the dictionary

Explanation:

- The `in` operator checks if a key is present in the dictionary.

9 | P a g e By S.Jayashankar (Technical Trainer)

4. Write a program to add a new key-value pair to an existing dictionary.

Source Code:

# Dictionary

my_dict = {"name": "Alice", "age": 24,"city": "New York"}

# Adding a new key-value pair

my_dict["country"] = "USA"

print(my_dict)

Output: {'name': 'Alice', 'age': 24, 'city': 'New York', 'country': 'USA'}

Explanation:

- We directly assigned a new key `"country"` and its corresponding value `"USA"` to the dictionary.

5. Write a program to sum all the items in a given dictionary.

Source Code:

# Dictionary with numeric values

num_dict = {"a": 10, "b": 20, "c": 30}

Page 74
# Summing all the values

total_sum = sum(num_dict.values())

print(f"Sum of all items: {total_sum}")

Output: Sum of all items: 60

Explanation:

- We used the `sum()` function to calculate the total of all the dictionary values.

NOTE: These detailed explanations and examples should give you a solid understanding of

**Dictionaries**, **Tuples**, **Sets**, and how they are used in Python.

Class diagram

Page 75
o A class diagram shows a set of classes, interfaces, and collaborations and their relationships.Class
diagrams are the most common diagrams in UML.
o Class diagrams address the static design view of a system.Class diagrams that include active classes
address the static process view of a system.
Object diagram

o Object diagrams represent static snapshots of instances of the things found in class diagrams
o These diagrams address the static design view or static process view of a system.
o An object diagram shows a set of objects and their relationships.
Use case diagram

o A use case diagram shows a set of use cases and actors and their relationships.
o Use case diagrams address the static use case view of a system.
o These diagrams are especially important in organizing and modeling the behaviors of a system.
Interaction Diagrams

o Both sequence diagrams and collaboration diagrams are kinds of interaction diagrams. Interaction
diagrams address the dynamic view of a system.A sequence diagram is an interaction diagram that
emphasizes the time-ordering of messages.
o A collaboration diagram is an interaction diagram that emphasizes the structural organization of the
objects that send and receive messages
o Sequence diagrams and collaboration diagrams are isomorphic, meaning that you can take one and
transform it into the other.
State chart diagram

o A State chart diagram shows a state machine, consisting of states, transitions, events, and activities
o Statechart diagrams address the dynamic view of a system
o They are especially important in modeling the behavior of an interface, class, or collaboration and
emphasize the event-ordered behavior of an object
Activity diagram

o An activity diagram is a special kind of a state chart diagram that shows the flow from activity to activity
within a system
o Activity diagrams address the dynamic view of a system.

Page 76
o They are especially important in modeling the function of a system and emphasize the flow of control
among objects
Component diagram

o A component diagram shows the organizations and dependencies among a set of components.
o Component diagrams address the static implementation view of a system
o They are related to class diagrams in that a component typically maps to one or more classes, interfaces,
or collaborations
Deployment diagram

o A deployment diagram shows the configuration of run-time processing nodes and the components that
live on them.
o Deployment diagrams address the static deployment view of an architecture
o They are related to component diagrams in that a node typically encloses one or more components.
Rules of the UML
The UML has semantic rules for
1. Names What you can call things, relationships, and diagrams
2. Scope The context that gives specific meaning to a name
3. Visibility How those names can be seen and used by others
4. Integrity How things properly and consistently relate to one another
5. Execution What it means to run or simulate a dynamic model
Models built during the development of a software-intensive system tend to evolve and may be viewed by many
stakeholders in different ways and at different times. For this reason, it is common for the development team to
not only build models that are well-formed, but also to build models that are
1. Elided : Certain elements are hidden to simplify the view
2. Incomplete : Certain elements may be missing
3. Inconsistent : The integrity of the model is not guaranteed
Common Mechanisms in the UML
UML is made simpler by the presence of four common mechanisms that apply consistently throughout the
language.

1. Specifications
2. Adornments
3. Common divisions
4. Extensibility mechanisms

Page 77
1.Specification that provides a textual statement of the syntax and semantics of that building block. The UML's
specifications provide a semantic backplane that contains all the parts of all the models of a system, each part
related to one another in a consistent fashion
2.Adornments Most elements in the UML have a unique and direct graphical notation that provides a visual
representation of the most important aspects of the element. A class's specification may include other details,
such as whether it is abstract or the visibility of its attributes and operations.

Many of these details can be rendered as graphical or textual adornments to the class's basic rectangular
notation.

3.Common Divisions
1.The division of class and objects.
2.Separation of interface and implementation.
4.Extensibility Mechanisms
The UML's extensibility mechanisms include
1. Stereotypes
2. Tagged values
3. Constraints
o Stereotype extends the vocabulary of the UML, allowing you to create new kinds of building blocks that
are derived from existing ones but that are specific to your problem.
o A tagged value extends the properties of a UML building block, allowing you to create new information
in that element's specification.
o A constraint extends the semantics of a UML building block, allowing you to add new rules or modify
existing ones.

Page 78
Page 79

You might also like