Introduction to Python PDF
Document Details
Uploaded by Deleted User
Harish Suthar
Tags
Summary
This document provides an introduction to the Python programming language, outlining its key features and versions. It highlights the differences between Python 2 and 3, including syntax changes and library improvements. The document also explains Python's uses in areas like web development, data science, and automation.
Full Transcript
Introduction to Python Python is open-source, high-level, dynamically typed, interpreted, object oriented programming language known for its simplicity and readability. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. Its syntax allows programmers t...
Introduction to Python Python is open-source, high-level, dynamically typed, interpreted, object oriented programming language known for its simplicity and readability. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. Its syntax allows programmers to express their concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more efficiently. Versions of Python Python 1.x Released: 1991 Key Features: Basic features like exception handling, functions, and the core data types (lists, dictionaries, etc.) were introduced. Python 2.x Released: 2000 Key Features: Introduced list comprehensions, garbage collection, and the yield statement. Significant libraries and modules were added. Unicode support was introduced but required a 'u' prefix. Division of integers resulted in integer values (e.g., 5/2 = 2). Python 3.x Released: 2008 Key Features: Print Function: The print statement was replaced with a print() function. Integer Division: Division of integers now results in float values (e.g., 5/2 = 2.5). Unicode: All strings are Unicode by default. Iterators: Range and other iterating functions return iterators instead of lists. Library Improvements: Many standard libraries were redesigned and improved. Syntax Changes: Many syntactic features were changed or removed to make the language cleaner and more consistent. Key Differences Between Python 2.x and Python 3.x: Harish Suthar | Unit 1 | Python | BCA Vth J Print Statement: Python 2: print "Hello, World!" Python 3: print("Hello, World!") Integer Division: Python 2: 5 / 2 results in 2 Python 3: 5 / 2 results in 2.5 Unicode Handling: Python 2: Strings are ASCII (American Standard Code for Information Interchange) by default, Unicode strings need a u prefix. Python 3: Strings are Unicode by default. Iterators: Python 2: range(5) returns a list. Python 3: range(5) returns a range object (iterator). Library Changes: Many standard libraries have been renamed or restructured in Python 3. For example, ConfigParser in Python 2 is configparser in Python 3. Syntax Changes: Many deprecated functions and syntax from Python 2 were removed in Python 3. Example: xrange() was removed in favor of range(). Features of Python 1. Easy to Read and Write: Python's syntax is clear and concise, making it an excellent choice for beginners and experienced developers alike. 2. Interpreted Language: Python is executed line by line, which makes debugging easier and code execution simpler. 3. Dynamically Typed: Python does not require explicit declaration of variable types, making it flexible but also necessitating careful variable management. 4. Extensive Standard Library: Python comes with a vast standard library that supports many common programming tasks, such as connecting to web servers, reading and modifying files, and more. 5. Cross-Platform: Python programs can run on various operating systems, including Windows, macOS, and Linux, without needing modification. Harish Suthar | Unit 1 | Python | BCA Vth J 6. Community Support: Python has a large, active community that contributes to an extensive ecosystem of libraries and frameworks, such as Django for web development, NumPy and pandas for data analysis, and TensorFlow for machine learning. 7. High-level - High-level language means readability, simplicity(open source, available for everyone) and abstraction. Common Uses of Python: Web Development: Frameworks like Django, Flask, and Pyramid enable efficient web application development. Data Science and Machine Learning: Libraries like NumPy, pandas, Scikit-learn, and TensorFlow make Python a popular choice for data analysis, visualization, and machine learning. Automation and Scripting: Python is often used for writing scripts to automate repetitive tasks. Software Development: Python can be used to develop standalone applications and prototype software. Game Development: Libraries like Pygame provide tools for game development. Network Programming: Python has robust support for networking, enabling the development of complex network applications. How to Install Python One has to have Python installed on their system in order to start creating Python code. Python is much simpler to learn and programme in. Any plain text editor, such as notepad or notepad++, may be used to create Python programs. To make it easier to create these routines, Harish Suthar | Unit 1 | Python | BCA Vth J one may also utilise an online IDE for Python or even install one on their machine. IDEs offer a variety of tools including a user-friendly code editor, the debugger, compiler, etc. Step 1: Visit the Python Website and Navigate to the Downloads Section First and foremost step is to open a browser and type Python Download or paste link (https://www.python.org/downloads/) Step 2: Choose the Python Version Click on the version you want to download. Click on the download button to download the exe file of Python If in case you want to download the specific version of Python. Then, you can scroll down further below to see different versions from 2 and 3 respectively. Click on download button right next to the version number you want to download. Step 3: Download the Python Installer Once the download is complete, run the installer program. On Windows, it will typically be a.exe file, on macOS, it will be a.pkg file, and on Linux, it will be a.tar.gz file. Install Python on Windows 10 Double-click the executable file, which is downloaded. The following window will open. Click on the Add Path check box, it will set the Python path automatically otherwise you will have to do it explicitly, then click on Install Now. It will start installing Python on Windows. After installation is complete click on Close. Python is installed. Verifying the Python Installation To verify whether the python is installed or not in our system, we have to do the following. Go to "Start" button, and search " cmd ". Then type, " python - - version ". Harish Suthar | Unit 1 | Python | BCA Vth J If python is successfully installed, then we can see the version of the python installed. If not installed, then it will print the error as " 'python' is not recognized as an internal or external command, operable program or batch file. ". Opening IDLE Now go to Windows and type IDLE. The Python Interpreter also called Python Shell will open. The three greater than >>> sign is called the Python command prompt, where we write our program and with a single enter key, it will give results so instantly. Install Python on MacOS To install Python simply open the Terminal app from Application -> Utilities and enter the following command brew install python3 After command processing is complete, Python’s version 3 would be installed on your Mac. To verify the installation enter the following commands in your Terminal app python3 –version Install Python on Linux Most Linux OSs have Python pre-installed. To check if your device is pre-installed with Python or not, just go to the terminal using Ctrl+Alt+T, On every Linux system including the following OS: Ubuntu, Linux Mint, Debian, openSUSE, CentOS, Fedora You will find Python already installed. You can check it using the following command from the terminal $ python --version To check the latest version of Python 3.x.x : $ python3 --version Python Development Environment A Python development environment (PDE) is a combination of a text editor and a Python runtime implementation. The text editor lets you write code, and the runtime implementation executes the code. A Python development environment is a setup that provides the necessary tools and libraries for writing, testing, and running Python programs Harish Suthar | Unit 1 | Python | BCA Vth J A text editor can be as simple as Notepad running on Windows or a more complicated integrated development environment (IDE) with syntax checking, integrated test runner and code highlighting. IDLE: Integrated development and learning environment. (scripting shell) This includes basic packages and concepts of an IDE in addition for learning and educational purpose. Multi-window text editor: this editor offers features like syntax highlighting, indentation. Debugger: helps you find and fix errors in your code by letting you step through the code and examine variables, Cross-platform: works in windows, mac, and linux Python Interpreter: Shell The Python interpreter, also known as the Python shell, is a program that allows users to directly interact with the Python interpreter and execute Python programs, code, or commands. The shell is a command line interface that provides a basic read-eval-print loop (REPL) that reads a Python statement, evaluates the result, and prints it to the screen. The shell then loops back to read the next statement. (after executing the program, we can see ‘>>>’ these arrows again, means ready to take next statement). The Python interpreter translates source code into machine code and runs the resulting program. If an error occurs, the interpreter stops translating the source code and displays an error message. Within a Python shell, the interpreter can run one line of code at a time, which is ideal for experimenting with small code snippets. Most development environments include a Python shell. The Python installer provides two interactive shells: IDLE (Python GUI) and Python (command line) (Interactive shell. Directly type and execute python code line by line.), both of which can be used to run simple programs. Steps performed by python interpreter: Parsing: The Python interpreter reads the source code and checks for syntax errors. It converts the source code into a series of tokens and then generates an Abstract Syntax Tree (AST). Compilation: The interpreter compiles the AST into bytecode. Bytecode is an intermediate, platform-independent representation of the source code. This bytecode is not machine code but a lower-level code that the Python Virtual Machine (PVM) can execute. Execution: The Python Virtual Machine (PVM) reads and executes the bytecode. The PVM interprets the bytecode instructions and translates them into machine-level instructions as needed, but this translation happens at runtime, not ahead of time. Intermediate Files Generated Harish Suthar | Unit 1 | Python | BCA Vth J Bytecode Files: When a Python script is executed, the interpreter compiles the script into bytecode, which is usually stored in.pyc files within the __pycache__ directory. These files are used to speed up future executions of the script by avoiding the need to recompile the source code. Just-In-Time (JIT) Compilation Some implementations of Python, such as PyPy, use Just-In-Time (JIT) compilation to improve performance. JIT compilation translates bytecode into machine code at runtime, allowing frequently executed code to run faster. However, the standard implementation of Python (CPython) does not include a JIT compiler and relies on the PVM to interpret bytecode. Bytecode and the Python Virtual Machine Bytecode: Bytecode is a set of instructions that is similar to assembly language but is platform-independent. It is stored in.pyc files in the __pycache__ directory. {Assembly language is a low-level language that helps to communicate directly with computer hardware. It uses mnemonics to represent the operations that a processor has to do. Which is an intermediate language between high-level languages like C++ and the binary language. It uses hexadecimal and binary values, and it is readable by humans.} Python Virtual Machine (PVM): The PVM is an interpreter that executes the bytecode. It reads the bytecode instructions and translates them into machine-level instructions on the fly. This means the PVM acts as a middle layer between the bytecode and the machine code. It also provides programming environment. Abstract Syntax Tree(AST) An Abstract Syntax Tree (AST) is a tree representation of the abstract syntactic structure of source code. Each node in the tree represents a construct occurring in the source code. The tree reflects the hierarchical structure of the program, showing the syntactic relationships between different parts of the code. Harish Suthar | Unit 1 | Python | BCA Vth J Key Features of AST 1. Abstraction: The AST abstracts away certain details of the source code, such as punctuation (e.g., commas, semicolons) and other tokens that do not affect the structure of the code. 2. Hierarchy: The AST captures the hierarchical structure of the source code, making it easier to analyze and manipulate. 3. Nodes: Each node in the AST represents a construct such as an expression, a statement, or a block of code. Nodes can have children that represent sub-constructs. Execute Python Script When we have completed our python program (with IDLE) we run the program using ‘F5’ key on keyboard. Following steps are done after that: Python Parsing Compilation Execution Code Indentation Indentation in Python is the use of whitespace (spaces or tabs) at the beginning of a line to define the structure and organization of code. Unlike many other programming languages, which use braces or keywords to delimit blocks of code, Python uses indentation levels to indicate the grouping of statements. Key Points About Indentation in Python Block Structure: Indentation is used to define blocks of code. For example, the body of a function, loop, or conditional statement is indented relative to the enclosing statement. Consistency: The amount of indentation must be consistent within a block. Mixing spaces and tabs or using inconsistent levels of indentation will result in an IndentationError. Syntax Requirement: Indentation is not optional in Python; it is a part of the syntax. Incorrect indentation will lead to syntax errors. def greet(name): if name: print(f"Hello, {name}!") else: print("Hello, World!") Indentation Rules Harish Suthar | Unit 1 | Python | BCA Vth J Consistent Indentation: Always use the same number of spaces or a single tab character for each indentation level. The common practice is to use four spaces per indentation level. Avoid Mixing Tabs and Spaces: Mixing tabs and spaces can cause errors and is discouraged. Most code editors have settings to convert tabs to spaces to help maintain consistency. Indentation Levels: Each new block of code is indented one level further than the block it is contained within. Blocks in Python In Python, a block is a group of statements that are executed as a unit. Blocks are defined by their indentation level. Python uses indentation to define the scope of loops, functions, conditionals, and other constructs, making the code structure visually clear and consistent. Types of Blocks in Python Function Blocks Conditional Blocks Loop Blocks Class Blocks Exception Handling Blocks With Statement Blocks (used in file handling) Python Keywords Every language contains words and a set of rules that would make a sentence meaningful. Similarly, in Python programming language, there are a set of predefined words, called Keywords which along with Identifiers will form meaningful sentences when used together. Python keywords cannot be used as the names of variables, functions, and classes. Keywords in Python are reserved words that cannot be used as a variable name, function name, or any other identifier. List of Keywords in Python Keyword Description Keyword Description Keyword Description Represents an and It is a Logical False expression that nonlocal It is a non- Operator will result in not local variable being true. It is used to as finally It is used with not It is a Logical create an alias exceptions Operator name Harish Suthar | Unit 1 | Python | BCA Vth J Keyword Description Keyword Description Keyword Description assert It is used for for It is used to or It is a Logical debugging create Loop Operator pass is used To import when the user break Break out a from pass specific parts of doesn’t Loop a module want any code to execute raise is used It is used to class It is used to global raise to raise declare a define a class exceptions or global variable errors. Skip the next To create a return is used continue iteration of a if Conditional return to end the loop Statement execution Represents an It is used to It is used to def import True expression define the import a that will result Function module in true. It is used to It is used to test del is try Try is used to delete an if two variables handle errors object are equal While Loop is To check if a Conditional used to elif in value is present while statements, execute a in a Tuple, List, same as else-if block of etc. statements with It is used in a Used to create statement is else conditional lambda an anonymous with used in statement function exception handling yield keyword try-except is is used to except None It represents a yield used to handle create a null value these errors generator function How to see keywords in python program: Harish Suthar | Unit 1 | Python | BCA Vth J 1. # importing keyword library which has lists 2. import keyword 3. 4. # displaying the complete list using "kwlist()." 5. print("The set of keywords in this version is: ") 6. print( keyword.kwlist ) Python Variables Python Variable is containers that store values. Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. A Python variable is a name given to a memory location. It is the basic unit of storage in a program. Rules for Python variables A Python variable name must start with a letter or the underscore character. A Python variable name cannot start with a number. A Python variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ). Variable in Python names are case-sensitive (name, Name, and NAME are three different variables). The reserved words(keywords) in Python cannot be used to name the variable in Python. Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of these classes. The following are the standard or built-in data types in Python: Numeric Sequence Type Boolean Set Dictionary To check the data type of any variable we use the type() function. Harish Suthar | Unit 1 | Python | BCA Vth J 1. Numeric Data Types in Python The numeric data type in Python represents the data that has a numeric value. A numeric value can be an integer, a floating number, or even a complex number. These values are defined as Python int, Python float, and Python complex classes in Python. Integers – This value is represented by int class. It contains positive or negative whole numbers (without fractions or decimals). In Python, there is no limit to how long an integer value can be. Float – This value is represented by the float class. It is a real number with a floating-point representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation. Complex Numbers – A complex number is represented by a complex class. It is specified as (real part) + (imaginary part)j. For example – 2+3j 2. Sequence Data Types in Python The sequence Data Type in Python is the ordered collection of similar or different Python data types. Sequences allow storing of multiple values in an organized and efficient fashion. There are several sequence data types of Python: Python String Python List Python Tuple String Data Type Strings in Python are arrays of bytes representing Unicode characters. A string is a collection of one or more characters put in a single quote, double-quote, or triple-quote. In Python, there is no character data type Python, a character is a string of length one. It is represented by str class. Harish Suthar | Unit 1 | Python | BCA Vth J Creating String Strings in Python can be created using single quotes, double quotes, or even triple quotes. Example of accessing string: String1 = "GeeksForGeeks" print("Initial String: ") print(String1) print("\nFirst character of String is: ") print(String1) print("\nLast character of String is: ") print(String1[-1]) List Data Type Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very flexible as the items in a list do not need to be of the same type. Creating a List in Python Lists in Python can be created by just placing the sequence inside the square brackets[]. List = [] print("Initial blank List: ") print(List) List = ['GeeksForGeeks'] print("\nList with the use of String: ") print(List) List = ["Geeks", "For", "Geeks"] print("\nList containing multiple values: ") print(List) print(List) List = [['Geeks', 'For'], ['Geeks']] print("\nMulti-Dimensional List: ") print(List) Tuple Data Type Just like a list, a tuple is also an ordered collection of Python objects. The only difference between a tuple and a list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is represented by a tuple class. Creating a Tuple in Python In Python Data Types, tuples are created by placing a sequence of values separated by a ‘comma’ with or without the use of parentheses for grouping the data sequence. Tuples can contain any number of elements and of any datatype (like strings, integers, lists, etc.). Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple. Tuple1 = () print("Initial empty Tuple: ") print(Tuple1) Harish Suthar | Unit 1 | Python | BCA Vth J Tuple1 = ('Geeks', 'For') print("\nTuple with the use of String: ") print(Tuple1) list1 = [1, 2, 4, 5, 6] print("\nTuple using List: ") print(tuple(list1)) Tuple1 = tuple('Geeks') print("\nTuple with the use of function: ") print(Tuple1) Tuple1 = (0, 1, 2, 3) Tuple2 = ('python', 'geek') Tuple3 = (Tuple1, Tuple2) print("\nTuple with nested tuples: ") print(Tuple3) Boolean Data Type in Python Python Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). However non-Boolean objects can be evaluated in a Boolean context as well and determined to be true or false. It is denoted by the class bool. Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error. x = 10 y = 20 result1 = (x == y) # False, because 10 is not equal to 20 result2 = (x < y) # True, because 10 is less than 20 result3 = (x > y) # False, because 10 is not greater than 20 print(result1) # Output: False print(result2) # Output: True print(result3) # Output: False Set Data Type in Python In Python Data Types, a Set is an unordered collection of data types that is iterable, mutable, and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements. Create a Set in Python Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence inside curly braces, separated by a ‘comma’. The type of elements in a set need not be the same, various mixed-up data type values can also be passed to the set. set1 = set() Harish Suthar | Unit 1 | Python | BCA Vth J print("Initial blank Set: ") print(set1) set1 = set("GeeksForGeeks") print("\nSet with the use of String: ") print(set1) set1 = set(["Geeks", "For", "Geeks"]) print("\nSet with the use of List: ") print(set1) set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks']) print("\nSet with the use of Mixed Values") print(set1) Access Set Items set1 = set(["Geeks", "For", "Geeks"]) print("\nInitial set") print(set1) print("\nElements of set: ") for i in set1: print(i, end=" ") print("Geeks" in set1) Dictionary Data Type in Python A dictionary in Python is an unordered collection of data values, used to store data values like a map, unlike other Python Data Types that hold only a single value as an element, a Dictionary holds a key: value pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon : , whereas each key is separated by a ‘comma’. Create a Dictionary in Python In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable. The dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just placing it in curly braces{}. Note – Dictionary keys are case sensitive, the same name but different cases of Key will be treated distinctly. Dict = {} print("Empty Dictionary: ") print(Dict) Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print("\nDictionary with the use of Integer Keys: ") print(Dict) Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} print("\nDictionary with the use of Mixed Keys: ") print(Dict) Harish Suthar | Unit 1 | Python | BCA Vth J Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'}) print("\nDictionary with the use of dict(): ") print(Dict) Dict = dict([(1, 'Geeks'), (2, 'For')]) print("\nDictionary with each item as a pair: ") print(Dict) Accessing Key-value in Dictionary Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'} print("Accessing a element using key:") print(Dict['name']) print("Accessing a element using get:") print(Dict.get(3)) Input and Print Statement In Python, input and output statements are fundamental for interacting with users and displaying information. Here's an overview: Input Statements The input() function in Python is used to gather user input. It pauses the program's execution and waits for the user to type something. Whatever the user types is then returned as a string. Here’s how it works: Syntax: input(prompt) prompt: A string, representing the text that is displayed to the user. Example: name = input("Enter your name: ") print("Hello, " + name + "!") Output Statements The print() function in Python is used to display output to the console. It can take multiple arguments, and by default, it separates them by a space. Syntax: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) *objects: Any number of objects to be printed. sep: The separator between objects, default is a space. end: The string appended after the last object, default is a newline. file: An object with a write method, default is sys.stdout. flush: A boolean, specifying whether to forcibly flush the stream. Example: print("Hello, World!") print("Hello", "World", sep="-") Harish Suthar | Unit 1 | Python | BCA Vth J print("Hello", end=" ") print("World") In the first print statement, it simply prints "Hello, World!" and moves to the next line. In the second print statement, it prints "Hello-World" using a hyphen as a separator. In the third and fourth print statements, "Hello" and "World" are printed on the same line. Combining Input and Output Often, programs require taking user input and then doing something with it. Here’s a combined example: # Taking input from the user age = input("Enter your age: ") # Displaying the output print("You are " + age + " years old.") In this example, the program takes the user's age as input and then prints a message including the age. Type Conversion Since input() returns a string, you might need to convert it to another type, such as an integer or a float, for mathematical operations. Example: number = input("Enter a number: ") number = int(number) # Convert the input string to an integer print("The square of the number is:", number * number) Arithmetic Operators The Python operators are fundamental for performing mathematical calculations in programming languages like Python, Java, C++, and many others. Arithmetic operators are symbols used to perform mathematical operations on numerical values. In most programming languages, arithmetic operators include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%). Arithmetic Operators in Python There are 7 arithmetic operators in Python. The lists are given below: Operator Description Syntax Addition Operator + Addition: adds two operands x+y Harish Suthar | Unit 1 | Python | BCA Vth J Operator Description Syntax Subtraction Subtraction: subtracts two operands – x–y Operator Multiplication Multiplication: multiplies two operands * x*y Operator Division (float): divides the first operand by Division Operator / the second x/y Floor Division Division (floor): divides the first operand by // the second x // y Operator Modulus: returns the remainder when the Modulus Operator % first operand is divided by the second x%y Exponentiation Power (Exponent): Returns first raised to ** power second x ** y Operator Assignment Operators The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python. Sign Syntax Operators Description Assign the value of the right side of the c=a+ Assignment Operator = expression to the left side operand b Add right side operand with left side Addition Assignment operand and then assign the result to left a += b += Operator operand Subtract right side operand from left side Subtraction Assignment operand and then assign the result to left a -= b -= Operator operand Harish Suthar | Unit 1 | Python | BCA Vth J Sign Syntax Operators Description Multiplication Multiply right operand with left operand and *= a *= b Assignment Operator then assign the result to the left operand Division Assignment Divide left operand with right operand and /= a /= b Operator then assign the result to the left operand Divides the left operand with the right Modulus Assignment operand and then assign the remainder to a %= b %= Operator the left operand Floor Division Divide left operand with right operand and //= a //= b Assignment Operator then assign the value(floor) to left operand Calculate exponent(raise power) value Exponentiation a **= **= using operands and then assign the result Assignment Operator b to left operand Bitwise AND Performs Bitwise AND on operands and &= a &= b Assignment Operator assign the result to left operand Bitwise OR Assignment Performs Bitwise OR on operands and |= a |= b Operator assign the value to left operand Bitwise XOR Performs Bitwise XOR on operands and ^= a ^= b Assignment Operator assign the value to left operand Bitwise Right Shift Performs Bitwise right shift on operands a >>= >>= and assign the result to left operand b Assignment Operator Performs Bitwise left shift on operands and Bitwise Left Shift 7 and x> 10) operand is false Truth Table for Logical Operators in Python a = True b = False result4 = a and b # False, because both a and b need to be True result5 = a or b # True, because at least one of a or b is True result6 = not a # False, because a is True and not inverts it print(result4) # Output: False print(result5) # Output: True print(result6) # Output: False AND Operator in Python The Boolean AND operator returns True if both the operands are True else it returns False. Harish Suthar | Unit 1 | Python | BCA Vth J Python OR Operator The Boolean OR operator returns True if either of the operands is True. Python NOT Operator The Boolean NOT operator works with a single boolean value. If the boolean value is True it returns False and vice-versa. Harish Suthar | Unit 1 | Python | BCA Vth J Membership Operator The Python membership operators test for the membership of an object in a sequence, such as strings, lists, or tuples. Python offers two membership operators to check or validate the membership of a value. They are as follows: Membership Operator Description Syntax Returns True if the value exists in a in Operator value in sequence sequence, else returns False Returns False if the value exists in a value not not in Operator sequence, else returns True in sequence Python IN Operator The in operator is used to check if a character/substring/element exists in a sequence or not. Evaluate to True if it finds the specified element in a sequence otherwise False. # initialized some sequences list1 = [1, 2, 3, 4, 5] str1 = "Hello World" set1 = {1, 2, 3, 4, 5} dict1 = {1: "Geeks", 2:"for", 3:"geeks"} tup1 = (1, 2, 3, 4, 5) # using membership 'in' operator # checking an integer in a list print(2 in list1) # checking a character in a string print('O' in str1) # checking an integer in aset print(6 in set1) # checking for a key in a dictionary print(3 in dict1) # checking for an integer in a tuple print(9 in tup1) Python NOT IN Operator The ‘not in’ Python operator evaluates to true if it does not find the variable in the specified sequence and false otherwise. # initialized some sequences list1 = [1, 2, 3, 4, 5] str1 = "Hello World" set1 = {1, 2, 3, 4, 5} Harish Suthar | Unit 1 | Python | BCA Vth J dict1 = {1: "Geeks", 2:"for", 3:"geeks"} tup1 = (1, 2, 3, 4, 5) # using membership 'not in' operator # checking an integer in a list print(2 not in list1) # checking a character in a string print('O' not in str1) # checking an integer in aset print(6 not in set1) # checking for a key in a dictionary print(3 not in dict1) # checking for an integer in a tuple print(9 not in tup1) Identity Operators The Python Identity Operators are used to compare the objects if both the objects are actually of the same data type and share the same memory location. There are different identity operators such as: Identity Operator Description Syntax Returns True if both objects refers to same memory is Operator obj1 is obj2 location, else returns False is not Returns False if both object refers to same memory obj1 is Operator location, else returns True not obj2 Python IS Operator The is operator evaluates to True if the variables on either side of the operator point to the same object in the memory and false otherwise. # Python program to illustrate the use # of 'is' identity operator num1 = 5 num2 = 5 lst1 = [1, 2, 3] lst2 = [1, 2, 3] lst3 = lst1 str1 = "hello world" str2 = "hello world" # using 'is' identity operator on different datatypes print(num1 is num2) #True print(lst1 is lst2) #False Harish Suthar | Unit 1 | Python | BCA Vth J print(str1 is str2) #True print(str1 is str2) #True We can see here that even though both the lists, i.e., ‘lst1’ and ‘lst2’ have same data, the output is still False. This is because both the lists refers to different objects in the memory. Where as when we assign ‘lst3’ the value of ‘lst1’, it returns True. This is because we are directly giving the reference of ‘lst1’ to ‘lst3’. Python IS NOT Operator The is not operator evaluates True if both variables on the either side of the operator are not the same object in the memory location otherwise it evaluates False. # Python program to illustrate the use # of 'is' identity operator num1 = 5 num2 = 5 lst1 = [1, 2, 3] lst2 = [1, 2, 3] lst3 = lst1 str1 = "hello world" str2 = "hello world" # using 'is not' identity operator on different datatypes print(num1 is not num2) print(lst1 is not lst2) print(str1 is not str2) print(str1 is not str2) Difference between ‘==’ and ‘is’ Operator While comparing objects in Pyhton, the users often gets confused between the Equality operator and Identity ‘is’ operator. The equality operator is used to compare the value of two variables, whereas the identities operator is used to compare the memory location of two variables. # Python program to illustrate the use # of 'is' and '==' operators lst1 = [1, 2, 3] lst2 = [1, 2, 3] # using 'is' and '==' operators print(lst1 is lst2) #False print(lst1 == lst2) #True Slice Function Syntax: slice(start, stop, step) Parameters: Harish Suthar | Unit 1 | Python | BCA Vth J start: Starting index where the slicing of object starts. stop: Ending index where the slicing of object stops. step: It is an optional argument that determines the increment between each index for slicing. Return Type: Returns a sliced object containing elements in the given range only. The slice function in Python is used to create a slice object, which can be used to specify how to slice a sequence (such as a list, tuple, or string). Slicing is a way to extract a portion of a sequence by specifying a start, stop, and step index. s = "Hello, World!" slice_obj = slice(0, 5, 1) print(s[slice_obj]) # Output: Hello Using Slicing Syntax You can achieve the same result with slicing syntax directly: s = "Hello, World!" print(s[0:5:1]) # Output: Hello Negative indexing In Python, negative sequence indexes represent positions from the end of the array. slice() function can also have negative values. In that case, the iteration will be performed backwards i.e. from end to start. numbers = [0, 1, 2, 3, 4, 5] print(numbers[-4:-1]) # Output: [2, 3, 4] Bitwise Operators Python bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into binary and then operations are performed on each bit or corresponding pair of bits, hence the name bitwise operators. The result is then returned in decimal format. Note: Python bitwise operators work only on integers. OPERATOR NAME DESCRIPTION SYNTAX Result bit 1, if both operand Bitwise AND Bitwise & bits are 1; otherwise results bit x&y operator AND 0. Harish Suthar | Unit 1 | Python | BCA Vth J OPERATOR NAME DESCRIPTION SYNTAX Result bit 1, if any of the Bitwise OR Bitwise | operand bit is 1; otherwise x|y operator OR results bit 0. Result bit 1, if any of the Bitwise XOR Bitwise ^ operand bit is 1 but not both, x^y Operator XOR otherwise results bit 0. Bitwise NOT Bitwise ~ Inverts individual bits. ~x Operator NOT The left operand’s value is Python Bitwise >> moved toward right by the x>> Bitwise right shift number of bits Right Shift specified by the right operand. The left operand’s value is Python Bitwise > 1) print("b >> 1 =", b >> 1) Python Bitwise Left Shift Shifts the bits of the number to the left and fills 0 on voids right as a result. Similar effect as of multiplying the number with some power of two. a = 5 b = -10 # print bitwise left shift operator print("a