Docsity

operating system notes, Summaries of Advanced Operating Systems

Toggle sidebar
bg1
Programming in Python
1
Programming in Python
Unit-I
Introduction to Python Programming
Additional Points:
Python Basics: Entering Expressions into the Interactive Shell, The Integer, Floating-Point,
and String Data Types
Entering Expressions into the Interactive Shell:
The Floating-Point Data Type ( float ):
The String Data Type ( str ):
Additional Points:
String Concatenation
Concatenation:
String Replication
Replication:
Storing Values in Variables
Variables:
Dissecting Your Program
Docstring
Python Data Types: In-depth Analysis
Operators
Flow Control
Boolean Values:
Comparison Operators:
Boolean Operators:
Mixing Boolean and Comparison Operators
Elements of Flow Control
Program Execution
Definition:
Steps in Program Execution:
Flow Control Statements
Types of Flow Control Statements:
Importing Modules
Ways to Import Modules:
Standard Library vs. Third-Party Modules:
Ending a Program Early with sys.exit()
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f

Partial preview of the text

Download operating system notes and more Summaries Advanced Operating Systems in PDF only on Docsity!

Programming in Python

Unit-I Introduction to Python Programming Additional Points: Python Basics: Entering Expressions into the Interactive Shell, The Integer, Floating-Point, and String Data Types Entering Expressions into the Interactive Shell: The Integer Data Type ( int ): The Floating-Point Data Type ( float^ ): The String Data Type ( str ): Additional Points: String Concatenation Concatenation: String Replication Replication: Storing Values in Variables Variables: Dissecting Your Program Docstring Python Data Types: In-depth Analysis Operators Flow Control Boolean Values: Comparison Operators: Boolean Operators: Mixing Boolean and Comparison Operators Elements of Flow Control Program Execution Definition: Steps in Program Execution: Flow Control Statements Types of Flow Control Statements: Importing Modules Ways to Import Modules: Standard Library vs. Third-Party Modules: Ending a Program Early with sys.exit()

Unit ๎‚ˆ II Functions Syntax of defining a function with parameters: Example 1๎‚’ Function without Parameters Example 2๎‚’ Function with Parameters Example 3๎‚’ Function with Multiple Parameters Example 4๎‚’ Function with Default Parameters Example 5๎‚’ Function with Keyword Arguments Example 6๎‚’ Function with Variable Number of Arguments Example 7๎‚’ Function with Keyword Arguments and Variable Number of Arguments Return Values and Return Statements The None Value Types of Functions Keyword Arguments print() Function Local and Global Scope Local Scope: Global Scope: The global Statement Exception Handling try-except Blocks Handling Specific Exceptions Raising Exceptions Custom Exception Classes Exception Propagation Handling Exceptions in File Operations Lists The List Data Type Working with Lists Accessing Elements: Slicing: List Methods: Adding Elements: Removing Elements: Searching and Counting: Sorting and Reversing: Augmented Assignment Operators: Methods:

library, making it suitable for various applications, including web development, data analysis, artificial intelligence, and scientific computing.

๎ฒ๎‚” Introduction to Python: History and features of Python. Python philosophy: "Readability counts." Python's role in modern programming paradigms. ๎ณ๎‚” Installing Python: Different distributions: CPython, Anaconda, etc. Installation steps on various operating systems: Windows, macOS, Linux. ๎ด๎‚” Python Interpreter: Understanding the Python interpreter. Interactive mode vs. script mode. ๎ต๎‚” Python Development Environment: IDEs ๎‚Integrated Development Environments): PyCharm, VS Code, Jupyter Notebook, etc. Text editors: Sublime Text, Atom, Vim, etc. Online platforms: Google Colab, Jupyter Online, etc. ๎ถ๎‚” First Python Program: Writing and executing a simple "Hello, World!" program. Understanding the structure of a Python program. ๎ท๎‚” Python Syntax: Indentation: Python's use of whitespace for block delimiters. Comments: Single-line and multi-line comments. Naming conventions: Variables, functions, classes, and modules. ๎ธ๎‚” Data Types in Python: Numeric types: int, float, complex.

Sequence types: list, tuple, range. Text type: str. Boolean type: bool. ๎น๎‚” Variables and Constants: Declaring and initializing variables. Naming rules and conventions. Constants and their significance. ๎บ๎‚” Keywords and Identifiers: Reserved words in Python. Naming rules for identifiers. Best practices for choosing meaningful names.

๎ฒ๎ฑ๎‚” Basic Input and Output:

Using input() function for user input. Printing output using print() function. Formatting output with f-strings and format() method.

Additional Points:

