0% found this document useful (0 votes)
51 views262 pages

Python Programming

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.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
51 views262 pages

Python Programming

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.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 262

By

Dr.Bharanidharan.G,
Assistant Professor,
Department of Computer Applications,
The New College, Chennai-14.
E-Mail: bharanidharan@thenewcollege.edu.in
Using C programming
// C program to add two numbers
#include<stdio.h>

int main()
{
int A, B, sum = 0;

// Ask user to enter the two numbers


printf("Enter two numbers A and B : \n");

// Read two numbers from the user || A = 5, B = 7


scanf("%d%d", &A, &B);

// Calclulate the addition of A and B


// using '+' operator
sum = A + B;

// Print the sum


printf("Sum of A and B is: %d", sum);

return 0;
}
Using python
Python used by
python Applications
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.
Installing
python Software
Download Python from the below link:

https://www.python.org/downloads/
Step: We will be brought to another page, where we will need to select either
the x86-64 or amd64 installer to install Python.
We use here Windows x86-64 executable installer.
Python
• 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 Syntax compared to other programming
languages
• Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the
scope of loops, functions and classes. Other programming languages often use
curly-brackets for this purpose.
How to Check Python Version on Linux, Mac &
Windows
How to Check Python Version on Linux, Mac &
Windows
How to check the Python version using a script?
• Python scripts can identify the version of Python installed on the computer. It
enables you to validate if multiple versions are installed in the system. The script
developed to check the Python version remains the same for windows OS, Mac
OS, and Linux distributions. You can create a script by importing either the
platform module or sys module of python.
How to Run Python Scripts: Step by Step Guide
• What is the Script in Python?
• A script in Python can be defined as a file that consists of Python code or a program.
• It ends with an extension as .py
• An interpreter can execute a script in two distinct ways, as listed below: –
• A script can be executed as a module or as a script itself.
• A code that is written in an interactive Python command prompt session manner.

• How to run Python code and scripts interactively?


Here are steps to do this:
• Step 1) The programmer must open the command line in the interactive mode.
• Step 2) In the next step, invoke the python interpreter in the command line by
typing the following command: –

• Step 3) The programmer can sequentially write Python code and execute them in the same order.

• The following program can be typed in the command line as shown below:
Python Indentation
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.


Python Indentation (cont..)
Example 1:

Output :
Python Indentation (cont..)

• Python will give you an error if you skip the indentation:

Example 2:
The number of spaces is up to you as a programmer, but it has to be at least one.

Example 3:
• You have to use the same number of spaces in the same block of code,
otherwise Python will give you an error:

Example 4:
Python Comments
Python Comments

• Comments can be used to

• explain Python code.

• make the code more readable.

• prevent execution when testing code.


Creating a Comment

Comments starts with a #, and Python will ignore them:

Example 1:
#This is a comment
print("Hello, World!")

• Comments can be placed at the end of a line, and Python will ignore the rest of the line:

Example 2:
print("Hello, World!") #This is a comment

• Comments does not have to be text to explain the code, it can also be used to prevent Python
from executing code:

Example 3:
#print("Hello, World!")
print("Cheers, Mate!")
Multi Line Comments

Python does not really have a syntax for multi line comments.

To add a multiline comment you could insert a # for each line:

Example 4:

#This is a comment
#written in
#more than just one line
print("Hello, World!")
Print() Statement
• The print() function in Python is used to print a specified message on the screen.
• The print command in Python prints strings or objects which are converted to a
string while printing on a screen.
• Syntax:
print(object(s))
• Example: 1
To print the Welcome to Guru99, use the Python print statement as follows:
print ("Welcome to Guru99")
Output:
Welcome to Guru99
• Example 2:
If you want to print the name of five countries, you can write:
print ("USA")
print ("Canada")
print ("Germany")
print ("France")
print ("Japan")

Output:
USA
Canada
Germany
France
Japan
• How to print blank lines
• Sometimes you need to print one blank line in your Python program.
Following is an example to perform this task using Python print format.
• Example:
• Let us print 8 blank lines. You can type:

print (8 * "\n")
(or)
print ("\n\n\n\n\n\n\n\n")
,

Print end command


• Print end command

• By default, print function in Python ends with a newline.


• This function comes with a parameter called ‘end.’ The default value of this parameter is ‘\n,’ i.e., the new line character.
• You can end a print statement with any character or string using this parameter. This is available in only in Python 3+.

