








































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
it is a Python Programming E-notes
Typology: Lecture notes
1 / 80
This page cannot be seen from the preview
Don't miss anything!









































































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.
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.
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.
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 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]:
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!")
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]:
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 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]:
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
In [24]:
In [25]: In [26]:
In [27]: In [28]: Observation: x and y points to same memory location In [29]:
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.
#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 represents the truth values False and True In [33]:
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)
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]:
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]:
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]:
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 are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.
#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
num = input("Enter a number: ") print (num)
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc.
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 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]:
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 (*=)
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]:
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]:
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
In [80]:
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
In [81]:
num = 0 if num > 0 : print("Positive number") elif num == 0 : print("ZERO") else : print("Negative Number")