Python Programming E-notes, Lecture notes of Computer Science

it is a Python Programming E-notes

Typology: Lecture notes

2023/2024

Available from 05/31/2024

sandeep-agrawal-1
sandeep-agrawal-1 🇮🇳

1 document

1 / 80

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Python Notes
Sandeep Agrawal
if you are intrusted in one on one classes of Python
Contect me in WhatsAp: +916386469316
What is Python
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for: web development (server-side), software development, mathematics, system scripting.
What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software development.
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is written.
This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.
Python Getting Started
Python Install
Many PCs and Macs will have python already installed.
To check if you have python installed on a Windows PC, search in the start bar for Python or run the
following on the Command Line (cmd.exe):
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

Partial preview of the text

Download Python Programming E-notes and more Lecture notes Computer Science in PDF only on Docsity!

Python Notes

Sandeep Agrawal

if you are intrusted in one on one classes of Python

Contect me in WhatsAp: +916386469316 ¶

What is Python

Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. It is used for: web development (server-side), software development, mathematics, system scripting.

What can Python do?

Python can be used on a server to create web applications. Python can be used alongside software to create workflows. Python can connect to database systems. It can also read and modify files. Python can be used to handle big data and perform complex mathematics. Python can be used for rapid prototyping, or for production-ready software development.

Why Python?

Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). Python has a simple syntax similar to the English language. Python has syntax that allows developers to write programs with fewer lines than some other programming languages. Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. Python can be treated in a procedural way, an object-oriented way or a functional way.

Python Getting Started

Python Install

Many PCs and Macs will have python already installed. To check if you have python installed on a Windows PC, search in the start bar for Python or run the following on the Command Line (cmd.exe):

To check if you have python installed on a Linux or Mac, then on linux open the command line or on Mac open the Terminal and type: In [ ]: If you find that you do not have Python installed on your computer, then you can download it for free from the following website: https://www.python.org/ (https://www.python.org/)

Python Quickstart

Python is an interpreted programming language, this means that as a developer you write Python (.py) files in a text editor and then put those files into the python interpreter to be executed. The way to run a python file is like this on the command line: Where "helloworld.py" is the name of your python file. Let's write our first Python file, called helloworld.py, which can be done in any text editor. In [1]:

Python Indentation

Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. Python uses indentation to indicate a block of code. In [2]: In [3]: Hello, World! Five is greater than two! File "", line 2 print("Five is greater than two!") ^ IndentationError: expected an indented block C:\Users\Your Name>python --version python -- version C:\Users\Your Name>python helloworld.py # helloworld.py print("Hello, World!") if 5 > 2 : print("Five is greater than two!") # Syntax Error: if 5 > 2 : print("Five is greater than two!")

  1. Keywords cannot be used as identifiers. In [7]: We cannot use special symbols like !, @, #, $, % etc. in our identifier. In [8]:

Python Comments