• Example 1:

print ("Welcome to", end = ' ' )


print ("Guru99", end = '!' )

Output:
Welcome to Guru99!

• Example 2: # ends the output with ' @ '

print (“Python", end = ' @ ' )

Output:
Python@
Python Variables
• What is a Variable in Python?
• A Python variable is a reserved memory location to store values. In other words, a
variable in a python program gives data to the computer for processing.
• Python Variable Types
• Every value in Python has a datatype. Different data types in Python are Numbers,
List, Tuple, Strings, Dictionary, etc.
• Variables in Python can be declared by any name or even alphabets like a, aa, abc,
etc.
• How to declare and use a variable?
• Let us see an example. We will define variable in Python and declare it as “a” and
print it.
a=100
print (a)
• Re-declare a Variable
• You can re-declare Python variables even after you have declared once.
• Here we have Python declare variable initialized to f=0.
• Later, we re-assign the variable f to value “guru99”
Python String Concatenation and Variable
• Let’s see whether you can concatenate different data types like string and number together. For example, we
will concatenate “Guru” with the number “99”.
• Unlike Java, which concatenates number with string without declaring number as string, while declaring
variables in Python requires declaring the number as string otherwise it will show a TypeError.
Python Variable Types: Local & Global

• There are two types of variables in Python, Global variable and Local
variable. When you want to use the same variable for rest of your program
or module you declare it as a global variable, while if you want to use the
variable in a specific function or method, you use a local variable while
Python variable declaration.
• Let’s understand this Python variable types with the difference between
local and global variables in the below program.
1. Let us define variable in Python where the variable “f” is global in scope and is
assigned value 101 which is printed in output
2. Variable f is again declared in function and assumes local scope. It is assigned value
“I am learning Python.” which is printed out as an output. This Python declare
variable is different from the global variable “f” defined earlier.
3. Once the function call is over, the local variable f is destroyed. At line 12, when we
again, print the value of “f” is it displays the value of global variable f=101
• While Python variable declaration using the keyword global, you can
reference the global variable inside a function.
1. Variable “f” is global in scope and is assigned value 101 which is printed in
output
2. Variable f is declared using the keyword global. This is NOT a local variable,
but the same global variable declared earlier. Hence when we print its
value, the output is 101
3. We changed the value of “f” inside the function. Once the function call is
over, the changed value of the variable “f” persists. At line 12, when we
again, print the value of “f” is it displays the value “changing global variable”
Delete a variable
• You can also delete Python variables using the command del “variable
name”.
• In the below example of Python delete variable, we deleted variable f,
and when we proceed to print it, we get error “variable name is not
defined” which means you have deleted the variable.
Summary
• Variables are referred to “envelop” or “buckets” where information can be maintained
and referenced. Like any other programming language Python also uses a variable to
store the information.
• Variables can be declared by any name or even alphabets like a, aa, abc, etc.
• Variables can be re-declared even after you have declared them for once
• Python constants can be understood as types of variables that hold the value which can
not be changed. Usually Python constants are referenced from other files. Python define
constant is declared in a new or separate file which contains functions, modules, etc.
• Types of variables in Python or Python variable types : Local & Global
• Declare local variable when you want to use it for current function
• Declare Global variable when you want to use the same variable for rest of the program
• To delete a variable, it uses keyword “del”.
Python Escape Character Sequences (Examples)
• Escape characters or sequences are illegal characters for Python and never get
printed as part of the output. When backslash is used in Python programming, it
allows the program to escape the next characters.
• Following would be the syntax for an escape sequence.

• Explanation:
Here, the escape character could be t, n, e, or backslash itself.
Types of Escape Sequence
• Escape characters can be classified as non-printable characters when backslash precedes them. The print statements do
not print escape characters.
• Here is a list of Escape Characters
Example Usage of Various Escape Characters
Explanation:
In the above example, instead of adding space using a keyboard, the program helps us by
putting a space or a tab between the string “Guru99”. It also provides a space at the precise
location where the escape sequence is added.
Summary
• Backslash is also regarded as a special character.
• To create an escape sequence, begin with a backslash followed by the
illegal character.
• Examples of escape sequences include “\b”, “\t”,”\n”,”\xhh” and “\ooo”
respectively.
• “\t” allows inserting a space or tab between two words. It plays a similar
role to the space key present on the keyboard.
• “\t” is used when the programmer wants to add space to a string at a
precise location.
• Certain whitespaces help in putting a new line between python strings.
• Line feed and carriage return, vertical tab, and form feed are types of
whitespaces.
Built-
Built-in Data Types
Built-
Built -in Data Types

• In programming, data type is an important concept.


• Variables can store data of different types, and different types can
do different things.

Text Type: str


Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset


Boolean Type: bool

Binary Types: bytes, bytearray, memoryview


Example Data Type

x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset

x = True bool

x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview
Getting the Data Type

You can get the data type of any object by using the type() function:
Setting the Data Type
Setting the Specific Data Type
Python Numbers
Python Numbers

There are three numeric types in Python:

• Int : Int, or integer, is a whole number, positive or negative, without

decimals, of unlimited length. (x = 1 )

• Float : Float, or "floating point number" is a number, positive or negative,

containing one or more decimals. (y = 2.8)

• Complex : Complex numbers are written with a "j" as the imaginary part:

(z = 1j )
Type Conversion

• You can convert from one type to another with the int(), float(), and complex() methods:

Note: You cannot convert complex numbers into another number type.
Random Number

• Python does not have a random() function to make a random number, but
Python has a built-in module called random that can be used to make
random numbers:
Python Strings
String Literals

• String literals in python are surrounded by either single quotation


marks, or double quotation marks.

ex: 'hello' is the same as "hello".

You can display a string literal with the print() function:


Python Collections (Arrays)
• List
• Tuple
• Set
• Dictionary
There are four collection data types in the Python programming language:

• List is a collection which is ordered and changeable. Allows duplicate


members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
• Set is a collection which is unordered and unindexed. No duplicate members.
• Dictionary is a collection which is unordered, changeable and indexed. No
duplicate members.

When choosing a collection type, it is useful to understand the properties of that type.
Choosing the right type for a particular data set could mean retention of meaning, and,
it could mean an increase in efficiency or security.
Python Collections - List
Python - List

mylist = ["apple", "banana", "cherry"]

1. Lists are used to store multiple items in a single variable.


2. List is a collection which is ordered and changeable.
3. Allows duplicate members.
4. In Python lists are written with square brackets.
List Items

• List items are ordered, changeable, and allow duplicate values.

• List items are indexed, the first item has index [0], the second item has

index [1] etc.


List is a collection which is ordered and changeable. Allows duplicate members

Ordered : When we say that lists are ordered, it means that the items have a defined
order, and that order will not change.
Changeable : The list is changeable, meaning that we can change, add, and remove
items in a list after it has been created.
Allow Duplicates : Since lists are indexed, lists can have items with the same value
List Length

• To determine how many items a list has, use the len() function:
List Items - Data Types
• List items can be of any data type:

Example : String, int and boolean data types:

Example : A list with strings, integers and boolean values:


type() ?

type()

• From Python's perspective, lists are defined as objects with the


data type 'list':
<class 'list'>
Example : What is the data type of a list?
Python - Access List Items

Access Items :

• List items are indexed and you can access them by referring to the index number:

Example : Print the second item of the list:

Note: The first item has index 0.


Negative Indexing
• Negative indexing means start from the end
• -1 refers to the last item, -2 refers to the second last item etc.

Example : Print the last item of the list:


Range of Indexes
• You can specify a range of indexes by specifying where to start and where to end
the range.
• When specifying a range, the return value will be a new list with the specified
items.
Example : Return the third, fourth, and fifth item:

Note: The search will start at index 2 (included) and end at index 5 (not included).
Example: This example returns the items from the beginning to, but NOT including, "kiwi":

Example : This example returns the items from "cherry" to the end:
Range of Negative Indexes

• Specify negative indexes if you want to start the search from the end of the list:

Example : This example returns the items from "orange" (-4) to, but NOT including
"mango" (-1):
Check if Item Exists

• To determine if a specified item is present in a list use the in keyword:

Example : Check if "apple" is present in the list:


Python - Change List Items

Change Item Value :


To change the value of a specific item, refer to the index number:

Example : Change the second item:


Change a Range of Item Values

• To change the value of items within a specific range, define a list with
the new values, and refer to the range of index numbers where you want
to insert the new values:
Example : Change the values "banana" and "cherry" with the values
"blackcurrant" and "watermelon":
If you insert more items than you replace, the new items will be inserted
where you specified, and the remaining items will move accordingly:

Example : Change the second value by replacing it with two new values:
If you insert less items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:

Example : Change the second and third value by replacing it with one value:
Insert Items :
• To insert a new list item, without replacing any of the existing values,
we can use the insert() method.
• The insert() method inserts an item at the specified index:

Example : Insert "watermelon" as the third item:


Python - Add List Items

Append Items :

To add an item to the end of the list, use the append() method:

Example : Using the append() method to append an item:


Insert Items:

• To insert a list item at a specified index, use the insert() method.


• The insert() method inserts an item at the specified index:

Example : Insert an item as the second position:


Extend List :

• To append elements from another list to the current list, use


the extend() method.

Example : Add the elements of tropical to thislist:


Python - Remove List Items

Remove Specified Item :

The remove() method removes the specified item.

Example : Remove "banana":


Remove Specified Index :
• The pop() method removes the specified index.
Example : Remove the second item:

• If you do not specify the index, the pop() method removes the last item.
Example : Remove the last item:
• The del keyword also removes the specified index:
Example : Remove the first item:

• The del keyword can also delete the list completely.


Example : Delete the entire list:
Clear the List :
• The clear() method empties the list.
• The list still remains, but it has no content.
Example : Clear the list content:
List Methods
• Python has a set of built-in methods that you can use on lists.

Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list


sort() Sorts the list
Python TUPLE – Pack, Unpack, Compare, Slicing,
Delete, Key
• What is Tuple Matching in Python?
• Tuple Matching in Python is a method of grouping the tuples by
matching the second element in the tuples. It is achieved by using a
dictionary by checking the second element in each tuple in python
programming. However, we can make new tuples by taking portions
of existing tuples.
• Tuple Syntax
Packing and unpacking
• In packing, we place value into a new tuple while in unpacking we
extract those values back into variables.
Comparing tuples
Comparing tuples
• Case1: Comparison starts with a first element of each tuple. In this
case 5>1, so the output a is bigger
• Case 2: Comparison starts with a first element of each tuple. In this
case 5>5 which is inconclusive. So it proceeds to the next element.
6>4, so the output a is bigger
• Case 3: Comparison starts with a first element of each tuple. In this
case 5>6 which is false. So it goes into the else block and prints “b is
bigger.”
Dictionary in Python with Syntax & Example
• What is a Dictionary in Python?
• A Dictionary in Python is the unordered and changeable collection of data values that
holds key-value pairs. Each key-value pair in the dictionary maps the key to its associated
value making it more optimized. A Dictionary in python is declared by enclosing a
comma-separated list of key-value pairs using curly braces({}). Python Dictionary is
classified into two elements: Keys and Values.
• Keys will be a single element.
• Values can be a list or list within a list, numbers, etc.
• Dictionary is listed in curly brackets, inside these curly brackets, keys and values are
declared. Each key is separated from its value by a colon (:), while commas separate each
element.
Python Dictionary Methods
Copying dictionary

• You can also copy the entire dictionary to a new dictionary.


• For example, here we have copied our original dictionary to the new dictionary
name “Boys” and “Girls”.
Python Dictionary Methods
• We have the original dictionary (Dict) with the name and age of the boys
and girls together
• But we want boys list separate from girls list, so we defined the element of
boys and girls in a separate dictionary name “Boys” and “Girls.”
• Now again we have created new dictionary name “student X” and “student
Y,” where all the keys and values of boy dictionary are copied into student
X, and the girls will be copied in studentY
• So now you don’t have to look into the whole list in the main dictionary(
Dict) to check who is a boy and who is girl, you just have to print student X
if you want boys list and StudentY if you want girls list
• So, when you run the student X and studentY dictionary, it will give all the
elements present in the dictionary of “boys” and “girls” separately
• Dictionary items() Method
• The items() method returns a list of tuple pairs (Keys, Value) in the
dictionary.

• We use the code items() method for our Dict.


• When code was executed, it returns a list of items ( keys and values)
from the dictionary
Check if a given key already exists in a
dictionary
• For a given list, you can also check whether our child dictionary exists
in the main dictionary or not.
• Here we have two sub-dictionaries “Boys” and “Girls”, now we want
to check whether our dictionary Boys exist in our main “Dict” or not.
For that, we use the for loop method with else if method.
Check if a given key already exists in a
dictionary
• The for loop in code checks each key in the main dictionary for Boys
keys
• If it exists in the main dictionary, it should print true or else it should
print false
• When you execute the code, it will print “True” for three times, as we
got three elements in our “Boys” dictionary
• So it indicates that the “Boys” exist in our main dictionary (Dict)
Sorting the Dictionary

• In the dictionary, you can also sort the elements. For example, if we
want to print the name of the elements of our dictionary
alphabetically, we have to use the for a loop. It will sort each element
of the dictionary accordingly.
Sorting the Dictionary

• We declared the variable students for our dictionary “Dict.”


• Then we use the code Students.sort, which will sort the element
inside our dictionary
• But to sort each element in the dictionary, we run the for a loop by
declaring variable S
• Now, when we execute the code, the for loop will call each element
from the dictionary, and it will print the string and value in an order
Python Dictionary in-built Functions
• Dictionary len() Method
• The len() function gives the number of pairs in the dictionary.
• For example, When len (Dict) function is executed it gives the
output at “4” as there are four elements in our dictionary
Variable Types
• Python does not require to explicitly declare the reserve memory
space; it happens automatically.
• The assign values to variable “=” equal sign are used. The code to
determine the variable type is ” %type (Dict).”
• Use the code %type to know the variable type
• When code was executed, it tells a variable type is a dictionary
Dictionary Str(dict)

• With Str() method, you can make a dictionary into a printable string
format.
• Use the code % str (Dict)
• It will return the dictionary elements into a printable string format
Summary
• Dictionaries in a programming language is a type of data-structure used to
store information connected in some way.
• Python Dictionary are defined into two elements Keys and Values.
• Dictionaries do not store their information in any particular order, so you
may not get your information back in the same order you entered it.
• Keys will be a single element
• Values can be a list or list within a list, numbers, etc.
• More than one entry per key is not allowed ( no duplicate key is allowed)
• The values in the dictionary can be of any type, while the keys must be
immutable like numbers, tuples, or strings.
• Dictionary keys are case sensitive- Same key name but with the different
cases are treated as different keys in Python dictionaries.
Python Dictionary Append: How to Add Key/Value
Pair
• Dictionary is one of the important data types available in Python. The
data in a dictionary is stored as a key/value pair. It is separated by a
colon(:), and the key/value pair is separated by comma(,).
• The keys in a dictionary are unique and can be a string, integer, tuple,
etc. The values can be a list or list within a list, numbers, string, etc.
• Here is an example of a dictionary:
Restrictions on Key Dictionaries
• Here is a list of restrictions on the key in a dictionary:
• If there is a duplicate key defined in a dictionary, the last is considered. For
example consider dictionary my_dict =
{“Name”:”ABC”,”Address”:”Mumbai”,”Age”:30, “Name”: “XYZ”};.It has a key
“Name” defined twice with value as ABC and XYZ. The preference will be
given to the last one defined, i.e., “Name”: “XYZ.”
• The data-type for your key can be a number, string, float, boolean, tuples,
built-in objects like class and functions.
• For example my_dict = {bin:”001″, hex:”6″ ,10:”ten”, bool:”1″, float:”12.8″,
int:1, False:’0′};Only thing that is not allowed is, you cannot defined a key in
square brackets for example my_dict =
{[“Name”]:”ABC”,”Address”:”Mumbai”,”Age”:30};
Operators in Python – Logical, Arithmetic,
Comparison

• Logical Operators in Python are used to perform logical operations


on the values of variables.
• The value is either true or false. We can figure out the conditions by
the result of the truth values.
• There are mainly three types of logical operators in python: logical
AND, logical OR and logical NOT. Operators are represented by
keywords or special characters.
Comparison Operators
• Comparison Operators In Python compares the values on either side of the operand and
determines the relation between them. It is also referred to as relational operators. Various
comparison operators in python are ( ==, != , <>, >,<=, etc.)
• Example: For comparison operators we will compare the value of x to the value of y and print the
result in true or false. Here in example, our value of x = 4 which is smaller than y = 5, so when we
print the value as x>y, it actually compares the value of x to y and since it is not correct, it returns
false.
Membership operators
• Declare the value for x and y
• Declare the value of list
• Use the “in” operator in code with if statement to check the value of x
existing in the list and print the result accordingly
• Use the “not in” operator in code with if statement to check the value
of y exist in the list and print the result accordingly
• Run the code- When the code run it gives the desired output
Summary
• Operators in a programming language are used to perform various operations on values and variables.
• There are various methods for arithmetic calculation in Python as you can use the eval function, declare variable & calculate, or
call functions
• Comparison operators often referred as relational operators are used to compare the values on either side of them and determine
the relation between them
• Python assignment operators are simply to assign the value to variable
• Python also allows you to use a compound assignment operator, in a complicated arithmetic calculation, where you can assign the
result of one operand to the other
• For AND operator – It returns TRUE if both the operands (right side and left side) are true
• For OR operator- It returns TRUE if either of the operand (right side or left side) is true
• For NOT operator- returns TRUE if operand is false
• There are two membership operators that are used in Python. (in, not in).
• It gives the result based on the variable present in specified sequence or string
• The two identify operators used in Python are (is, is not)
• It returns true if two variables point the same object and false otherwise
• Precedence operator can be useful when you have to set priority for which calculation need to be done first in a complex
calculation.
Python Array
• What is Python Array?
• A Python Array is a collection of common type of data structures having elements with same
data type. It is used to store collections of data. In Python programming, an arrays are
handled by the “array” module. If you create arrays using the array module, elements of the
array must be of the same numeric type.
• When to use Array in Python?
• Python arrays are used when you need to use many variables which are of the same type. It
can also be used to store a collection of data. The arrays are especially useful when you have
to process the data dynamically. Python arrays are much faster than list as it uses less
memory.
• How to insert elements?
• Python array insert operation enables you to insert one or more items
into an array at the beginning, end, or any given index of the array.
This method expects two arguments index and value.
• The syntax is
Summary
• An array is a common type of data structure wherein all elements must be of the same data type.
• Python programming, an array, can be handled by the “array” module.
• Python arrays are used when you need to use many variables which are of the same type.
• In Python, array elements are accessed via indices.
• Array elements can be inserted using an array.insert(i,x) syntax.
• In Python, arrays are mutable.
• In Python, a developer can use pop() method to pop and element from Python array.
• Python array can be converted to Unicode. To fulfill this need, the array must be a type ‘u’;
otherwise, you will get “ValueError”.
• Python arrays are different from lists.
• You can access any array item by using its index.
• The array module of Python has separate functions for performing array operations.
Python Collections - SETS
Python - SETS
myset = {"apple", "banana", "cherry"}
• Sets are used to store multiple items in a single variable.
• Set is a collection which is unordered and unindexed.
• No duplicate members.
• In Python sets are written with curly brackets.

Note: Sets are unordered


• meaning: the items will appear in a random order.
• so you cannot be sure in which order the items will appear.
Set Items
• Set items are unordered, unchangeable, and do not allow duplicate
values.
Unordered :
• Unordered means that the items in a set do not have a defined order.
• Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.
Unchangeable :
• Sets are unchangeable, meaning that we cannot change the items after the set
has been created.
NOTE : Once a set is created, you cannot change its items, but you can add new items.
Duplicates Not Allowed:
Sets cannot have two items with the same value.
Get the Length of a Set

• To determine how many items a set has, use the len() method.
Set Items - Data Types
• Set items can be of any data type:

Example : String, int and boolean data types:

• A set can contain different data types:

Example : A set with strings, integers and boolean values:


type()

• From Python's perspective, sets are defined as objects with the data
type 'set':
<class 'set'>
Example : What is the data type of a set?
Python - Access Items

• You cannot access items in a set by referring to an index, since sets


are unordered the items has no index.
• But you can loop through the set items using a for loop, or ask if a
specified value is present in a set, by using the in keyword.

Example:
Loop through the set, and print the values:
Example:
Check if "banana" is present in the set:
Change Items

• Once a set is created, you cannot change its items, but you can add
new items.
Python - Add Set Items
Add Items:

• Once a set is created, you cannot change its items, but you can add new items.

• To add one item to a set use the add() method.

• To add more than one item to a set use the update() method.

Example: Add an item to a set, using the add() method:


Example: Add multiple items to a set, using the update() method:
Python - Remove Item
• To remove an item in a set, use the remove(), or the discard() method.

Example: Example:
Remove "banana" by using the discard() method:
Remove "banana" by using the remove() method:

Note: If the item to remove does not exist,


• remove() will raise an error.
• discard() will NOT raise an error.
Join Two Sets

• There are several ways to join two or more sets in Python.


• You can use the union() method that returns a new set containing all items from both
sets, or the update() method that inserts all the items from one set into another:

Example : The union()/ update() method returns a new set with all items from both
sets:
Set Methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets

difference_update() Removes the items in this set that are also included in another, specified set

discard() Remove the specified item


intersection() Returns a set, that is the intersection of two other sets

intersection_update() Removes the items in this set that are not present in other, specified set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set


remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and another

union() Return a set containing the union of sets

update() Update the set with the union of this set and others
Python File - Handling
Python File - Handling

• File handling is an important part of any web application.


• Python has several functions for creating, reading, updating, and
deleting files.
Python - File Handling
The key function for working with files in Python is the open() function.

• The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

 "r" - Read - Default value. Opens a file for reading, error if the file does not exist
 "a" - Append - Opens a file for appending, creates the file if it does not exist
 "w" - Write - Opens a file for writing, creates the file if it does not exist
 "x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

 "t" - Text - Default value. Text mode


 "b" - Binary - Binary mode (e.g. images)
Syntax

To open a file for reading it is enough to specify the name of the file:

f = open("demofile.txt")

The code above is the same as:

f = open("demofile.txt", "r")

f = open("demofile.txt", "rt“)

• Because "r" for read, and "t" for text are the default values, you do not need to

specify them.

Note: Make sure the file exists, or else you will get an error.
Python File Open - Open a File on the Server

• Assume we have the following file, located in the same folder as Python:

 To open the file, use the built-in open() function.


 The open() function returns a file object, which has a read() method for reading the
content of the file:
demofile.txt
Ex – 1:
WELCOME
TO
f = open("demofile.txt", "r") PYTHON
CLASS
print(f.read())
If the file is located in a different location, you will have to specify the file path, like this:

EX - 2 : Open a file on a different location:

f = open("E:\K4U\K4U TRANNING\Python Programs\welcome.txt", "r")

print(f.read())
Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how many characters
you want to return:

Ex – 3 : Return the 5 first characters of the file demofile.txt


WELCOME
TO
f = open("demofile.txt", "r") PYTHON
CLASS
print(f.read(5))
Read Lines - readline() method:

You can return one line by using the readline() method:

Ex – 4 : Read one line of the file


f = open("demofile.txt", "r")
print(f.readline())

By calling readline() two times, you can read the two first lines:

Ex – 5 : Read two lines of the file:


f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
read the whole file, line by line

By looping through the lines of the file, you can read the whole file, line by line:

Ex -6 : Loop through the file line by line

f = open("demofile.txt", "r")
for x in f:
print(x)
Close Files

It is a good practice to always close the file when you are done with it.

Ex : Close the file when you are finish with it

f = open("demofile.txt", "r")
print(f.readline())
f.close()

Note: You should always close your files, in some cases, due to buffering,
changes made to a file may not show until you close the file.
Python File Write - Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content

Ex – 7 : Open the file "demofile2.txt" and append content to the file

f = open("demofile2.txt", "a")
f.write(“B Prasad Python class!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
Python File Write - overwrite the content

Ex – 8 : Open the file "demofile3.txt" and overwrite the content

f = open("demofile3.txt", "w")
f.write(" Prasad - Add content!")
f.close()

#open and read the file after the appending:


f = open("demofile3.txt", "r")
print(f.read())

Note: the "w" method will overwrite the entire file.


Create a New File

To create a new file in Python, use the open() method, with one of the following parameters:

"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist

Example:
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Result: a new empty file is created!

Example:
Create a new file if it does not exist:
f = open("myfile.txt", "w")
Python Delete File - Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

Ex - 10: Remove the file "demofile4.txt"


import os
os.remove("demofile.txt")

Check if File exist:


To avoid getting an error, you might want to check if the file exists before you try to delete it:
Ex – 11 : Check if file exists, then delete it
import os
if os.path.exists("demofile4.txt"):
os.remove("demofile4.txt")
else:
print("The file does not exist")
Delete Folder

To delete an entire folder, use the os.rmdir() method:

Ex - Remove the folder "myfolder":


import os
os.rmdir("myfolder")

Note: You can only remove empty folders.


Python - User Input
User Input

• Python allows for user input.


• That means we are able to ask the user for input.

Python input() Function :

• The input() function allows user input.

Syntax : input(prompt)
Example 1:

Example 2:
Example 3:
Example 4:
Python Strings
Python - String

• String literals in python are surrounded by either single quotation


marks, or double quotation marks.

ex: 'hello' is the same as "hello".

You can display a string literal with the print() function:


Assign String to a Variable

• Assigning a string to a variable is done with the variable name followed by an


equal sign and the string:
Multiline Strings

• You can assign a multiline string to a variable by using three quotes (single
or double):

Three double quotes: “ “ “ “ “ “


Example : You can use three double quotes:
Three single quotes: ‘’’ ‘’’

Example : You can use three single quotes:


Python - Modify Strings

• Python has a set of built-in methods that you can use on strings.

Upper Case : upper() method

Example : The upper() method returns the string in upper case:


Lower Case : lower() method

Example : The lower() method returns the string in lower case:


Remove Whitespace

• Whitespace is the space before and/or after the actual text, and very often
you want to remove this space.
• The strip() method removes any whitespace from the beginning or the end:

Example :
Replace String

• The replace() method replaces a string with another string:

Example :
Split String

• The split() method returns a list where the text between the specified separator
becomes the list items.
• The split() method splits the string into substrings if it finds instances of the
separator:
• The capitalize() method returns a string where the first character is upper
case, and the rest is lower case.

• The casefold() method returns a string where all the characters are lower case.
Python - Format - Strings

• Python Variables cannot combine strings and numbers :


String Format

• But we can combine strings and numbers by using the format() method!
• The format() method takes the passed arguments, formats them, and places
them in the string where the placeholders {} are:

Example : Use the format() method to insert numbers into strings:


• The format() method takes unlimited number of arguments, and are placed into
the respective placeholders:
• You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:
Python Flow Control
Python - Flow Control

• Python If ... Else


• Python While Loops
• Python For Loops
Python - If ... Else

Python Conditions :

Python supports the usual logical conditions from mathematics:

• Equals: a == b

• Not Equals: a != b

• Less than: a < b

• Less than or equal to: a <= b

• Greater than: a > b

• Greater than or equal to: a >= b


If statements

• Python conditions can be used in several ways, most commonly


in "if statements" and loops.
• An "if statement" is written by using the if keyword.

Example: If statement
Else

• The else keyword catches anything which isn't caught by the


preceding conditions.
Example: else statement

In this example a is greater than b, so the first condition is not true, so we go to the else condition
and print to screen that "a is greater than b"
And - Keyword

The and keyword is a logical operator, and is used to combine conditional


statements:

Example : Test if a is greater than b, AND if c is greater than a:


Or - Keyword

• The or keyword is a logical operator, and is used to combine conditional


statements:
Example : Test if a is greater than b, OR if a is greater than c:
Nested If

• You can have if statements inside if statements, this is

called nested if statements.

Example :
Python - While/For Loops

Python Loops :

Python has two primitive loop commands:

• while loops

• for loops
Python - While Loops

• With the while loop we can execute a set of statements as long as


a condition is true.
• The while loop in Python executes a block of code until the specified
condition becomes False.
Example : Print i as long as i is less than 6:

Note: remember to increment i, or else the loop will continue forever.


break statement

• With the break statement we can stop the loop even if the while
condition is true:

Example : Exit the loop when i is 3:


continue statement

• With the continue statement we can stop the current iteration, and
continue with the next:

Example : Continue to the next iteration if i is 3


else statement

• With the else statement we can run a block of code once when the
condition no longer is true:

Example : Print a message once the condition is false


Python – For Loops

• A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
• This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming
languages.
• With the for loop we can execute a set of statements, once for each item in a
list, tuple, set etc.
Python with MySQL Connectivity: Database & Table
[Examples]
• In order to use MySQL connectivity with Python, we must have some
knowledge of SQL
• MySQL is an Open-Source database and one of the best type of
RDBMS (Relational Database Management System). Co-founder of
MySQLdb is Michael Widenius’s, and also MySQL name derives from
the daughter of Michael.

You might also like