Uml Lab Manul
Uml Lab Manul
(AUTONOMOUS)
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.
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.
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.
3. Verify Installation:
Open a terminal (or Anaconda Prompt on Windows) and type conda --version.
This should display the version of Conda installed.
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
• Cross Platform
• Extensible
• Embedded
• Extensive Library
Simple:
• As compared to other popular languages like Java and C++, it is easier to code
in Python.
• IN C: #include <stdio.h>
int main(){
printf("Hello world!");
return 0;
}
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.
• 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.
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.
• This allows us to integrate Python feature into our program of the other language.
Extensive Library:
• It can help you do various things like Database Programming, E-mailing, GUI
Programming etc.
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?
Except False, True and None all the other keywords are in lowercase.
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 :
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.
Global Variable:
Local Variable:
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:
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:
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 `**`:
10. Comparison `==`, `!=`, `>`, `<`, `>=`, `<=`, `is`, `is not`, `in`, `not in`:
15. Assignment `=`, `+=`, `-=`, `*=`, `/=`, `//=`, `%=`, `**=`, `&=`, `|=`, `^=`, `>>=`, `<<=`:
• Description: Assignment operations.
• 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}")
print(f"Result of 2 ** 3 ** 2 is {result}")
print(f"Result of -3 + 5 is {result}")
= 10 / 2 * 3
print(f"Result of 10 / 2 * 3 is {result}")
print(f"Result of 10 - 2 + 3 is {result}")
print(f"Result of 5 ^ 3 is {result}")
print(f"Result of 5 | 3 is {result}")
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
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
• 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.
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.
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.
Key Points:
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
# Float
num_float = 10.5
# String
# List
my_list = [1, 2, 3, 4, 5]
# Tuple
my_tuple = (1, 2, 3, 4, 5)
# Set
my_set = {1, 2, 3, 4, 5}
# Dictionary
# Boolean
flag = True
# None
none_value = None
# Function
def my_function():
# Class
class MyClass:
pass
my_instance = MyClass()
• 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.
• In the above example, the integer `a` is implicitly converted to a float when added
to the float `b`, resulting in a float `c`.
- int()
- float()
- str()
- list()
- tuple()
- set()
- dict()
• The programmer manually converts one data type to another using functions like
`int()`, `float()`, `str()`, etc.
Example:
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:
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:
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.
• 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.
v) Bitwise Operators:
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
On the other hand dictionary is an unordered collection which holds the data in a key:
value pair.
1. Creating a Dictionary
Example:
# Creating a dictionary
person = {
"name": "John",
"age": 25,
print(person)
Output:
Explanation:
Page 66
• You can access the value using the key and modify it similarly.
Example:
# Accessing a value
person["age"] = 26
print(person)
Output:
Explanation:
Example:
print(len(person)) # Output: 3
print(person.items())
Page 67
# Output: dict_items([('name', 'John'), ('age', 26), ('city', 'New York')])
Explanation:
- `keys()`, `values()`, and `items()` provide a way to retrieve keys, values, or both.
4. Dictionary Methods
- `get()`: Safely access a value (won't throw an error if the key doesn't exist).
Example:
# Using get()
# Using update()
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.
Example:
del person["city"]
Tuples in Python:
1. Creating Tuples
• Tuples are immutable sequences of data. Once created, their elements cannot be changed.
Example:
# Creating a tuple
Explanation:
- Tuples can store multiple data types, and their values are enclosed in parentheses `()`.
- Accessing Elements: Like lists, you can access tuple elements using indices.
Example:
Page 69
# Accessing elements
# Slicing
# Concatenating tuples
Explanation:
- Tuples and Dictionaries: Tuples can be used as dictionary keys, but lists cannot because
Example:
Explanation:
- The `zip()` function combines two or more iterables (like lists or tuples) into pairs of tuples.
Example:
Page 70
names = ("Alice", "Bob")
Explanation:
- The `zip()` function returns an iterator that pairs the elements of the passed iterables.
1. Creating Sets
Example:
# Creating a set
my_set = {1, 2, 3, 4, 4}
Explanation:
- Sets automatically remove duplicates. They are defined using curly braces `{}`.
2. Set Methods
- `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)
Explanation:
- The set is modified in place using the `add()` and `remove()` methods.
3. Frozenset
once assigned.
Example:
# Creating a frozenset
Explanation:
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:
Page 72
# Concatenating tuples
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 `+`.
2. Write a program to count the number of vowels in a string (No control flow allowed).
Source Code:
# Given string
vowels = 'aeiouAEIOU'
Explanation:
- The `sum()` function counts the number of vowels in the string by using a generator expression.
Source Code:
# Dictionary
Page 73
key_to_check = "age"
if key_to_check in my_dict:
else:
Explanation:
Source Code:
# Dictionary
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.
Source Code:
Page 74
# Summing all the values
total_sum = sum(num_dict.values())
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
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