Python Programming Sem 1 Module 1, 2 PDF

Summary

These notes cover the basics of Python Programming, including its introduction, applications, and development steps. The notes are from ITM Skills University and contain information suitable for an undergraduate-level course.

Full Transcript

COURSE:- Python Programming Sem:- I Module: 1, 2 By: Dr. Ritu Jain, Associate Professor, Computer Science-ISU Engineering Introduction Python is a general purpose programming language conceived in 1989 by Dutch programmer Guido van Rossum while working at N...

COURSE:- Python Programming Sem:- I Module: 1, 2 By: Dr. Ritu Jain, Associate Professor, Computer Science-ISU Engineering Introduction Python is a general purpose programming language conceived in 1989 by Dutch programmer Guido van Rossum while working at National Research Institute at Netherlands. But officially Python was made available to public in 1991. The official Date of Birth for Python is : Feb 20th 1991. Python was named after the BBC TV Show Monty Python's Flying Circus. Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell. Most of syntax in Python Derived from C and ABC language. Created by Dr. Ritu Jain Applications of Python The application areas of python are numerous. Python is used: 1. For developing Desktop Applications 2. For developing Web Applications 3. For developing Database Applications 4. For Network Programming 5. For developing games 6. For Machine Learning and Data Analysis Applications 7. For developing Artificial Intelligence Applications 8. For IOT and many more Created by Dr. Ritu Jain Top Companies using Python Industrial Light and Magic Google Facebook Instagram Spotify Quora Netflix Dropbox Created by Dr. Ritu Jain Reddit and many more Python Python is free and open source language, with development coordinated through the Python Software Foundation. Python is one of the most popular programming languages. Python is an all-purpose programming language that can be used to create desktop applications, 3D graphics, video games, and even websites. It is easy to learn and it's simpler than languages like C, C++, or Java. Python is powerful and robust enough to create advanced applications. This makes Python a good language for students with or without any programming experience. Created by Dr. Ritu Jain Development Steps of Python Guido Van Rossum published the first version of Python code (version 0.9.0) in February 1991. This release included exception handling, functions, and the core data types such as list, dictionary, string and others. It was also object oriented and had a module system. Python version 1.0 was released in January 1994. The major new features included in this release were the functional programming tools such as lambda, map, filter and reduce. Six and a half years later in October 2000, Python 2.0 was introduced. This release included list comprehensions, a full garbage collector and it was supporting Unicode. Python flourished for another 8 years in the versions 2.x before the next major release as Python 3.0 (also known as "Python 3000" and "Py3K") was released. Python 3 is not backwards compatible with Python 2.x. The emphasis in Python 3 had been on the removal of duplicate programming constructs Created by Dr. Ritu Jain and modules. Python 3 version - Python 3.12.6 Official Introduction to Python Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python's elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms. Created by Dr. Ritu Jain Easy to code: Features of Python Python is a high-level programming language. Python is very easy to learn the language as compared to other languages like C, Java, etc. Supports quick development Short Code => Less to type, debug, maintain Readability => Maintainable Free and Open Source: Freeware: Python language is freely available at the official website www.python.org. You don’t have to pay anything for using it. It is open-source, this means that source code is also available to the public. So you can download it, change it, use it, and distribute it. Expressive Python needs to use only a few lines of code to perform complex tasks. For example, to display Hello World, you simply need to type one line - print(“Hello World”). Other languages like Java or C would take up by Created multiple lines to execute this. Dr. Ritu Jain Features of Python Object-Oriented and Procedure-Oriented A programming language is object-oriented if it focuses design around data and objects, rather than functions and logic. On the contrary, a programming language is procedure-oriented if it focuses more on functions (code that can be reused). One of the critical features of Python is that it supports both object- oriented and procedure-oriented programming. GUI Programming Support: One of the key aspects of any programming language is support for GUI or Graphical User Interface. A user can easily interact with the software using a Created by Dr. Ritu Jain GUI. Python offers various toolkits, which allows for GUI's easy and fast development. Features of Python High-Level Language: Python is a high-level language. When we write programs in python, we do not need to remember the system architecture, nor do we need to manage the memory. Extensible feature: Programs in other languages can be used in python. If performance is very important, so can write code in C, C++ and extend it to python. This makes Python an extensible language, meaning that it can be extended to other languages. Python is Portable language: Python language is also a portable language. For example, if we have python code for windows and if we want to run this code on other platforms such as Linux, Unix, and Mac then we do not need to change it, we can run this code on any platform. Embeddable We just saw that we can put code in other languages in our Python source code. However, it is also possible to put our Python Created code in by aDr.source Ritu code in a different language like C++. Jain This allows us to integrate scripting capabilities into our program of the other language. Features of Python Interpreted Language: Python is an Interpreted Language because Python code is executed line by line at a time. There is no need to compile python code this makes it easier to debug our code. The source code of python is converted into an intermediate form called bytecode. Large Standard Library Python has a large standard library which provides a rich set of module and functions so you do not have to write your own code for every single thing. Dynamically Typed Language: Python is a dynamically-typed language. That means the type (for example- int, double, long, etc.) for a variable is decided at run time not in advance because of this feature we don’t need to specify the type of variable. Created by Dr. Ritu Jain Installation of Python Version: Python 3.12.6 Created by Dr. Ritu Jain Installation of Python Created by Dr. Ritu Jain Choose the following: So now, you can reach Python in the following ways: Terminal: You can run Python on terminal Search for terminal, and type the following: python Now, you can use it as an interpreter. As an example, we have calculated 2+3. Created by Dr. Ritu Jain Executing Python program through Command Prompt Writing Your First Python Program Create a folder “Python_Prg”. You will be storing all your Python programs in this folder. In Notepad type in your python program Save your notepad program with extension.py (eg. try2_notepad.py). In the field Save as type select All Files. Click on Save. Running Your First Program Open command prompt. Go to the folder where you have saved the file. To run the program, type python Hello.py and hit Enter. You should see the line Hello World! Created by Dr. Ritu Jain Python IDLE The IDLE : There are various editors for writing Python code. The easiest way to start writing Python is to use IDLE, an integrated development environment for Python. IDLE comes as part of the standard Python installation package. IDLE is an application, just like any other application on your computer. Start it the same way you would start any other application, e.g., by double-clicking on an icon. Using IDLE you get some help with the syntax; as an example, keywords are displayed in a different color. Open the Applications. Click on IDLE. This will take you to the command prompt for Python. To run a script with multiple lines, write the program in the editor in Python IDLE and save it in the directory that you would use to save all programs. It will be saved as a *.py for example hello.py file. You can run the script Created from by Dr. Ritu Jainterminal by typing python hello.py. Python IDLE Created by Dr. Ritu Jain Click New File. Type: a=2 b=3 print(a+b) Save it as add.py. Click run module: Created by Dr. Ritu Jain nano ~/.bash_profile alias python=python3 Created by Dr. Ritu Jain Python is compiled as well as interpreted Created by Dr. Ritu Jain Keywords Keywords are the reserved words in Python. All the keywords except True, False, and None are in lower case. In your terminal, to check the keywords: Created by Dr. Ritu Jain Identifiers It is a name given to entities like variables, class, functions, etc. Rules for writing identifiers a to z, A to Z , 0 to 9, underscore ( _) are allowed. Variable names can be arbitrarily long. Keywords cannot be used as identifiers. Cannot use special symbols except _. Spaces are not allowed. Identifier should not starts with digit Case-sensitive language. Therefore, count and Count are different. It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter. Good Programming practice Created by Dr. Ritu Jain Variable names should be short but descriptive. Valid and Invalid Variable Names Created by Dr. Ritu Jain Variable A variable comes into existence as a result of assigning a value to it. Unlike in other languages, you don't need to declare it in any special way. If you assign any value to a nonexistent variable, the variable will be automatically created. Eg: a=10 print(a) Created by Dr. Ritu Jain Variables In Python, variables is seen as a labels or tags that is tied to some value. Python considers the values as objects. Thus, Variables provide a way to associate names with objects. For example, the statement a=1 means the value ‘1’ is created first in memory and then a tag by the name ‘a’ is created. Eg: pi = 3 radius = 11 area = pi * (radius**2) radius = 14 It first binds the names pi and radius to different objects of type int. It then binds the name area to a third object of type int. This is depicted in the left panel of Figure. If the program then executes radius = 11, the name radius is rebound to a different object of type int, as shown in the right panel of Figure. Note that this assignment has no effect on the value to which area is bound. It is still bound to the Created by Dr. Ritu Jain object denoted by the expression 3*(11**2). Variable The assignment statement binds a name, on the left-hand side of the operator, to a value, on the right-hand side. In Python, a variable is just a name, nothing more. An assignment statement associates the name to the left of the = symbol with the object denoted by the expression to the right of the =. An object can have one, more than one, or no name associated with it. Dynamic typing: All type checking is done at runtime. No need to declare a variable or give it a type before use. Created by Dr. Ritu Jain Multiple References to a Single Object >>> n = 300 >>> print(n) 300 >>> type(n) # int object >> bin(0X10) Created by Dr. Ritu Jain '0b10000’ Base Conversions oct(): We can use oct() to convert from any base to octal >>> oct(10) Output: '0o12' >>> oct(0B1111) Output: '0o17’ >>> oct(0X123) Output: '0o443' hex(): We can use hex() to convert from any base to hexadecimal Eg: >>> hex(16) Output: ‘0x10’ >>> hex(0B111111) Output: '0x3f' >>> hex(0o77) Output: ‘0x3f' Created by Dr. Ritu Jain int() int() can be used to convert from any base to int. Created by Dr. Ritu Jain int(str_var, base): function to convert a string into integer. str_var: represents string format of a number base: base of the number system to be used for the string. Created by Dr. Ritu Jain float data type Floating point number that contain a decimal point. Eg num =55.56 Floating point number can also be written in exponential form (scientific notation) where we use e or E to represent power of 10. Eg: f=1.2e3 print(f) output: 1200.0 The main advantage of exponential form is we can represent big values in less memory. We can represent int values in decimal, binary, octal and hexadecimal forms. But we can represent float values onlyby by Created using Dr. Ritu Jain decimal form. Complex Data Type complex number is a number that is written in the form of a and b can contain integers or floating point values. J can be lower case or uppercase (i.e a+bj or a+bJ) Eg: 3+5j Created by Dr. Ritu Jain 10+5.5j 0.5+0.1j Complex Data Type Note: Complex data type has some inbuilt attributes to retrieve the real part and imaginary part c=10.5+3.6j c.real==>10.5 c.imag==>3.6 We can use complex type generally in scientific applications and electrical engineering applications. Created by Dr. Ritu Jain Data types Identifying Data Type of Object Syntax : type(object) Eg. type(i) Type Conversion Syntax: datatype(object) Eg. Height = 165.5 Ht = int(Height) type(Height) type (Ht) Created by Dr. Ritu Jain Type Coercion We can convert one type value to another type. This conversion is called Typecasting or Type coercion. The following are various inbuilt functions for type casting. 1. int() 2. float() 3. complex() 4. bool() 5. str() We can convert from any type to int except complex type. If we want to convert str type to int type, compulsory str should contain only integral value complex(x) is used to convert x intoCreated a complex number by Dr. Ritu Jain with real part x and imaginary part zero. complex(x, y) is used to convert x and y into a complex number such that: x will be real part and y as imaginary part. Example: We can convert from any type to int except complex type. Created by Dr. Ritu Jain Type Coercion Few coercions are accepted, but not all types of coercions are possible. Eg1. x = ‘2’ x= int(x) type(x) Eg2. x=“h” type(x) x= int(x) #valueError The int function can take a floating point number or a string, and turn it into an int. For floating point numbers, it discards the decimal portion of the number — a process we call truncation towards zero on the number line. Created by Dr. Ritu Jain Type Casting: int >>> int(123.987) 123 >>> int(10+5j) TypeError: can't convert complex to int >>> int(True) 1 >>> int(False) 0 >>> int("10") 10 >>> int("10.5") ValueError: invalid literal for int() with base 10: '10.5' >>> int("ten") ValueError: invalid literal for int() with base 10: 'ten' >>> int("0B1111") ValueError: invalid literal for int() with base 10: '0B1111' Created by Dr. Ritu Jain Type Coercion Created by Dr. Ritu Jain bool data type We can use this data type to represent Boolean values. The only allowed values for this data type are: True and False Internally Python represents True as 1 and False as 0 Eg1: b=True type(b) Output: bool Eg2: a=10 b=20 c=aFalse 2) bool(1)==>True 3) bool(20)===>True 4) bool(13.5)===>True 5) bool(0.178)==>True 6) bool(0.0)==>False 7) bool(10-2j)==>True 8) bool(0+1.5j)==>True 9) bool(0+0j)==>False 10) bool("True")==>True 11) bool("False")==>True 12) bool("")==>False Created by Dr. Ritu Jain 13) bool(“0”) ===> True Type Casting: float We can use float() function to convert other type values to float type. >>> float(10) >>> float(10+5j) # >>> float(True) >>> float(False) >>> float("10") >>> float("10.5") >>> float("ten") # >>> float("0B1111") # Note: 1. We can convert any type value to float type except complex type. 2. Whenever we are trying to convertCreated str type toRitu by Dr. float Jain type compulsary str should be either integral or floating point literal and should be specified only in base-10. Type Casting: complex() We can use complex() function to convert other types to complex type. complex(x): We can use this function to convert x into complex number with real part x and imaginary part 0. Eg: complex(10) complex(10.5) complex(True) complex(False) complex("10") complex("10.5") complex("ten") # complex(x,y): We can use this method to convert x and y into complex number such that x will be real part and y will be imaginary part. Eg: complex(10,-2) Created by Dr. Ritu Jain complex(True,False) Examples:type casting Complex Created by Dr. Ritu Jain String str represents String data type. A String is a sequence of characters enclosed within single quotes or double quotes. Triple quotes is used for multiline strings. Eg: “”” Python is an General purpose programming language “”” We can also use triple quotes to use single quote or double quote in our String. ''' This is " character''' ' This i " Character ' We can embed one string in another string Created by Dr. Ritu Jain Eg. ‘‘’You know that “String is a basic datatype” ‘’’ String s1 = “You’re looking great today” s2 = ‘You”re looking great today’ s3 =“You\”re looking great today” s4= =‘You’re looking great today’ Syntax Error ! In Python, we can represent char values also by using str type and explicitly char type is not available. A string in Python can contain as many characters as you wish. The only limit is your machine’s memory resources. A string can also be empty. Created by Dr. Ritu Jain String In Python, we can represent char values also by using str type and explicitly char type is not available. Eg: 1) >>> c='a' 2) >>> type(c) 3) Created by Dr. Ritu Jain String Slice means a piece In Python Strings follows zero based index, i.e., index starts from 0 Slicing operator ([], [:]): retrieve a subset of string Syntax: str1[start : end ] Eg. str1 =“HelloWorld” print(str1) print(str1[1:8:2]) Output: elWr The index can be either +ve or -ve. +ve index means forward direction from Left to Right -ve index means backward direction from Right to Left Concatenation operator (+) print(“Hello” + “World”) Repetition operator(*) Created by Dr. Ritu Jain print(“Hello”*3) String >>> s=“Hello" >>> s >>> s >>> s[-1] >>> s >>> s[1:40] >>> s[1:] >>> s[:4] >>> s[:] >>> s*3 Created by Dr. Ritu Jain >>> len(s) String title() displays each word in titlecase, where each word begins with a capital letter. upper(): converts each letter into upper case lower(): converts each letter into lower case Eg. name = "ada lovelace“ print(name.title()) print(name.upper()) print(name.lower()) Created by Dr. Ritu Jain Stripping Whitespace Python can look for extra whitespace on the right and left sides of a string. To ensure that no whitespace exists at the right end of a string, use the rstrip() method. Eg1. favorite_language = ‘ python ' favorite_language.rstrip() Eg2. favorite_language.lstrip() Eg3. favorite_language.strip() In the real world, these stripping functions are used most often to clean up user input before it’s stored in a program. Created by Dr. Ritu Jain String Check it! age = 23 message = "Happy " + age + "rd Birthday!" print(message) Created by Dr. Ritu Jain Type casting:str() str(): We can use this method to convert other type values to str type Eg: >>> str(10) >>> str(10.5) >>> str(10+5j) >>> str(True) Created by Dr. Ritu Jain str data type String are immutable and hence you can not change the individual letters of string. name=‘hello’ name=‘p’ #TypeError: 'str' object does not support item assignment Created by Dr. Ritu Jain List List is an ordered, mutable, heterogenous collection of elements, where duplicates also allowed. Objects of a list are also called as elements or components. List represent a group of values as a single entity where insertion order is preserved duplicates are allowed. heterogeneous objects are allowed can add and remove elements from it Lists are one of Python’s most powerful features. Eg: [11, 22, 33, 44] Created by Dr. Ritu Jain [‘abc’, 10, 10.5] List Elements of a list need not be of same data type. It is enclosed between two square brackets []. Individual elements in the list are separated by commas. Empty List: ls =[] Creating and printing a list ls=[20,5.5,’abc',True,20] print(list) list=[10,20,30,40] print(list) print(list[-1]) print(list[1:3]) list=100 print(list) print(type(list)) Created by Dr. Ritu Jain Tuple an ordered, immutable, heterogenous collection of elements, where duplicates also allowed. Immutable: once created they can’t be modified. So, when you want to have a list of items that cannot change in your program, use tuple. Enclosed between () Creating tuples t1=(10,20,30,40) print(t1) print(type(t1)) t2=(10, 10.5, "abc",True) print(t2) print(t2) Created by Dr. Ritu Jain print(t2[-1]) t2=100 Set Set is an unordered collection of data types that is mutable, and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements. 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. In sets: insertion order is not preserved duplicates are not allowed heterogeneous objects are allowed index concept is not applicable It is mutable collection, but it cannot contain mutable elements Growable in nature Created by Dr. Ritu Jain Set s1={10,20,30} print(s1) s2={10,20,30,10} print(s2) s3={100,0.5,10,200,'abc'} print(s3) print(s3) s1={1,2,(3,4)} print(s1) Created by Dr. Ritu Jain s2={1,2,[3,4]} print(s2) Dictionary Unordered collection of comma separated key-value pairs, within {} Each key is connected to a value, and you can use a key to access the value associated with that key. Mutable type Colon is used to separate key, value pair. Creating a dictionary: Fuel_Type = {“Petrol”: 1, “Diesel”:2, “CNG”:3} Keys are immutable, but values can be modified. Printing the dictionary print(Fuel_type) # {'Petrol': 1, 'Diesel': 2,Dr. Created by 'CNG': Ritu Jain3} print(Fuel_Type[“Petrol”]) #1 Data types List, set, dict are mutable types int, float, bool, string, and tuple are immutable types Created by Dr. Ritu Jain Class tuple None None is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None. Null Vs None in Python None – None is an instance of the NoneType object type. Null – There is no null in Python, we can use None instead of using null values. Example: print(type(None)) var1 = None print(type(var1)) CreatedNone Note: If a function does not return anything, it returns by Dr.inRitu Jain Python. Constants Constants concept is not applicable in Python. But it is convention to use only uppercase characters if we don’t want to change value. Eg. MAX=10 It is just convention but we can change the value. Created by Dr. Ritu Jain Escape characters \n New Line \t Horizontal tab \’ Single quote \” Double quote \\ back slash symbol Created by Dr. Ritu Jain Operators Operator: Symbol that perform some operation on variables. The most elementary goal of an operator is to be part of an expression. Operators by themselves don’t do much Operands: variables on which operations are performed. Types of operators: unary, binary, ternary Operators in python: 1. Arithmetic 2. Relational 3. Logical 4. Assignment Created by Dr. Ritu Jain 5. Bitwise 6. Special operators Arithmetic Operators Arithmetic operators are those operators that allow you to perform arithmetic operations on numeric values Binary Operators: Operator Eg, Result (if a= 10, b=3) Addition (+) a+b 13 Subtraction (-) a-b 7 Multiplication (*) a*b 30 Division (/) (return always float) a/b 3.3333333333333335 Floor Division or Integer a//b 3 Division(//) Modulus (%) a%b 1 Created by Dr. Ritu Jain Exponent (**) a**b 1000 a and b both can be int, float, complex type Unary operators: +,- Arithmetic Operators a = 10.5 b=2 Output a+b 12.5 a-b 8.5 a*b 21.0 a/b 5.25 a//b 5.0 # Floor division always rounds down a%b 0.5 a**b 110.25 #a and b both can be int, float type Note: The result of integer division is always rounded toDr. Created by theRitu nearest Jain integer value that is less than the real (not rounded) result. Arithmetic Operators Division operator (/) always performs floating point arithmetic. Hence it will always returns float value. 10/2==>5.0 10.0/2==>5.0 But Floor division (//) can perform both floating point and integral arithmetic. If arguments are int type then result is int type. If at least one argument is float type then result is float type. 10//2==>5 Created by Dr. Ritu Jain 10.0//2===>5.0 ZeroDivisionError Note: For any number x, x/0 and x%0, x//0 always raises "ZeroDivisionError“ Created by Dr. Ritu Jain Repetition Operator If we use * operator for str type then compulsory one argument should be int and other argument should be str type. 2*“Hello“ Correct “Hello"*2 Correct 2.5*“Hello" O/P: TypeError: can't multiply sequence by non-int of type 'float’ “Hello"*“Hello“ O/P: TypeError: can't multiply sequence by non-int of type 'str' Created by Dr. Ritu Jain Order of Precedence Decreasing Order of Precedence Operators Parentheses () Exponent ** Division, Multiplication, Modulus, Floor division /, *, %, // Addition and Subtraction +, - Created by Dr. Ritu Jain Precedence of Operators x=1 + 2 ** 3 / 4 * 5 print(2*’Yes’ + 3*’!’) print(type(1+5)) print(type(1+5.0)) print(type(1+’5’)) print(type(‘1’+’5’)) print(2+3*5/5) print(3+2**2**3) Created by Dr. Ritu Jain Relational Used to test numerical equalities and inequalities. Operators allow you to compare operands. These operators always return a Boolean value (True or False) Example Operator Meaning Result x=10, y=5 > Greater than x>y True False < Less than x= Greater than or equal to x >= y False =3.0). True print(10 >4) True print(10.5 > 10) True Created by Dr. Ritu Jain Relational Operators (cont’d) Relational operators can be applied on str types also. String comparison in Python takes place character by character. That is, characters in the same positions are compared from both the strings. If the characters fulfill the given comparison condition, it moves to the characters in the next position. Otherwise, it merely returns False. The comparisons are case-sensitive, hence same letters in different letter cases(upper/ lower) will be treated as separate characters If two characters are different, then their Unicode value is compared; the character with the smaller Unicode value is considered to be lower. Uppercase letters are considered lessCreated than small letters. by Dr. Ritu Jain Relational Operators (cont’d) Relational operators on str types: Created by Dr. Ritu Jain Relational Operators (cont’d) Equality operators (== , !=): We can apply these operators for any type even for incompatible types also 10==20 False 10!= 20 True “Hello"==“Hello“ True 10==“Hello“ False 10+1j==10+1j True Relational operator have lower precedence than arithmetic operators a+5 > c-2 corresponds to (a+5) > (c-2) Created by Dr. Ritu Jain Chaining of Relational Operators Relational operators can be chained. If we get all True, then only result will be True, otherwise False Example: x=15 10=2>1 Created by Dr. Ritu Jain Relational Operators (cont’d) Chaining concept is applicable for equality operators. If at least one comparison returns False then the result is False. Otherwise the result is True. 10==20==30==40 False 10==10==10==10 True Created by Dr. Ritu Jain Logical Operators Logical operators can have either of the two types of operands: relational expressions (evaluates to either True or False) or numbers or strings or lists (non boolean values) Example: x =10, y=20, Operator Meaning z =5 and True if both the operands are true ((xTrue not False ==>True Note: If the first expression evaluated to be false while using and operator, then the further expressions are not evaluated. Note: If the first expression evaluated to be True while using or operator, then the Created by Dr. Ritu Jain further expressions are not evaluated. In the case of multiple operators, Python always evaluates the expression from left to right. Logical and operator Logical and operator returns True if both the operands are True else it returns False. Note: If the first expression evaluated toRitu Created by Dr. beJain false while using and operator, then the further expressions are not evaluated. Logical or operator Logical or operator returns True if either of the operands is True. Note: If the first expression evaluated toJain Created by Dr. Ritu be True while using or operator, then the further expressions are not evaluated. Logical not operator Logical not operator work with the single boolean value. If the boolean value is True it returns False and vice-versa. Created by Dr. Ritu Jain Logical Operators When evaluated with logical operators, all the following are considered false: Boolean value False Any value that is numerically zero (0, 0.0, 0.0+0.0j) An empty string An object of a built-in composite data type such as list, tuple, dict, and set which is empty The special value denoted by the Python keyword None Virtually any other object built into Python is regarded as true. Created by Dr. Ritu Jain Logical Operators Rules for non-boolean types when evaluated with logical operators: x and y: if x is evaluates to false return x otherwise return y. If first argument is zero then result is zero otherwise result is y Eg: 10 and 20 ===> 20 0 and 20 ===> 0 201 ==>it will ignore second operand, if first operand is false, even if second operand is syntactically wrong x or y: If x evaluates to True then result is x otherwise result is y 10 or 20 ==> 10 0 or 20 ==> 20 20>10 or “a”+1>1 ==>it will ignore second operand, if first operand is true, even if second operand is syntactically wrong not x: If x is evaluates to False then result is True otherwise False Created by Dr. Ritu Jain not 10 ==>False not 0 ==>True Logical Operators Eg: “Hello” and “Hello World” ==>”Hello World” “” and “Hello” ==>”” “Hello” and “” ==>”” “” or “Hello” ==>“Hello” “Hello" or ""==>”Hello” not”” ==>True not “Hello” ==>False Created by Dr. Ritu Jain Assignment Operators Operator Example Equivalent to also known += as Augmented a+=b Assignment Operators a= a+b -= a-=b a=a-b *= a*=b a=a*b /= a/=b a=a/b //= a//=b a=a//b **= a**=b a=a**b &= a&=b a =a&b |= a|=b a= a|b ^= a^=b a=a^b >>= a>>=b a=a>>b Created by Dr. Ritu Jain >> m = n >>> id(n) 60127840 >>> id(m) 60127840 >>> m = 400 >>> id(m) 60127872 Created by Dr. Ritu Jain Identity Operators We can use identity operators (is, is not) for address comparison. is r1 is r2 returns True if both r1 and r2 are pointing to the same object is not r1 is not r2 returns True if both r1 and r2 are not pointing to the same object NOTE: Use is operator for address comparison where as == operator for content comparison. Created by Dr. Ritu Jain Membership operators We can use Membership operators to check whether the given object present in the given collection.(It may be String,List,Set,Tuple or Dict) in Returns True if the given object present in the specified Collection not in Retruns True if the given object not present in the specified Collection Created by Dr. Ritu Jain Operator Description Associativity () Parentheses left-to-right ** Exponent Operator Precedence and Associativity right-to-left +,-, ~ Unary plus, unary minus, bitwise Not left-to-right * / % Multiplication/division/modulus left-to-right + – Addition/subtraction left-to-right > Bitwise shift left, Bitwise shift right left-to-right < >= Relational greater than/greater than or equal to == != Relational is equal to/is not equal to left-to-right is, is not Identity left-to-right in, not in Membership operators & Bitwise AND left-to-right ^ Bitwise exclusive OR left-to-right | Bitwise inclusive OR left-to-right not Logical NOT right-to-left and Logical AND left-to-right or Logical OR left-to-right = Assignment Created by Dr. Ritu Jain += -= Addition/subtraction assignment *= /= Multiplication/division assignment right-to-left %= &= Modulus/bitwise AND assignment ^= |= Bitwise exclusive/inclusive OR assignment = Bitwise shift left/right assignment

Use Quizgecko on...
Browser
Browser