Python Versions: Python has two major versions in use today: Python 2.x and Python 3.x. Python 3.x is the current version and recommended for new development due to its many improvements over Python 2.x. Community and Resources: Python has a vast and active community with abundant resources, including documentation, tutorials, forums, and libraries. Zen of Python: A set of guiding principles for writing computer programs in Python. Accessible via import this. Dynamic Typing: Python is dynamically typed, meaning you don't need to declare variable types explicitly. Interoperability: Python can be easily integrated with other languages like C/C๎‚๎‚, Java, and .NET.

Python uses the (^) float data type to represent floating-point numbers. Floating-point numbers can also be expressed in scientific notation, e.g., 6.022e (^). Arithmetic operations like addition, subtraction, multiplication, and division can be performed on floating-point numbers.

The String Data Type ( str ):

Strings represent sequences of characters enclosed within single quotes ( ' ) or double quotes ( " ). Examples of strings: (^) 'hello' , (^) "Python" , (^) '123'. Python provides many operations and methods for working with strings, including concatenation ( + ), slicing, indexing, and formatting. Strings can be manipulated in various ways, such as converting case ( upper() , lower() ), finding substrings ( find() , index() ), and replacing ( replace() ). Python also supports raw strings ( r'raw string' ) and multi-line strings ( '''multi-line string''' ).

Example:

Integer

x = 5 print(x) # Output: 5 print(type(x)) # Output:

Floating-point

y = 3. print(y) # Output: 3. print(type(y)) # Output:

String

s = 'hello' print(s) # Output: hello print(type(s)) # Output:

Additional Points:

Python supports other numeric types such as complex numbers ( complex^ ) for working with complex arithmetic. String literals can also be enclosed within triple quotes ( ''' or """ ) to create multi-line strings. In Python, strings are immutable, meaning once created, they cannot be modified. Any operation that appears to modify a string actually creates a new string object. Python provides many built-in functions and methods for performing operations on strings and converting between different data types.

Understanding these fundamental data types is crucial for building more complex Python programs and applications. They form the building blocks upon which more advanced concepts and techniques are built.

String Concatenation

Concatenation:

Definition: Concatenation is the process of combining two or more strings into a single string. Operator: Use the (^) + operator to concatenate strings. Example:

str1 = "Hello" str2 = "World" result_concatenation = str1 + str print("Concatenation:", result_concatenation) # Output: H elloWorld

Understanding string concatenation is essential for combining strings in Python to create meaningful outputs or manipulate text data effectively.

String Replication

Comments: Add comments to explain the purpose or functionality of different parts of your code. Debugging: Use print()^ statements to display intermediate results and debug your program. Indentation: Python uses indentation to define blocks of code, ensuring proper structure and readability. Example:

This is a comment explaining the purpose of the code bel

ow result = x * 2 # Multiply x by 2 and store the result in the variable 'result' print("Result:", result) # Output: 20

To comment multiple lines in Python, you can use triple quotes ( ''' or """ ). While triple quotes are typically used for docstrings, they can also be used as block comments. Here's how you can do it:

''' This is a multi-line comment. It spans across multiple lines. '''

Alternatively, you can use the # character at the beginning of each line to comment multiple lines:

This is a

multi-line comment.

It spans across

multiple lines.

Both methods achieve the same result of commenting out multiple lines of code. The choice between them depends on personal preference and whether you want the comments to be considered docstrings (if using triple quotes).

Here are the major ways to dissect a Python program along with examples:

๎ฒ๎‚” Debugging Tools: Debugging tools like pdb ๎‚Python Debugger) allow you to step through code, set breakpoints, and inspect variables to understand how your program behaves during execution. Example:

import pdb

def divide(x, y): pdb.set_trace() # Set a breakpoint result = x / y return result

divide(10, 2)

When you run this code, the debugger will pause execution at the breakpoint, allowing you to inspect the values of x , y , and result. ๎ณ๎‚” Logging: The (^) logging module allows you to add log messages at different levels (debug, info, warning, error, etc.) to provide insights into the flow of your program and identify issues. Example:

import logging

logging.basicConfig(level=logging.DEBUG) # Set logging le vel logging.debug("This is a debug message") logging.info("This is an info message")

cProfile.run('factorial(10)')

Profiling the (^) factorial() function with (^) cProfile provides information about the number of function calls, execution time, and other performance metrics.

๎ถ๎‚” Static Analysis Tools:

Static analysis tools analyze your code for potential errors, style violations, and type inconsistencies. Example:

pylint myscript.py

Running pylint on your Python script provides feedback on coding standards, potential errors, and areas for improvement.

๎ท๎‚” Unit Testing:

Writing unit tests for your code helps verify that individual components work as expected and catch regressions. Example (using unittest^ ):

import unittest

def divide(x, y): return x / y

