Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Python All Unit by Dsalgo

The document provides an overview of Python programming concepts, including data types, operators, and control flow statements. It covers key features such as variable declaration, type conversion, and the use of comments to improve code readability. Additionally, it includes examples and best practices for writing clean and efficient Python code.

Uploaded by

materialstudy072
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python All Unit by Dsalgo

The document provides an overview of Python programming concepts, including data types, operators, and control flow statements. It covers key features such as variable declaration, type conversion, and the use of comments to improve code readability. Additionally, it includes examples and best practices for writing clean and efficient Python code.

Uploaded by

materialstudy072
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

ENGINEERING

THANKS FOR VISITING

COLLEGE HUB
“The Engineer Has Been, And Is, A Maker Of History.”
- By ”lovely Engineer”

Click
Scan For
to learn Join
more aboutAll
the Feelings Monster in
Group
the Directly
Reflect app.
Example :
 Python is a versatile and widely-used programming language # Basic print statement
known for its readability and ease of use print("Hello, World!")
 It is object oriented programming language # Printing multiple values
name =, nam "Alice"
age = 30
 Python's programming cycle is notably shorter due to its print("Name:"e, "Age:", age)
interpreted nature. # Changing separator and end
 Python skips compile and link steps, distinguishing itself from
print("Four")
traditional languages.
 Programs import modules at runtime, ensuring immediate print("One", "Two", "Three", sep=' | ', end='
execution after changes. *** ')
 Dynamic module reloading in Python allows modifications and
reloads during runtime, facilitating continuous program
updates without interruptions.  The input() function is used to take user input from the
console. It waits for the user to enter some text and returns
that text as a string.
Syntax :
variable = input(prompt)

Example
# Taking user input
name = input("Enter your name: ")
print("Hello, " + name + "!")
# Converting input to integer
age = int(input("Enter your age: "))
print("You will be", age + 1, "years old next
year.")

 Single-Line Comments:
 An Integrated Development Environment (IDE) is a software  Created with #.
suite that streamlines the software development process.  Used for short explanations on the same line.
 Syntax :
# Single-line comment
 Multi-Line (Block) Comments:
 Achieved with triple-quoted strings.
 Used for longer explanations spanning multiple lines.
 Syntax :
'''
Multi-line comment
'''
 Best Practices:
 Provide clarity and context.
 Keep comments concise and up-to-date.
 Avoid redundancy with self-explanatory code.
 Example :
result = calculate_total(price, quantity) # Calculate total cost

 Comments serve to improve code readability and


 Key features include:
understanding without affecting program execution.
1.Code Editing 7.Debugging
2.Build and Compilation 8. Version Control
3.Project Management 9.Testing  A variable holds a value that may change.
4.User Interface Design 10.Auto-Completion  The process of writing the variable name is called declaring
5.Extensibility 11.Performance Profiling the variable.
6.Documentation and Help  In Python, variables do not need to be declared explicitly in
order to reserve memory spaces as in other programming
languages like C, Java, etc.
 The print() function is used to display output on the console.
 When we initialize the variable in Python, Python Interpreter
 It can take one or more arguments and prints them to the
automatically does the declaration process.
standard output (usually the console).
 Syntax :
Syntax
Variable = Expression
print(value1, value2, ..., sep=' ', end='\n')
 Example :
x = 10 # Variable x is initialized with the value 10
 An identifier is a name given to a variable, function, class,  Automatic conversion by Python based on the operation
module, or other entities in a program. being performed.
 Rules for Naming:
 Must start with a letter (a-z, A-Z) or an underscore (_).
 Use specific functions for explicit conversion:
 The remaining characters can be letters, numbers (0-9), or
 int() for integer conversion.
underscores.  float() for float conversion.
 Case-sensitive (e.g., variable and Variable are different).
 str() for string conversion.
 Cannot be a reserved word (e.g., if, else, for, etc.).

Examples:
 Reserved keywords in a programming language are words # Implicit conversion
that have special meanings and cannot be used as identifiers result = 10 + 3.14 # int implicitly converted
(names for variables, functions, etc.)
to float for addition
 because they are reserved for specific purposes in the
language. # Explicit conversion
num_float = 5.5
num_int = int(num_float) # Converts float to
integer
str_num = str(42)

 input() returns a string, so use int() or float() for numerical


input.
 age_str = input("Enter your age: ")
 age_int = int(age_str) # Converts input string to integer

 data types represent the type of data that a variable can hold.
 Here are some common data types in Python:  A combination of symbols that yields a value.
 Integer (int):  Comprises variables, operators, values, sub-expressions, and
 Represents whole numbers without decimal points.
reserved keywords.
 Example: x = 5
 When entered in the command line, expressions are
 Float (float): evaluated by the interpreter, producing a result.
 Represents numbers with decimal points or in exponential
 arithmetic expressions are evaluating to a numeric type are
form. termed arithmetic expressions.
 Example: y = 3.14
 Sub-expressions are parts of larger expressions, enclosed in
 String (str): parentheses.
 Represents text or sequences of characters.
 Example: 4 + (3 * k)
 Example: name = "John"
 Individual Expressions: A single literal or variable can also be
 Boolean (bool): considered an expression (e.g., 4, 3, k).
 Represents either True or False.
 Hierarchy of Sub-Expressions: Expressions may have
 Example: is_valid = True
multiple levels of sub-expressions, forming a hierarchy.
 List (list):  Example: a + (b * (c - d)) has sub-expressions 3 and k.
 Represents an ordered collection of elements.
 Example: numbers = [1, 2, 3]
 Tuple (tuple):  Used for creating, assigning values to, and modifying
 Similar to a list but immutable (cannot be changed after variables.
creation).  Syntax:
 Example: coordinates = (4, 5)  Variable = Expression represents the assignment statement.
 Set (set):
 Represents an unordered collection of unique elements.
 Value-based expression on RHS.
 Example: unique_numbers = {1, 2, 3}
x = 5 + 3 # Assign the result of the expression (5 + 3) to the
 Dictionary (dict):
variable x
 Represents a collection of key-value pairs.
 Current variable on RHS.
 Example: person = {'name': 'Alice', 'age': 25}
y=2
 NoneType (None):
y = y + 1 # Increment the value of the variable y by 1
 Represents the absence of a value or a null value.
 Operation on RHS.
 Example: result = None
a = 10
 Complex (complex):
b=2
 Represents complex numbers with a real and an imaginary
c = a / b # Assign the result of the division operation (a / b)
part.
to the variable c
 Example: z = 3 + 4j

 operators are special symbols or keywords that perform


 Type conversion in Python is changing the data type of a
operations on operands.
variable, allowing operations involving different data types.
Arithmetic Operators:
 Perform basic mathematical operations.
 Examples: + , - , * , / , % , **
Program:
a=5
b=10+a
Print(a, b ) #output 5 15

 Compare two values and return a Boolean result.


 Examples: == , != , < , > , <= , >=
Program
a=5
b=10
Print(a==b , a> b , a< b ) #output:  Operator precedence defines the order in which different
false false true operators are evaluated in an expression. Operators with
higher precedence are evaluated first.
 Perform logical operations on Boolean values.
 Examples: and , or, not  Determines the order of execution for operators with the
Program same precedence.
a=5
b=10 a. Left to Right:
Print( a> b and a< b ) #output: false  Operators of the same precedence are executed from the left
Print( a> b or a< b ) #output: true side first.
b. Right to Left:
Print( not a< b ) #output: false
 Operators of the same precedence are executed from the
right side first.
 Assign values to variables. Associativity in Python:
 Examples: =, +=, -= , *= , /=  Left-to-right associative operators include multiplication,
Program floor division, etc.
a=5  The ** operator is right-to-left associative.
a+=6 Example
Print(a ) #output: 11  result_left = 5 + 3 - 2 # Addition and subtraction with left-to-
right associativity
 print(result_left) # Output: 6
 result_right = 2 ** 3 ** 2 # Exponentiation with right-to-left
 Perform operations on individual bits of binary numbers.
associativity
 Examples: & , | , ^ , ~ , << , >>
print(result_right) # Output: 512
Program
a=5
 PEP 8 is the Python Enhancement Proposal that provides
b=6
style guidelines for writing clean, readable, and consistent
Print(a & b , ~b ) #output: 4, -7 Python code.
 Here are some key points from PEP 8
 Check if a value is a member of a sequence.  Indentation:Use 4 spaces per indentation level.
 Examples: in , not in  Maximum Line Length:Limit all lines to a maximum of 79
Program characters for code, and 72 for docstrings.
a=[5.,3,2,3]  Imports:Import standard libraries first, followed by third-
b=4 party libraries, and then your own modules.
 Whitespace in Expressions and Statements:
Print(b in a , b not in a ) #output: false true
 Immediately inside parentheses, brackets, or braces.
 Immediately before a comma, semicolon, or colon.
 Compare the memory location of two objects.  Comments:Comments should be used to explain complex
 Examples: is ,is not pieces of code or decisions that may not be obvious.
Program  Naming Conventions:
a=5  Use snake_case for function and variable names.

b=a  Use CamelCase for class names.


 Avoid single-letter variable names except for indices and
Print(a is b , a is not b ) #output: true false
loop variables.
 Docstring Conventions:
 Use triple double-quotes for docstrings.
 Write docstrings for all public modules, functions, classes,
and methods.
1. Write a Python program that declares three variables
(integer, string, and float) and prints their values
2. Calculate the average of three numbers
3. Create a program that takes two numbers as input and
calculates their sum, difference, product, and quotient.

4. Write a program that compares two numbers and prints


whether they are equal, greater, or smaller.

5. Develop a program that takes two strings as input and


concatenates them. Print the resulting string.

6. Implement a Python program that demonstrates


incrementing a variable by 1 and then decrementing it by 1.

7. Create a Python program that swaps the values of two


variables without using a temporary variable.

8. Develop a program that uses compound assignment


operators to update the values of variables.

9. Write a Python program that takes user input for their name,
age, and favorite color. Print a formatted output using this
information.
ENGINEERING
THANKS FOR VISITING

COLLEGE HUB
“The Engineer Has Been, And Is, A Maker Of History.”
- By ”lovely Engineer”

Click
Scan For
to learn Join
more aboutAll
the Feelings Monster in
Group
the Directly
Reflect app.
 Syntax :
 conditional statements are used to control the flow of a if condition1:
program based on certain conditions # Code to be executed if condition1 is true
 Conditional statements are also known as decision-making elif condition2:
statements.
# Code to be executed if condition1 is false and condition2 is
 The basic conditional statements are if, else, and elif (short
form "else if"). true
else:
# Code to be executed if both condition1 and condition2
 The if statement is used to test a condition. If the condition is are false
true, the code inside the if block is executed.
 Syntax
if condition:
# Code to be executed if the condition is true

Example:
x = 10 Example
if x > 5: # Example using if-elif-else
print("x is greater than 5") score = 85

if score >= 90:


grade = 'A'
 The if-else statement allows you to specify two blocks of code: elif score >= 80:
one to be executed if the condition is true, and another if the grade = 'B'
condition is false.
elif score >= 70:
 Syntax:
grade = 'C'
if condition:
else:
# Code to be executed if the condition is true
grade = 'F'
else:
print(f"Your grade is {grade}")
# Code to be executed if the condition is true
 Nested-if statements are nested inside other if statements.
That is, a nested-if statement is the body of another if
statement.
 Syntax :
if condition1:
# Code to be executed if condition1 is true

if condition2:
# Code to be executed if condition2 is true (nested within
condition1)

# More code for condition1 (outside the inner if block)


 Example:
x=3 # Code after the if statement(s) (outside the outer if block))
if x > 5: Example
print("x is greater than 5") x = 10
else: if x > 5:
print("x is not greater than 5") print("x is greater than 5")
if x > 8:
print("x is also greater than 8")
I print("This is still inside the outer if
 The if-elif-else statement allows you to test multiple
block")
conditions in sequence. The code inside the block associated
with the first true condition is executed. print("This is outside the outer if block")
Q. Wrie a program to find whether a number iseven or
odd.

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

if number % 2 == 0:
print("even")
else :
print("odd")

Q.Write a program to check the largest among the given


three numbers.
For example :
# Taking user input for three numbers count = 0
num1 = float(input("Enter the first number: ")) while (count < 9) :
num2 = float(input("Enter the second number: ")) print ‘The count is :’, count
num3 = float(input("Enter the third number: ")) count = count +

Q. Checking for the largest number using if statements


if num1 >= num2 and num1 >= num3:  The for loop iterates over each element in the iterable.
largest = num1  For each iteration, the loop executes the code in its body.
elif num2 >= num1 and num2 >= num3:  The loop continues until all elements in the iterable have
largest = num2 been processed.
else:  After the loop completes, any code after the loop will be
executed.
largest = num3
# Displaying the result
print("The largest number ",largest)

Q. Write a Python program to check if the input year is a


leap year or not.
# Taking user input for the year
year = int(input("Enter a year: "))

# Checking if it's a leap year


if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
For example :
print(f"{year} is a leap year.")
i=1
else:
for i in range(1, 8) :
print(f"{year} is not a leap year.")
print 2*i

 A loop is a programming structure that repeats a sequence of


instructions until a specific condition is met.  Loop defined within another loop is known as nested loops.
 A loop statement allows us to execute a statement or group  2. Nested loops are the loops that are nested inside an
of statements multiple times. existing loop, that is, nested loops are the body of another
 Python programming language provides following types of loop.
loops to handle looping requirements:  Syntax :
 a.While loop b. For loop c. Nested loop for condition1 :
for condition2 :
#Body of for loop
 The while loop checks the condition.
 If the condition is True, the loop enters, and the The while
For example :
loop checks the condition.
 If the condition is True, the loop enters, and the code in the for i in range(1,9,2) :
loop's body is executed. for j in range(i) :
 The loop continues to execute the body as long as the print( i, end = ' ')
condition remains True. print()
 When the condition becomes False, the program exits the
loop, and any code after the loop will be executed.
Q . Write a Python program to print fibonocci series and
 The break statement is used to exit a loop prematurely. input take from the user
Example: # Input from the user
for i in range(1, 10): n = int(input("Enter number of terms for Fibonacci series: "))
if i == 5:
break prevNum = 0
print(i) currNum = 1
print(prevNum, currNum)
for i in range(2, n):
 The continue statement is used to skip the rest of the code nextNum = prevNum + currNum
inside the loop for the current iteration and move on to the print(nextNum, end=", ")
next iteration.
prevNum, currNum = currNum, nextNum

Example:
Q .Write a Python program to check whether number is
for i in range(1, 6):
armstrong or not .
if i == 3:
# Input from the user
continue
n = int(input("Enter a number to check for
print(i)
Armstrong: "))

Q. WAP for these patterns : order = len(str(n))


**** * *** * + temp = n
**** ** *** ++ sum = 0
**** *** ** +++ while temp > 0:
**** **** * ++++ digit = temp % 10
sum += digit ** order
temp //= 10
1. for i in range(0, 4): 2.for i in range(0, 4):
# Print asterisks # Print asterisks
# Check and print the result
for j in range(0,4): for j in range(0,i+1):
if (sum==num):
print("*", end=" ") print("*", end=" ")
print("number is an Armstrong number.")
print() print()
else:
print( "number is not an Armstrong
3.for i in range(0, 4): 4.for i in range(0, 4): number.")
# Print asterisks # Print spaces
for j in range(i, 3):
for j in range(i,4 ): print(" ", end=" ") Q . What will be the output after the following
print("*", end=" ") # Print plus statements ?
print() for j in range(0,i+1 ): x = ['P', 'y', 't', 'h', 'o', 'n']
print("+", end=" ") for i in x:
print() print(i, end=' ')

Q . Write a Python program to print multiplication table


and input take from the user
# Input from the user
num = int(input("Enter the number for multiplication table: "))

# Print the multiplication table


print(f"Multiplication Table for {num}:")
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
ENGINEERING
THANKS FOR VISITING

COLLEGE HUB
“The Engineer Has Been, And Is, A Maker Of History.”
- By ”lovely Engineer”

Click
Scan For
to learn Join
more aboutAll
the Feelings Monster in
Group
the Directly
Reflect app.
Author : DSALGO
string list
 A string is a sequence of characters in Python.  list is a mutable, ordered collection of element.
 Formed by enclosing characters in quotes.  Lists are one of the most versatile & widely used data types in
 Python treats single and double quotes equally. Python.
 Strings are literal or scalar, treated as a single value in Python
 Python treats strings as a single data type. Here are some key characteristics of lists:
 Allows easy access and manipulation of string parts.
:
 Example :
my_list = [1, 2, 3, "hello", True]
str1 = 'Hello World'
str2 = "My name is khan"
String manipulation in Python
1.Concatenation: Joining two or more strings together. first_element = my_list[0] # Accessing the first elementssing the first
result = str1 + " " + str2 element
print(result) # Output: "Hello World My name is khan"

2.String Formatting: Creating formatted strings with placeholders or sublist = my_list[1:4] # Extracting elements from index 1 to 3
f-strings.
fstr = f"{str1} and {str2}"
print(fstr) my_list[0] = 100 # Modifying an element
3.String Methods: Using built-in string methods to manipulate strings. my_list.append(5) # Adding an element to the end
u_str = str1.upper() #HELLO WORLD my_list.remove("hello") # Removing an element
l_str = str1.lower() # hello world
r_str =str2.replace("khan ", "singh")#my name is singh
length_of_list = len(my_list)
4.Splitting and Joining: Splitting a string into a list of substrings based
on a delimiter, and joining a list of strings into a single string.
splitlist = str1.split("") #['Hello','World'] my_list.sort() # Sorts the list in ascending order
joinlist = "-".join(splitlist) # Hello – World my_list.reverse() # Reverses the list
5.Stripping: Removing leading and trailing whitespace characters
from a string.
my_string = " Hello World " copy() method in list :
stripped_str = my_string.strip() original_list = [1, 2, 3, 4, 5]
print(stripped_str) # Output: "Hello World" copied_list1 = original_list.copy() #method 1
print(copied_list1)
6.Searching: Finding substrings within a string. copied_list2 = list(original_list) # method 2
string = "the quick brown fox jumps over the lazy dog" print(copied_list2)
is_dog = "dog" in string #bool:true or false copied_list3 = original_list[:] # method 3
index =string.find("fox") #return first occurance index print(copied_list3)

Delete element in list


slicing string manipulation : my_list = [1, 2, 3, 4, 5]
 string slicing is a technique used to extract a portion of a string del my_list[2] # Removes the element at index 2
by specifying a range of indices. print(my_list) #[1, 2, 4, 5]
 Syntax : my_list = [1, 2, 3, 4, 5]
string[start:stop:step]
my_list.remove(3) # Removes the first occurrence of the value 3
 Example:
print(my_list) #[1, 2, 4, 5]
# Basic slicing
my_list = [1, 2, 3, 4, 5]
substring1 = text[7:10] # Extracts "is"
popped_element = my_list.pop(2) # Removes and returns the
substring2 = text[0:6] # Extracts "Python"
element at index 2
# Omitting start or stop
print(my_list) # [1, 2, 4, 5]
substring3 = text[:6] # Extracts "Python"
my_list = [1, 2, 3, 4, 5]
substring4 = text[7:] # Extracts "is amazing"
my_list[1:3] = [] # Deletes elements at indices 1 and 2
# Using negative indices
print(my_list) #[1, 4, 5]
substring5 = text[-7:-1] # Extracts "amazin"
my_list = [1, 2, 3, 4, 5]
# Slicing with step
my_list.clear() # Removes all elements from the list
substring6 = text[0:15:2] # Extracts "Pto saa"
print(my_list) # []
# Reverse a string
substring7 = text[::-1] # Extracts "gnizama si nohtyP"
Built-in operator in python :  Program :
# Defining sets
list1 = [1, 2, 3] set1 = set([1, 2, 4, 1, 2, 8, 5, 4])
set2 = set([1, 9, 3, 2, 5])
list2 = [4, 5, 6]
# Printing sets
result_list = list1 + list2 # Concatenates the lists
print(set1) # Output: {1, 2, 4, 5, 8}
print(set2) # Output: {1, 2, 3, 5, 9}
repeated_string = "abc" * 3 # Repeats the string three times # Intersection of set1 and set2
repeated_list = [1, 2] * 4 # Repeats the list four times intersection = set1 & set2
print(intersection) # Output: {1, 2, 5}
string_check = "lo" in "Hello" # Checks if "lo" is in "Hello" (True)
# Union of set1 and set2
list_check = 3 in [1, 2, 3, 4] # Checks if 3 is in the list (True)
union = set1 | set2
tuple print(union) # Output: {1, 2, 3, 4, 5, 8, 9}
 tuple is an ordered, immutable collection of elements.
 once a tuple is created, its elements cannot be modified or # Difference of set1 and set2
changed. difference = set1 - set2
 Tuples are defined using parentheses () and can contain print(difference) # Output: {4, 8}
elements of different data types.
 Program :
# Symmetric difference of set1 and set2
my_tuple = (1, 2, 3, 'hello', True) # tuple creation
symm_diff = set1 ^ set2
first_element = my_tuple[0] #Accessing Elements
print(symm_diff) # Output: {3, 4, 8, 9}
my_tuple[0] = 100 # This will raise an error
packed_tuple = 1, 'apple', 3.14 #Tuple Packing
x, y, z = packed_tuple #Unpacking
Functions
 Functions are self-contained units designed for specific tasks.
length = len(my_tuple) Length of Tuple  Once created, functions can be called as needed.
combined_tuple = (1, 2, 3) + ('a', 'b', 'c') #Tuple Concatenation  Functions have names and may or may not return values.
count_of_2 = my_tuple.count(2) #output : 1  Python offers built-in functions like dir(), len(), abs(), etc.
index_of_hello = my_tuple.index('hello') #output: 3  Users can define custom functions for specific requirements.
 We will use the def keyword to define functions

Dictionary
 dictionary is a mutable, unordered collection of key-value pairs. Why do we use functions :(advantges)
 Each key in a dictionary must be unique, and it is associated with 1.Reusability 2. Readability,
a specific value. 3.Maintainability 4. Scoping
 Dictionaries are defined using curly braces {} and consist of key-
value pairs separated by commas. Syntax:
 Here are some key points about dictionaries:
 Creating a Dictionary: # define the function_name
 my_dict = {'name': 'John', 'age': 25, 'city': 'New York'} def function_name():
 Accessing Values:
# Code inside the function
name = my_dict['name']
age = my_dict['age'] # Optionally, return a value
 Modifying Values:
my_dict['age'] = 26 #call the function_name
 Adding New Key-Value Pairs: Function_name()
my_dict['gender'] = 'Male'
 Removing Key-Value Pairs: Example function without parameters
del my_dict['city']
def greet():
 Checking Key Existence:
print("Hello, World!")
is_name_present = 'name' in my_dict
 Dictionary Methods: greet() # Calling the greet function
keys = my_dict.keys() Example function with parameters
values = my_dict.values() def add_numbers(a, b):
items = my_dict.items() return a + b
Set
 set is an unordered and mutable collection of unique elements. # Calling the add_numbers function
 Sets are defined using curly braces {} and can contain various result = add_numbers(5, 7)
data types, such as numbers, strings, and other sets. print("Sum:", result)
 Operations performed on sets are union , intersection ,
difference , symmetric difference

Elements of the function
 Keyword: def for function header. #Make a table for selection operation
 Function Name: Identifies uniquely. print("Select operation:")
 Colon: Ends function header. print("1. Add")
 Parameters: Values passed at a defining time , e.g., x and y.
print("2. Subtract")
 Arguments: Values passed at a calling time , e.g., a and b.
 Function Body: Processes arguments. print("3. Multiply")
 Return Statement: Optionally returns a value. print("4. Divide")
 Function Call: Executes the function, e.g., a = max(8, 6). choice = input("Enter choice (1/2/3/4): ")
 Keyword Arguments:Pass values to function by associating num1 = float(input("Enter first number: "))
them with parameter names. num2 = float(input("Enter second number: "))
Syntax : function_name(p1=val1 , p2 =val2)
if choice == '1':
 Default Values: can have default values, making them optional
during function calls.
print(num1, "+", num2, "=", add(num1, num2))
Syntax: def function_name(param1=default_value1, elif choice == '2':
param2=default_value2): print(num1, "-", num2, "=", sub(num1, num2))
scope rules in Python [LEGB rule ] elif choice == '3':
Local: Variables within a function; accessible only within that function. print(num1, "*", num2, "=", mult(num1, num2))
Enclosing: Scope for nested functions; refers to the enclosing elif choice == '4':
function's scope. print(num1, "/", num2, "=", div(num1, num2))
Global: Variables at the top level of a module or declared global else:
within a function; accessible throughout the module.
print("Invalid input. Please enter a valid choice.")
Builtin: Outermost scope containing built-in names like print(), sum(),
etc.; available everywhere.
Q. Write a function in find the HCF of given numbers
# Global scope
global_variable = "I am global" def HCF(num1, num2):
def outer_function(): while num2:
# Enclosing scope num1, num2 = num2, num1 % num2
enclosing_variable = "I am in the enclosing scope" return abs(num1)
def inner_function(): # Example usage:
# Local scope number1 = 24
local_variable = "I am in the local scope" number2 = 36
print(local_variable) result = HCF (number1, number2)
print(enclosing_variable) print(f"The HCF of {number1} and {number2} is {result}")
print(global_variable)
print(len(global_variable)) # Using a built-in function
inner_function()
outer_function()

Output :
I am in the local scope
I am in the enclosing scope
I am global
10

Q . make a calculator using function inpython like sub, add, mult ,


div
# four basic Functions for calculator sub, sum , divide, multiply
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mult(x, y):
return x * y
def div(x, y):
if y != 0:
return x / y
else:
return "Error! Division by zero."
ENGINEERING
THANKS FOR VISITING

COLLEGE HUB
“The Engineer Has Been, And Is, A Maker Of History.”
- By ”lovely Engineer”

Click
Scan For
to learn Join
more aboutAll
the Feelings Monster in
Group
the Directly
Reflect app.
v

Author : DSALGO
 Example:
 File handling in Python refers to the manipulation and file = open('example.txt', 'r')
management of files, lines = file.readline()#read first line of the file
 such as reading from or writing to them. lines = file.readline()#read second line of the file
 Python provides built-in functions and methods to perform
various file operations.
 Reads all lines from the file and returns them as a list of strings.
 Each string in the list represents a single line from the file,
1. opening file 4.file navigation
including the newline character ('\n').
2. Reading file 5.checking file existance
 Useful when you want to iterate over lines in a file or process
3. Writing file
them individually.
 Advantages
 Example:
1. Versatility 2. ease to use 3. portability
file = open('example.txt', 'r')
4. Flexibility 5.integration
 Disadvantages lines = file.readlines() # Reads all lines into a list
1. performance 2.error handling 3. security Risks file.close()
4. Limited File Locking 5. Resource management
Difference b/w read(), readline() , readlines() function:
 readline() when you want to read lines one by one.
 You can use the open() function to open a file.  read() when you want to read a specific number of bytes or the
 It takes two parameters: entire file.
 file path 2. mode[r,w, a]  readlines() when you want to read all lines into a list for further
 syntax: processing.
file = open('filename.txt', 'r')

 After using read(), it's important to close the file using the close()  Writes a string to the file.
method to release system resources  If the file is opened in text mode ('t'), you can only write strings
 syntax: to it.
file.close()  If the file is opened in binary mode ('b'), you can write bytes-like
objects (e.g., bytes or bytearray).
 Examples:
 read() function in Python is used to read data from a file.
 read() function is called on a file object and takes an optional file = open('example.txt', 'w') # Open file in write mode
parameter specifying the number of bytes to read. file.write("Hello, world!") # Write a string to the file
 If no size is specified, it reads the entire file. file.close()
 Syntax:
file_object.read(size) :
 Example 1:  Writes a list of strings to the file.
file = open('example.txt', 'r')  Each string in the list represents a line, and newline characters
data = file.read() # Reads the entire contents ('\n') must be included if needed.
file.close()  Example:
 Example 2: (file cursor) lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file = open('example.txt', 'r') file = open('example.txt', 'w')
data1 = file.read(10) # Reads the first 10 bytes file.writelines(lines) # Write multiple lines to the file
data2 = file.read(10) # Reads the next 10 bytes file.close()
file.close()
 You can use print() function with file parameter to write to file.
 You can also use read() along with splitlines() to read lines from  By default, it adds a newline character ('\n') after each print
the file unless specified otherwise
 Example:  Example:
file = open('example.txt', 'r') file = open('example.txt', 'w')
lines = file.read().splitlines() # Reads lines from the file into a list print("Hello, world!", file=file) # Write to file using print function
file.close() file.close()

 If you want to append data to an existing file without


 Reads a single line from the file. overwriting its contents, open it in append mode ('a') instead of
 Moves the file cursor to the beginning of the next line after write mode ('w').
reading.  Example:
 Returns the line as a string, including the newline character ('\n'), file = open('example.txt', 'a') # Open file in append mode
unless the end of the file is reached, in which case an empty file.write("Appending new content!") # Append to the file
string is returned. file.close()
# Example usage:
 You can use the with statement to automatically close the file source_file = input("Enter the source file name: ")
after writing, ensuring proper resource management destination_file = input("Enter the destination file name: ")
 Examples:
with open('example.txt', 'w') as file: #function call
file.write("Using 'with' statement for file writing.") copy_file(source_file, destination_file)

with open('filename.txt', 'r') as file: Q.Develop a Python program that reads a text file and prints the
content = file.read() longest line along with its length
# File automatically closed after this block def longest_line(file_name):
try:
with open(file_name, 'r') as file:
 Manipulating the file pointer using the seek() function in Python lines = file.readlines()
allows you to move the cursor position within the file longest_length = 0
 Examples: longest_line = ""
# Open a file in read mode
with open('example.txt', 'r') as file: for line in lines:
# Read the first 10 bytes line_length = len(line.strip())
data1 = file.read(10) if line_length > longest_length:
longest_length = line_length
# Get the current cursor position
longest_line = line.strip()
position = file.tell()
print("Current position:", position) print(f"The longest line is: '{longest_line}'")
print(f"Its length is: {longest_length} characters")
# Move the cursor to the beginning of the file
except FileNotFoundError:
file.seek(0)
print(f"File '{file_name}' not found.")
# Read the next 20 bytes from the beginning of the file
except Exception as e:
data2 = file.read(20)
print(f"An error occurred: {e}")

# Print the read data


Q.Write a Python program to search for a specific string in a text file
print("Data 1:", data1)
and print out the line(s) where it occurs.
print("Data 2:", data2)
# Example usage:
file_name = input("Enter the file name: ")

Description : longest_line(file_name)
 We open a file named example.txt in read mode. def search_string_in_file(file_name, search_string):
 We use read(10) to read the first 10 bytes from the file. try:
 We use tell() to get the current cursor position. with open(file_name, 'r') as file:
 We use seek(0) to move the cursor back to the beginning of the
for line_number, line in enumerate(file, 1):
file.
 We use read(20) to read the next 20 bytes from the beginning of if search_string in line:
the file. print(f"Found '{search_string}' in line {line_number}:
 Finally, we print the read data. {line.strip()}")
except FileNotFoundError:
Q. Create a Python program that reads the content of a source file
and writes it to a destination file. print(f"File '{file_name}' not found.")
def copy_file(source_file, destination_file): except Exception as e:
try: print(f"An error occurred: {e}")
with open(source_file, 'r') as source:
with open(destination_file, 'w') as destination: # Example usage:
for line in source: file_name = input("Enter the file name: ")
destination.write(line) search_string = input("Enter the string to search: ")
print(f"Content copied from '{source_file}' to '{destination_file}'
search_string_in_file(file_name, search_string)
successfully.")
except FileNotFoundError: Q.Write a Python program to read a text file and count the total
print("One of the files could not be found.") number of words in it.
except Exception as e: Q.Design a Python program that encrypts the contents of a file using
a simple substitution cipher and then decrypts it back to its original
print(f"An error occurred: {e}")
form.
ENGINEERING
THANKS FOR VISITING

COLLEGE HUB
“The Engineer Has Been, And Is, A Maker Of History.”
- By ”lovely Engineer”

Click
Scan For
to learn Join
more aboutAll
the Feelings Monster in
Group
the Directly
Reflect app.
PYTHON UNIT 5
Abhay Kumar Singh
www.abhaysingh722@gmail.com
 NumPy is a powerful library for numerical computing in import numpy as np
Python,
 it provides a wide range of built-in functions for various # Create a NumPy array
mathematical operations. arr = np.array([1, 2, 3, 4, 5])

# Perform statistical operations


print("Standard Deviation:", np.std(arr))
print("Variance:", np.var(arr))
print("Median:", np.median(arr))
print("Percentile (50th):", np.percentile(arr, 50))

output:
Standard Deviation: 1.4142135623730951
Variance: 2.0
Median: 3.0
Percentile (50th): 3.0
# importing the numpy module
import numpy as np
# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5]) import numpy as np
# Print the array # Define two matrices
print("Original Array:", arr) matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
# Perform some basic operations
print("Sum of Array Elements:", np.sum(arr)) # Perform matrix multiplication
print("Mean of Array Elements:", np.mean(arr)) result = np.dot(matrix1, matrix2)
print("Maximum Element in Array:", np.max(arr)) print("Matrix Multiplication Result:")
print("Minimum Element in Array:", np.min(arr)) print(result)
# Reshape the array
reshaped_arr = arr.reshape(1, 5) # Compute matrix determinant
print("Reshaped Array:", reshaped_arr) det = np.linalg.det(matrix1)
print("Determinant of Matrix1:", det)
output:
Original Array: [1 2 3 4 5] # Compute matrix inverse
Sum of Array Elements: 15 inverse = np.linalg.inv(matrix1)
Mean of Array Elements: 3.0
print("Inverse of Matrix1:")
Maximum Element in Array: 5
Minimum Element in Array: 1 print(inverse)
Reshaped Array: [[1 2 3 4 5]]
output:
Matrix Multiplication Result:
[[19 22]
import numpy as np [43 50]]
Determinant of Matrix1: -2.0000000000000004
# Create two NumPy arrays
Inverse of Matrix1:
arr1 = np.array([1, 2, 3]) [[-2. 1. ]
arr2 = np.array([4, 5, 6]) [ 1.5 -0.5]]

# Perform array operations


print("Element-wise Sum:", np.add(arr1, arr2))
print("Element-wise Subtraction:", np.subtract(arr1, arr2))
print("Element-wise Multiplication:", np.multiply(arr1, arr2))
 Pandas is a powerful library for data manipulation and
print("Element-wise Division:", np.divide(arr1, arr2))
analysis in Python.
output:  It provides data structures like DataFrame and Series, as
Element-wise Sum: [5 7 9] well as functions to manipulate and analyze them
Element-wise Subtraction: [-3 -3 -3] efficiently.
Element-wise Multiplication: [ 4 10 18]
Element-wise Division: [0.25 0.4 0.5 ]
2 Charlie 35 Chicago Male
import pandas as pd 3 David 40 Houston Male
# Creating a DataFrame from a dictionary
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'], import pandas as pd
'Age': [25, 30, 35, 40], # Reading data from a CSV file
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']} df = pd.read_csv('data.csv')
df = pd.DataFrame(data) # Display the DataFrame
print("DataFrame read from CSV:")
# Display the DataFrame print(df)
print("DataFrame:")
# Writing data to a CSV file
print(df)
df.to_csv('output.csv', index=False)
print("DataFrame written to CSV.")
output:
DataFrame:
output:
Name Age City
DataFrame read from CSV:
0 Alice 25 New York
Name Age City
1 Bob 30 Los Angeles
0 Alice 25 New York
2 Charlie 35 Chicago
1 Bob 30 Los Angeles
3 David 40 Houston
2 Charlie 35 Chicago
3 David 40 Houston
# Accessing specific columns DataFrame written to CSV.
print("\nAccessing 'Name' column:")
print(df['Name'])
output:
import pandas as pd
DataFrame: # Creating a DataFrame
Name Age City data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
0 Alice 25 New York 'Age': [25, 30, 35, 40],
1 Bob 30 Los Angeles 'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']}
2 Charlie 35 Chicago
df = pd.DataFrame(data)
3 David 40 Houston
# Descriptive statistics
print("Descriptive statistics:")
# Accessing specific rows
print(df.describe())
print("\nAccessing first row:")
print(df.iloc[0])
output:
output: Descriptive statistics:
Accessing first row: Age
Name Alice count 4.000000
Age 25 mean 32.500000
City New York std 6.454972
Name: 0, dtype: object min 25.000000
25% 28.750000
# Adding a new column 50% 32.500000
df['Gender'] = ['Female', 'Male', 'Male', 'Male'] 75% 36.250000
print("\nDataFrame after adding 'Gender' column:") max 40.000000
print(df)
output: # Grouping
DataFrame after adding 'Gender' column: print("\nMean age by city:")
Name Age City Gender print(df.groupby('City')['Age'].mean())
0 Alice 25 New York Female
1 Bob 30 Los Angeles Male output:
2 Charlie 35 Chicago Male Mean age by city:
3 David 40 Houston Male City
Chicago 35.0
# Filtering rows based on a condition Houston 40.0
print("\nRows where Age > 30:") Los Angeles 30.0
New York 25.0
print(df[df['Age'] > 30])
Name: Age, dtype: float64
output:
Rows where Age > 30:
Name Age City Gender
 Matplotlib is a comprehensive library for creating static,
animated, and interactive visualizations in Python.
 You can use the keyword argument marker to emphasize
 Matplotlib makes easy things easy and hard things
each point with a specified marker
possible.
 Create publication quality plots.
 Make interactive figures that can zoom, pan, update. import matplotlib.pyplot as plt
import matplotlib import numpy as np
y1 = np.array([3, 8, 1, 10])
y2 = np.array([6, 2, 7, 11])
plt.plot(y1)
Most of the Matplotlib utilities lies under plt.plot(y2)
the pyplot submodule, and are usually imported under
the plt alias
import matplotlib.pyplot as plt

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125]) plt.show()
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.plot(x, y)

plt.title("Sports Watch Data") import matplotlib.pyplot as plt


plt.xlabel("Average Pulse") import numpy as np
plt.ylabel("Calorie Burnage")
#plot 1:
plt.show() x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)

#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x,y)

plt.show()
import matplotlib.pyplot as plt plt.subplot(1, 2, 1)
import numpy as np
#the figure has 1 row, 2 columns, and this plot is the first plot.
xpoints = np.array([1, 2, 6, 8]) plt.subplot(1, 2, 2)
ypoints = np.array([3, 8, 1, 10]) #the figure has 1 row, 2 columns, and this plot is the second plot.
plt.plot(xpoints, ypoints)
plt.show()
7.scatterplot
import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
plt.show()

 With Pyplot, you can use the pie() function to draw pie
charts:
import matplotlib.pyplot as plt
import numpy as np

y = np.array([35, 25, 25, 15])


import matplotlib.pyplot as plt mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
import numpy as np
plt.pie(y, labels = mylabels)
x = np.array(["A", "B", "C", "D"]) plt.show()
y = np.array([3, 8, 1, 10])

plt.bar(x,y)
plt.show()

1.Draw a line in a diagram from position (1, 3) to (2, 8) then to


(6, 1) and finally to position (8, 10):

2.Draw a line in a diagram from position (0,0) to position


 histogram represents data provided in the form of some (6,250)
groups.
 It is an accurate method for the graphical representation of
numerical data distribution.
 GUI programming involves creating visual interfaces for
import matplotlib.pyplot as plt user interaction.
import numpy as np  It utilizes graphical elements like windows, buttons,
menus, and textboxes.
# Generate random data for the histogram  Users interact with applications through these graphical
data = np.random.randn(1000)
# Plotting a basic histogram
components.
plt.hist(data, bins=30, color='skyblue', edgecolor='black')  Libraries or frameworks are used to design and implement
GUIs.
# Adding labels and title  GUIs provide a more intuitive and user-friendly way to
plt.xlabel('Values') interact with software.
plt.ylabel('Frequency')
 They are used in desktop applications, mobile apps, games,
plt.title('Basic Histogram')
# Display the plot and data visualization tools.
plt.show()  GUI programming enhances the user experience and
accessibility of software.
 It is essential for creating visually appealing and interactive def get_entry_text():
applications. print(entry.get())

root = tk.Tk()
 Tkinter is Python's built-in GUI toolkit for creating desktop entry = tk.Entry(root)
applications. entry.pack()
 It offers a wide range of GUI widgets such as buttons, button = tk.Button(root, text="Get Text", command=get_entry_text)
button.pack()
labels, and textboxes.
root.mainloop()
 GUI elements are arranged using layout managers like
pack, grid, and place.
 Tkinter follows an event-driven programming paradigm,
 Text: Multi-line text entry field for longer text input or
responding to user actions with specific functions.
display.
 It allows customization of widget appearance and
behavior. import tkinter as tk
 Tkinter applications are highly portable across various
operating systems. def get_text_content():
 Suitable for small to medium-sized GUI projects and rapid print(text.get("1.0", "end-1c"))
prototyping.
 Comprehensive documentation and community support root = tk.Tk()
are available. text = tk.Text(root)
 While Tkinter is sufficient for many applications, more text.pack()
advanced libraries like PyQt and wxPython offer additional button = tk.Button(root, text="Get Text",
features and scalability for larger projects. command=get_text_content)
button.pack()
root.mainloop()

:A button that triggers an action when


 Checkbutton: Checkbox widget that allows users to select
pressed.
or deselect an option.
import tkinter as tk

import tkinter as tk
def button_clicked():
print("Button clicked!")
root = tk.Tk()
var = tk.IntVar()
root = tk.Tk()
checkbutton = tk.Checkbutton(root, text="Check me",
button = tk.Button(root, text="Click Me", command=button_clicked)
variable=var)
button.pack()
checkbutton.pack()
root.mainloop()
root.mainloop()

: text or image that provides information or  : Group of radio buttons where only one
instructions to the user. option can be selected at a time.

import tkinter as tk import tkinter as tk

root = tk.Tk() root = tk.Tk()


label = tk.Label(root, text="Hello, Tkinter!") var = tk.StringVar()
label.pack() radiobutton1 = tk.Radiobutton(root, text="Option 1",
root.mainloop() variable=var, value="Option 1")
radiobutton2 = tk.Radiobutton(root, text="Option 2",
variable=var, value="Option 2")
 Entry: Single-line text entry field where users can input radiobutton1.pack()
text or numbers. radiobutton2.pack()
root.mainloop()

import tkinter as tk  Widget for displaying a list of items from which


users can select one or more.
import tkinter as tk edit_menu.add_command(label="Copy",
command=menu_command)
root = tk.Tk() edit_menu.add_command(label="Paste",
listbox = tk.Listbox(root) command=menu_command)
for item in ["Item 1", "Item 2", "Item 3"]:
listbox.insert(tk.END, item) # Add the edit menu to the menu bar
listbox.pack() menu_bar.add_cascade(label="Edit", menu=edit_menu)
root.mainloop() # Display the menu bar
root.config(menu=menu_bar)

 Container widget used to organize and group other


root.mainloop()
widgets together.

import tkinter as tk
root = tk.Tk()
root.title("Frame Example")

# Create a frame
frame = tk.Frame(root, width=200, height=100, bg="lightblue")
frame.pack()

# Add widgets to the frame


label = tk.Label(frame, text="This is a frame", font=("Arial", 18))
label.pack(pady=10)

button = tk.Button(frame, text="Click Me", command=lambda:


print("Button clicked!"))
button.pack()

root.mainloop()

 : Menu bar, dropdown menus, and context menus


for creating menu-driven interfaces.

import tkinter as tk
def menu_command():
print("Menu command executed")
root = tk.Tk()
# Create a menu
menu_bar = tk.Menu(root)

# Create a file menu


file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="New",
command=menu_command)
file_menu.add_command(label="Open",
command=menu_command)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)

# Add the file menu to the menu bar


menu_bar.add_cascade(label="File", menu=file_menu)

# Create an edit menu


edit_menu = tk.Menu(menu_bar, tearoff=0)
edit_menu.add_command(label="Cut",
command=menu_command)
ENGINEERING
THANKS FOR VISITING

COLLEGE HUB
“The Engineer Has Been, And Is, A Maker Of History.”
- By ”lovely Engineer”

Click
Scan For
to learn Join
more aboutAll
the Feelings Monster in
Group
the Directly
Reflect app.

You might also like