Comments are lines that exist in computer programs that are ignored by compilers and interpreters. Including comments in programs makes code more readable for humans as it provides some information or explanation about what each part of a program is doing. In general, it is a good idea to write comments while you are writing or updating a program as it is easy to forget your thought process later on, and comments written later may be less useful in the long term. In Python, we use the hash (#) symbol to start writing a comment. In [9]:

Multi Line Comments

If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the beginning of each line. In [10]: Another way of doing this is to use triple quotes, either ''' or """. File "", line 1 global = 1 ^ SyntaxError: invalid syntax File "", line 1 a@ = 10 #can't use special symbols as an identifier ^ SyntaxError: invalid syntax Hello, world global = 1 a @ = 10 #can't use special symbols as an identifier #Print Hello, world to console print("Hello, world") #This is a long comment #and it extends #Multiple lines

In [11]:

DocString in python

Docstring is short for documentation string. It is a string that occurs as the first statement in a module, function, class, or method definition. In [13]: In [14]:

Python Indentation

  1. Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python uses indentation.
  2. A code block (body of a function, loop etc.) starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block.
  3. Generally four whitespaces are used for indentation and is preferred over tabs. In [15]: Indentation can be ignored in line continuation. But it's a good idea to always indent. It makes the code more readable. Out[11]: 'This is also a\nperfect example of\nmulti-line comments' 20 function to double the number 0 1 2 3 4 5 6 7 8 9 """This is also a perfect example of multi-line comments""" def double(num): """ function to double the number """ return 2 ***** num print (double( 10 )) print (double.doc) #Docstring is available to us as the attribute doc of t for i in range( 10 ): print (i)

We don't need to declare a variable before using it. In Python, we simply assign a value to a variable and it will exist We don't even have to declare the type of the variable This is handled internally according to

Variable Assignments

In [24]:

Multiple Assignments

In [25]: In [26]:

Storage Locations

In [27]: In [28]: Observation: x and y points to same memory location In [29]:

Data Types

Every value in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.

Numbers

#We use the assignment operator (=) to assign values to a variable a = 10 b = 5. c = "ML" a, b, c = 10 , 5.5, "ML" a = b = c = "AI" #assign the same value to multiple variables at once x = 3 print(id(x)) #print address of variable x y = 3 print(id(y)) #print address of variable y y = 2 print(id(y)) #print address of variable y

Integers, floating point numbers and complex numbers falls under Python numbers category. They are defined as int, float and complex class in Python. We can use the type() function to know which class a variable or a value belongs to and the isinstance() function to check if an object belongs to a particular class. In [30]: In [31]: In [32]:

Boolean

Boolean represents the truth values False and True In [33]:

Python Strings

String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings. Multi-line strings can be denoted using triple quotes, ''' or """. A string in Python consists of a series or sequence of characters - letters, numbers, and special characters. Strings can be indexed - often synonymously called subscripted as well. Similar to C, the first character of a string has the index 0. In [34]: 5 is of type 2.5 is of type (1+2j) is complex number? True

This is Online AI course a = 5 #data type is implicitly set to integer print(a, " is of type", type(a)) a = 2.5 #data type is changed to float print(a, " is of type", type(a)) a = 1 + 2j #data type is changed to complex number print(a, " is complex number?") print(isinstance( 1 + 2j, complex)) a = True #a is a boolean type print(type(a)) s = "This is Online AI course" print(s)

Python Set

Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }. Items in a set are not ordered. In [42]: In [43]: We can perform set operations like union, intersection on two sets. Set have unique values. In [44]: In [45]:

Python Dictionary

Dictionary is an unordered collection of key-value pairs. In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value. Key and value can be of any type. In [48]:

Conversion between Datatypes

We can convert between different data types by using different type conversion functions like int(), float(), str() etc.

{10, 20, 30} --------------------------------------------------------------------------- TypeError Traceback (most recent call last) **** in ----> 1 print ( s [ 1 ]) #we can't print particular element in set because 2 #it's unorder collections of items TypeError : 'set' object is not subscriptable apple a = { 10 , 30 , 20 , 40 , 5 } print(a) print(type(a)) #print type of a s = { 10 , 20 , 20 , 30 , 30 , 30 } print(s) #automatically set won't consider duplicate elements print(s[ 1 ]) #we can't print particular element in set because #it's unorder collections of items d = {'a': "apple", 'b': "bat"} print (d['a'])

In [49]: In [50]: In [51]: Conversion to and from string must contain compatible values. In [52]: In [53]: We can convert one sequence to other In [54]: In [55]:

Python Input and Output

Python Output

Out[49]: 5. Out[50]: (^100) Out[51]: (^) '20' --------------------------------------------------------------------------- ValueError Traceback (most recent call last) **** in ----> 1 int ('10p') ValueError : invalid literal for int() with base 10: '10p' Congratulations, satish! You just wrote 100 lines of code

Out[55]: (^) ['H', 'e', 'l', 'l', 'o'] float( 5 ) #convert interger to float using float() method int(100.5) #convert float to integer using int() method str( 20 ) #convert integer to string int('10p') user = "satish" lines = 100 print("Congratulations, " + user + "! You just wrote " + str(lines) + " lines of c #remove str and gives error a = [ 1 , 2 , 3 ] print(type(a)) #type of a is list s = set(a) #convert list to set using set() method print(type(s)) #now type of s is set list("Hello") #convert String to list using list() method

In [68]:

Operators

Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.

Operator Types

  1. Arithmetic operators
  2. Comparison (Relational) operators
  3. Logical (Boolean) operators
  4. Bitwise operators
  5. Assignment operators Hello World The value of a is 10 The value of a is 10 The value of a is 10 and b is 20 The value of b is 20 and a is 10 Hello satish, Good Morning The story of Bill, Manfred, and Georg Enter a number: 25 25 _# Python Input and Output

Python Output

#We use the print() function to output data to the standard output device_ print("Hello World") a = 10 print("The value of a is", a) #python 3 print ("The value of a is " + str(a)) # Output Formatting a = 10 ; b = 20 #multiple statements in single line. print("The value of a is {} and b is {}".format(a, b)) #default a = 10 ; b = 20 #multiple statements in single line print("The value of b is {1} and a is {0}".format(a, b)) #specify position of argu #we can use keyword arguments to format the string print("Hello {name}, {greeting}".format(name = "satish", greeting = "Good Morning")) #we can combine positional arguments with keyword arguments print('The story of {0}, {1}, and {other}'.format('Bill', 'Manfred', other = 'Georg')) _# Python Input

want to take the input from the user. In Python, we have the input() function to_

num = input("Enter a number: ") print (num)

  1. Special operators

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc.

  • , -, *, /, %, //, ** are arithmetic operators Example: In [69]:

Comparision Operators

Comparison operators are used to compare values. It either returns True or False according to the condition. >, <, ==, !=, >=, <= are comparision operators

x, y = 10 , 20 #addition print(x + y) #subtraction(-) #multiplication() #division(/) #modulo division (%) #Floor Division (//) #Exponent (*)

In [72]:

Assignment operators

Assignment operators are used in Python to assign values to variables. a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left. =, +=, -=, *=, /=, %=, //=, **=, &=, |=, ^=, >>=, <<= are Assignmen t operators In [73]:

Special Operators

a, b = 10 , 4 #Bitwise AND print(a & b) #Bitwise OR #Bitwise NOT #Bitwise XOR #Bitwise rightshift #Bitwise Leftshift a = 10 a += 10 #add AND print(a) #subtract AND (-=) #Multiply AND (=) #Divide AND (/=) #Modulus AND (%=) #Floor Division (//=) #Exponent AND (*=)

Identity Operators

is and is not are the identity operators in Python. They are used to check if two values (or variables) are located on the same part of the memory. In [74]: In [75]: In [76]:

MemberShip Operators

in and not in are the membership operators in Python. They are used to test whether a value or variable is found in a sequence (string, list, tuple, set and dictionary). In [77]: In [78]:

Python if ... else Statement

The if…elif…else statement is used in Python for decision making. True False False True True a = 5 b = 5 print(a is b) #5 is object created once both a and b points to same object #check is not l1 = [ 1 , 2 , 3 ] l2 = [ 1 , 2 , 3 ] print(l1 is l2) s1 = "Satish" s2 = "Satish" print(s1 is not s2) lst = [ 1 , 2 , 3 , 4 ] print( 1 in lst) #check 1 is present in a given list or not #check 5 is present in a given list d = { 1 : "a", 2 : "b"} print( 1 in d)

if test expression: Body of if else: Body of else

Flow Chart

Example

In [80]:

if...elif...else Statement

Syntax:

Positive number num = 10 if num > 0 : print("Positive number") else : print("Negative Number")

if test expression: Body of if elif test expression: Body of elif else: Body of else

Flow Chart

Example:

In [81]:

Nested if Statements

ZERO

num = 0 if num > 0 : print("Positive number") elif num == 0 : print("ZERO") else : print("Negative Number")