class TestDivide(unittest.TestCase): def test_divide(self): self.assertEqual(divide(10, 2), 5) self.assertRaises(ZeroDivisionError, divide, 10,

if name == 'main': unittest.main()

Running the unit test ensures that the (^) divide() function behaves correctly under different conditions. ๎ธ๎‚” Documentation Generation: Documentation generation tools like Sphinx generate documentation from docstrings and other sources in your code. Example:

sphinx-quickstart

Using Sphinx, you can create documentation for your Python project, including explanations, usage examples, and API references.

By leveraging these techniques, you can effectively dissect your Python programs, understand their behavior, identify issues, and ensure their correctness, performance, and maintainability.

Dissecting your program involves understanding its components, including comments, debugging techniques, indentation, and ensuring readability and correctness. This ensures that your code is clear, well-structured, and easy to maintain.

Docstring

In Python, a docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Docstrings are used to document Python code and provide information about what the code does, how it works, and how to use it. They serve as documentation for developers who may need to understand or use the code in the future.

There are two main types of docstrings in Python:

๎ฒ๎‚” Module-Level Docstrings: Module-level docstrings provide an overview of the module's purpose, functionality, and usage. They are enclosed in triple quotes ( ''' or """ ) and appear at the beginning of the module file, before any other code.

Python Data Types: In-depth Analysis

๎ฒ๎‚” Integer ( int ) : Represents whole numbers without any decimal point. Immutable: Integers cannot be modified after creation. Supports arithmetic operations like addition, subtraction, multiplication, and division. Can be converted to other types using type casting. Example: x = 10 ๎ณ๎‚” Float ( float ) : Represents floating-point numbers with decimal points. Immutable: Floats, once created, cannot be altered. May encounter precision issues due to finite floating-point representation. Supports mathematical operations including exponentiation and modulo. Example: pi = 3. ๎ด๎‚” String ( str^ ) : Represents sequences of characters. Immutable: Strings cannot be modified in place. Supports various string manipulation methods like concatenation, slicing, and formatting. Enclosed in single, double, or triple quotes. Supports escape characters for special formatting (\n for newline, \t for tab, etc.). Example: (^) name = "Alice" ๎ต๎‚” Boolean ( bool^ ) : Represents truth values True or False.

Immutable: Booleans cannot be changed after assignment. Often used in conditional statements and boolean operations. Example: is_valid = True

๎ถ๎‚” List ( list ) :

Represents ordered collections of items. Mutable: Lists can be modified by adding, removing, or changing elements. Supports heterogeneous data types within the same list. Allows duplicate elements. Supports slicing and indexing. Example: numbers = [1, 2, 3, 4, 5]

๎ท๎‚” Tuple ( (^) tuple ) :

Represents ordered collections of items. Immutable: Tuples cannot be altered once created. Often used for grouping related data. More memory-efficient compared to lists. Supports unpacking into individual variables. Example: coordinates = (10, 20)

๎ธ๎‚” Dictionary ( dict ) :

Represents collections of key-value pairs. Mutable: Dictionaries can be modified by adding, removing, or updating key-value pairs. Keys must be unique and immutable (e.g., strings, integers). Values can be of any data type, including lists, tuples, or even other dictionaries. Example: person = {"name": "Bob", "age": 30}

print(a % b) # Output: 1 (modulus) print(a ** b) # Output: 1000 (exponentiation)

2. Assignment Operators:

Used to assign values to variables. Includes simple assignment (=), addition assignment (+=), subtraction assignment (-=), multiplication assignment (=), division assignment (/=), modulus assignment ๎‚%๎‚›๎‚‚, exponentiation assignment (*=), floor division assignment (//=).

x = 10 x += 5 # Equivalent to: x = x + 5

3. Comparison Operators:

Used to compare values. Returns True or False based on the comparison. Includes equal to (==), not equal to ๎‚!๎‚›๎‚‚, greater than (>), less than (<), greater than or equal to (>=), less than or equal to (<=).

x = 10 y = 5 print(x > y) # Output: True

4. Logical Operators:

Used to combine conditional statements. Includes logical AND (and), logical OR (or), logical NOT (not).

a = True b = False print(a and b) # Output: False

5. Membership Operators:

Used to test if a sequence is present in an object. Includes in^ and not in^.

sequence = [1, 2, 3, 4, 5] print(3 in sequence) # Output: True

6. Identity Operators:

Used to compare the memory location of two objects. Includes is and is not.

x = [1, 2, 3] y = [1, 2, 3] print(x is y) # Output: False

7. Bitwise Operators:

Used to perform bitwise operations on integers. Includes bitwise AND ๎‚&๎‚‚, bitwise OR ๎‚|๎‚‚, bitwise XOR ๎‚^๎‚‚, bitwise NOT ๎‚๎‚ฃ๎‚‚, left shift (<<), and right shift (>>).

a = 5 # Binary: 101 b = 3 # Binary: 011 print(a & b) # Output: 1 (bitwise AND)

Understanding and mastering these operators is essential for writing efficient and expressive Python code.

Flow Control

Boolean Values:

Definition: Boolean values represent truth values - (^) True or (^) False. Example: