SlideShare uma empresa Scribd logo
1 de 213
Baixar para ler offline
Introduction to Python
Sisir Kumar Jena
Assistant Professor, CSE
Graphic Era Hill University
Sisir Kumar Jena
What is Python?
• An object-oriented scripting
language.
• It is a high-level, interpreted,
general-purpose programming
language.
• Released publicly in 1991.
• Developed by: Guido van
Rossum
Guido van
Rossum
Sisir Kumar Jena
Why Python in Popular?
• Its open source, free and widely available with a massive open-source
community.
• It’s easier to learn than languages like C, C++, C# and Java, enabling
novices and professional developers to get up to speed quickly.
• It’s easier to read than many other popular programming languages.
• It’s widely used in education.
• It enhances developer productivity with extensive standard libraries
and thousands of third-party open-source libraries, so programmers
can write code faster and perform complex tasks with minimal code.
Sisir Kumar Jena
Why Python in Popular?
• There are massive numbers of free open-source Python applications.
• It’s popular in web development (e.g., Django, Flask).
• It supports popular programming paradigms—procedural, functional,
object oriented.
• There are lots of capabilities for enhancing Python performance.
• It’s used to build anything from simple scripts to complex apps with
massive numbers of users, such as Dropbox, YouTube, Reddit,
Instagram and Quora.
Sisir Kumar Jena
Why Python in Popular?
• It’s popular in artificial intelligence, which is enjoying explosive
growth, in part because of its special relationship with data science.
• It’s widely used in the financial community.
• There’s an extensive job market for Python programmers across many
disciplines, especially in data-science-oriented positions, and Python
jobs are among the highest paid of all programming jobs.
Sisir Kumar Jena
History
• 1980s: Beginning the development of Python
• Guido van Rossum worked that time in a project at the CWI, called
Amoeba, a distributed operating system.
• The language, he used at that time is the ABC language.
• Van Rossum began exploring a scripting language with a syntax similar
to ABC but with access to the Amoeba system calls. As a result, Van
Rossum set out to create a new simple scripting language that could
overcome ABC’s limitations.
• He gave the name to its newly created language “Python”.
• First released in 1991 as Python 0.9.0.
Sisir Kumar Jena
Why the name “Python” ?
• Rossum, wanted his new language’s name to be short, original, and
mysterious.
• The name was inspired by Monty Python’s Flying Circus, a BBC
comedy series.
Sisir Kumar Jena
Python Versions
• First released it in 1991 as Python 0.9.0.
• Python 2.0 was released in 16 October 2000 and introduced new
features such as list comprehensions, cycle-detecting garbage
collection, reference counting, and Unicode support.
• Python 3.0, released in 3 December 2008, was a major revision that is
not completely backward-compatible with earlier versions.
• Python 2 was discontinued with version 2.7.18 in 2020.
• Latest stable version is Python 3.10
Sisir Kumar Jena
Python versions
Python 2 Python 3
Released Year: 2000 Relesed Year: 2008
More complex Syntax as compared to Python 3 Syntax is easy and simple
By default, Strings are saved in ASCII format By default, String are saved in UNICODE format
Print is a statement. Syntax: print “hello world” Print is a function. Syntax: print (“hello world”)
Exception should be enclosed in notations Exception should be enclosed in parentheses
To perform iterations, xrange() is used To perform iterations Range() is used
Sisir Kumar Jena
Features of Python
• Open source: Python is publicly available open-source software.
• Easy-to-learn: Popular (scripting/extension) language, clear and easy
syntax, no type declarations, automatic memory management, high-level
data types and operations, design to read (more English like syntax) and
write (shorter code compared to C, C++, and Java) fast.
• High-level Language: Python is an example of a high-level language like C,
C++, Perl, and Java with low-level optimization.
• Portable: High level languages are portable, which means they are able to
run across all major hardware and software platforms with few or no
change in source code.
• Object-Oriented: Python is a full-featured object-oriented programming
language, with features such as classes, inheritance, objects, and
overloading.
Sisir Kumar Jena
Features of Python
• Python is Interactive: Python has an interactive console where you get a Python
prompt (command line) and interact with the interpreter directly to write and
test your programs. This is useful for mathematical programming.
• Interpreted: Python programs are interpreted, takes source code as input, and
then compiles (to portable byte-code) each statement and executes it
immediately.
• Extendable: Python is often referred to as a "glue" language, meaning that it is
capable of working in mixed-language environment. The Python interpreter is
easily extended and can add a new built-in function or modules written in
C/C++/Java code.
• Libraries: Databases, web services, networking, numerical packages, graphical
user interfaces, 3D graphics, others.
• Supports: Support from online Python community
Sisir Kumar Jena
Setting up your programming environment
• Python is a cross-platform programming language, which means it
runs on all the major operating systems.
Sisir Kumar Jena
Python on Windows
• Windows doesn’t always come with Python, so you’ll probably need
to install it, and then install Sublime Text.
• Check whether Python is installed on your system:
• In the command prompt window, enter python in lowercase. If you get a
Python prompt (>>>) in response, Python is installed on your system.
• If error, goto https://www.python.org/downloads/
Sisir Kumar Jena
Python on Windows
Sisir Kumar Jena
Python on Windows
Sisir Kumar Jena
Python on Windows
• Running Python in a terminal
Sisir Kumar Jena
Python on Windows
• Enter the following line in your Python session, and make sure you
see the output Hello Python interpreter!
• To close the terminal session, press ctrl-Z and then press enter, or
enter the command exit().
• You can install sublime text at https://sublimetext.com/.
Sisir Kumar Jena
Python on MacOS
• Python is already installed on most macOS systems, but it’s most
likely an outdated version that you won’t want to learn on.
• Check whether Python is installed on your system:
• Open a terminal window by going to Applications  Utilities  Terminal.
• You can also press spacebar, type terminal, and then press enter.
Sisir Kumar Jena
Python on MacOS
• To see which version of Python is installed, enter python with a
lowercase p—this also starts the Python interpreter within the
terminal, allowing you to enter Python commands.
• Once you’ve seen this output, press ctrl-D or enter exit() to leave the
Python prompt and return to a terminal prompt.
Sisir Kumar Jena
Python on MacOS
• To check whether you have Python
3 installed, enter the command
python3.
• If Python 3 isn’t installed by default,
you’ll need to install it manually.
• When you’re finished, enter the
following at a terminal prompt:
$ python3 -- version
Python 3.10.5
Sisir Kumar Jena
Python on Linux
• Linux systems are designed for programming, so Python is already
installed on most Linux computers.
• Checking your version of Python
• Open a terminal window by running the Terminal application on your system
(in Ubuntu, you can press ctrl-alt-T).
• To find out whether Python is installed, enter python with a lowercase p.
Sisir Kumar Jena
Python on Linux
• To check for Python 3, you might have to specify that version; try the
command python3:
Sisir Kumar Jena
Python on Linux
• Installing a Text Editor
• Geany is a simple text editor: it’s easy to install.
• Running your first program
• Open Geany
• Save an empty Python file (File  Save As) called hello_world.py. The
extension .py tells Geany your file will contain a Python program.
• After you’ve saved your file, enter the following line:
Sisir Kumar Jena
Running your first program
• Install Sublime text
Sisir Kumar Jena
Running your first program
Install Sublime text
Sisir Kumar Jena
Running your first program
• First create a folder at your
desired location and name
it as per your choice.
• It’s best to use lowercase
letters and underscores for
spaces in file and folder
names, because Python
uses these naming
conventions.
Sisir Kumar Jena
Running your first program
• Type the first line as
shown in the image.
• Press ctrl+B to run your
code.
• The output is shown in the
image on right.
Sisir Kumar Jena
References
• Book Reference
• Matthes, Eric. Python crash course: A hands-on, project-based introduction to
programming. no starch press, 2019.
• Deitel, P., and H. Deitel. "Introduction to Python for Computer Science and
Data Science." (2020).
• Cite Reference: accessed on 16th June 2022.
• https://docs.python.org/3.4/tutorial/
• https://intellipaat.com/blog/tutorial/python-tutorial/
• https://www.w3schools.com/python/python_intro.asp
• https://www.javatpoint.com/python-tutorial
• https://www.scaler.com/topics/python/what-is-python/
• https://www.w3resource.com/python/python-tutorial.php
Getting Started with Python
Sisir Kumar Jena
Content
• IDLE
• Comments
• Variables
• Keywords
• Quotations
• Input and Output
Sisir Kumar Jena
Getting Started
• After the installation, you can see a python environment IDLE is
installed in your Windows machine.
• IDLE stands for Integrated Development and Learning Environment.
Sisir Kumar Jena
IDLE
• Interactive Mode
Sisir Kumar Jena
IDLE
• Interactive Mode
• If we want to repeat prior command in interactive window, you can use  key
to scroll backward through commands history and  key to scroll forward. Use
Enter key to select it. Using these keys, your prior commands will be recalled
and displayed, and we may edit or rerun them.
• You can quit the interpreter by pressing Ctrl+D.
• To restart the interpreter, you can type Ctrl+F6 will restart the shell.
• You can also use commands as follows to know more:
• credits
• copyright
• license()
• help()
Sisir Kumar Jena
IDLE
• Script Mode
• In interactive mode you can run small piece of code and you can not save it.
For running large programs and saving for future, you need to use script
mode.
Sisir Kumar Jena
IDLE
• Script Mode
• Execute the code using RUN option or press Ctrl + F5
Sisir Kumar Jena
Comments
• In Python we use
# symbol to write
comments.
This is a
comment line
Sisir Kumar Jena
Comments
• When # is written inside two bouble
quote it is considered as a character.
• You can write multi line comment by
putting a # in front of each line.
Sisir Kumar Jena
Variables
• Variables are names given to memory locations.
• We can store any value in that location and refer it by the variable
name.
23
age
A memory segment
Variable Name
Variable Value
Sisir Kumar Jena
Variables
• In python, variable do not require declaration.
Sisir Kumar Jena
Variables
• Let's try a simple example:
Sisir Kumar Jena
Variables
• In python, a variable can store any type of data.
Sisir Kumar Jena
Variables
• You can assign a single value to multiple variables or multiple values
to multiple variables in a single statement.
Sisir Kumar Jena
Variables
• Referring a variable that was not assigned a value causes error.
Sisir Kumar Jena
Variables
• You can delete a variable in use at any point of time using del
statement.
Sisir Kumar Jena
Variables
• Naming a variable
• Variable names can contain only letters, numbers, and underscores. They can
start with a letter or an underscore, but not with a number. For instance, you
can call a variable message_1 but not 1_message.
• Spaces are not allowed in variable names, but underscores can be used to
separate words in variable names. For example, greeting_message works,
but greeting message will cause errors.
• Avoid using Python keywords and function names as variable names; that is,
do not use words that Python has reserved for a particular programmatic
purpose, such as the word print.
Sisir Kumar Jena
Variables
• Naming Variables
• Variable names should be short but descriptive. For example, name is better
than n, student_name is better than s_n, and name_length is better
than length_of_persons_name.
• Be careful when using the lowercase letter l and the uppercase letter O
because they could be confused with the numbers 1 and 0.
• It is better to use lower case letter to name a variable.
Sisir Kumar Jena
Keywords (Reserved Words)
• These words have predefined meaning and known to Python
interpreter.
• We can not use these words for any other purpose; like declaring
variables using these words causes error.
and break continue del else
exec for global import is
not pass raise try with
assert class def elif except
finally from if in lambda
or print return while yield
Sisir Kumar Jena
Keywords (Reserved Words)
• What happen when I am trying to use keywords as variable name?
Sisir Kumar Jena
Indentation
• Indentation is the leading whitespace ( spaces and tabs ) before any
statement in Python.
• Python treats the statements with the same indentation level
(statements with an equal number of whitespaces before them) as a
single code block.
Sisir Kumar Jena
Indentation
• A program with proper indentation does not lead to any error.
Sisir Kumar Jena
Indentation
• Improper indentation leads to syntactical error.
Sisir Kumar Jena
Indentation
• You can use any number of space
to indent your code, but it should
be at least one.
• Better way to indent is to use tab
key.
Sisir Kumar Jena
Indentation
• You have to use the same
number of spaces in the
same block of code.
Sisir Kumar Jena
Indentation
Sisir Kumar Jena
Quotations
• Python uses three types
quotations to represent string:
• Single quote ('string')
• Double quote ("string")
• Triple quote ('''string''')
• The most common use of
single quote and double quote
is to enclose string.
Sisir Kumar Jena
Quotations
Sisir Kumar Jena
Quotations
• We should not mix the quotations, otherwise it will lead to error.
Sisir Kumar Jena
Quotations
• If your string itself contains single or double quote, then escaping
them is easy in Python.
• Let your string contains a double quote (or a single quote) that you want to
print, then enclose the entire string using single quote (or double quote).
Sisir Kumar Jena
Quotations
• If your string contains both single quote and double quote and you
want to print them, then use triple quote to enclose the entire string.
Sisir Kumar Jena
Quotations
• Another use of triple quote to enclose multiple lines.
Sisir Kumar Jena
Input and Output
• As like other programming language, the programmer sometimes
require inputs from the user and act upon that input.
• Python provides a function to read inputs from the user:
• input()
• input()
• This function reads the input from the user, convert it into string, and then
assign it to the variable.
Sisir Kumar Jena
Input and Output
Sisir Kumar Jena
Input and Output
Sisir Kumar Jena
Input and Output
Sisir Kumar Jena
References
• Book Reference
• Matthes, Eric. Python crash course: A hands-on, project-based
introduction to programming. no starch press, 2019.
• Deitel, P., and H. Deitel. "Introduction to Python for Computer Science
and Data Science." (2020).
• Reema, Thareja. "Python Programming: Using Problems Solving
Approach." (2020).
• Websites: Accessed on 5th July 2022
• https://www.w3schools.com/python/gloss_python_indentation.asp
• https://www.scaler.com/topics/python/indentation-in-python/
Data Types and Operators
Sisir Kumar Jena
Content
• Data Types
• Operators
Sisir Kumar Jena
Data Types
• We can store different type of data in a variable.
• Standard data types supported in Python is given below:
Data Types
Numbers
String Lists
Dictionary
Tuple
Sets
Integers Floating Point Complex
Boolean
Sequences
Sisir Kumar Jena
Numbers
• Integers
• var = 45
• Floating Points
• var = 8.98
• Complex
• var = 45j
Sisir Kumar Jena
Strings
• A string is a series of characters.
• Anything inside quotes is considered a string in Python.
• Example:
• 'this is a string'
• "this is a string"
• '''this is a string'''
Sisir Kumar Jena
Strings
• You can store an entire string inside a variable.
Sisir Kumar Jena
Strings
• Individual characters in a
string can be accessed
through its index number.
• Index numbers can be
positive or negative.
Sisir Kumar Jena
Strings
Sisir Kumar Jena
String
G R A P H I C E R A H I L L
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
-16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
String
Index
Index
Sisir Kumar Jena
String
• String slicing
Sisir Kumar Jena
Strings
• You can skip characters at regular
interval.
• You can reverse the string by using
-1 as reverse skipping.
• You can not slice string in reverse
order.
Sisir Kumar Jena
Strings
• Home Task
• What happen to this code?
>>> univ="Graphic Era Hill"
>>> univ[::-2]
>>> univ[:15:]
>>> univ[:5:]
>>> univ[:5:1]
>>> univ[:5:2]
>>> univ[:5:-1]
>>> univ[0:16:1:1]
Sisir Kumar Jena
Strings
• String Concatenation
• String Repetition
(Multiplication)
Sisir Kumar Jena
String Functions
• len()
• Find the length of a string
• casefold()
• Convert to lower case
• lower()
• Convert to lower case
• upper()
• Convert to upper case
• title()
• Convert first character of each word
to upper case
• swapcase()
• Convert lower to upper and vice versa
Sisir Kumar Jena
String functions
• capitalize()
• Capitalize the first character
of a string
• count()
• Count the number of
occurrences of a substring
• index()
• Searches the string for a
specified value and returns
the position of where it was
found
• find()
• Searches the string for a
specified value and returns
the position of where it was
found
Sisir Kumar Jena
String Functions
• isalnum()
• Returns True if all characters in the
string are alphanumeric
• isalpha()
• Returns True if all characters in the
string are in the alphabet
• isdigit()
• Returns True if all characters in the
string are digits
Sisir Kumar Jena
String Functions
• You can find more string functions at:
• https://www.w3schools.com/python/python_ref_string.asp
Sisir Kumar Jena
Operators
• Operators are symbols used for performing an operation on
operands.
• In Python, the operators are classified as follows:
• Arithmetic operators
• Comparison (relational) operators
• Logical operators
• Assignment operators
• Identity operators
• Membership operators
• Bitwise operators
Sisir Kumar Jena
Arithmetic Operators
Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
// Floor division x // y
Sisir Kumar Jena
Comparison Operator
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Sisir Kumar Jena
Logical Operator
Operator Description Example
and Returns True if both x < 5 and x < 10
statements are true
or Returns True if one of x < 5 or x < 4
the statements is true
not Reverse the result, returns not(x < 5 and x < 10)
False if the result is true
Sisir Kumar Jena
Logical Operator
Sisir Kumar Jena
Assignment Operator
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
Sisir Kumar Jena
Assignment Operator
Operator Example Same As
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Sisir Kumar Jena
Identity Operator
Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same memory
location.
Operator Description Example
is Returns True if both variables are the x is y
same object
is not Returns True if both variables are not x is not y
the same object
Not in
Course
Sisir Kumar Jena
Membership Operator
Membership operators are used to test if a sequence is presented in an
object
Operator Description Example
in Returns True if a sequence with the x in y
specified value is present in the object
not in Returns True if a sequence with the x not in y
specified value is not present in the object
Not in
Course
Sisir Kumar Jena
Bitwise Operator
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits
is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the
right and let the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the
leftmost bit in from the left, and let the
rightmost bits fall off
Sisir Kumar Jena
Bitwise Operator
Sisir Kumar Jena
References
• Book Reference
• Matthes, Eric. Python crash course: A hands-on, project-based
introduction to programming. no starch press, 2019.
• Reema, Thareja. "Python Programming: Using Problems Solving
Approach." (2020).
• Websites: Accessed on 6th July 2022
• https://www.w3schools.com/python/python_operators.asp
• https://www.w3schools.com/python/python_ref_string.asp
Data Structures : Lists
Sisir Kumar Jena
Content
• Basics of List Data Structure
• Changing, adding, and deleting in List
• Organizing a List
• Printing a list in reverse order
• Finding the length of a list
Sisir Kumar Jena
Basics of List Data Structure
• What is a List?
• A list is a collection of items in a particular order.
• You can put anything you want into a list, and the items in your list don’t have
to be related in any particular way.
• it’s a good idea to make the name of your list plural, such as letters,
digits, or names.
• In Python, square brackets ([]) indicate a list, and individual elements in the
list are separated by commas.
Sisir Kumar Jena
Basics of List Data Structure
• Lists are ordered collections; you
can access any item by
specifying its index number.
Sisir Kumar Jena
Basics of List Data Structure
programming english math chemistry physics
0 1 2 3 4
-5 -4 -3 -2 -1
subjects
Sisir Kumar Jena
Basics
of
List
Data
Structure programming english math chemistry physics
0 1 2 3 4
-5 -4 -3 -2 -1
subjects
Sisir Kumar Jena
graphic era 2011 8.98 dehradun 25
0 1 2 3 4
-5 -4 -3 -2 -1
info
Basics
of
List
Data
Structure
Sisir Kumar Jena
• You can format the elements
of a list by using different
string methods.
programming english math chemistry physics
0 1 2 3 4
-5 -4 -3 -2 -1
subjects
Basics
of
List
Data
Structure
Sisir Kumar Jena
Basics of List Data Structure
• We can formulate messages by using list items.
programming english math chemistry physics
0 1 2 3 4
-5 -4 -3 -2 -1
subjects
Sisir Kumar Jena
Changing, adding, and deleting in List
• Changing a list item
Sisir Kumar Jena
Changing, adding, and deleting in List
• Adding an element to the list
• Simplest way to add a new element at the end of the list is to use the function
append().
Sisir Kumar Jena
Changing, adding, and deleting in List
• Adding elements to the
list
• The append() method
makes it easy to build lists
dynamically. For example,
you can start with an
empty list and then add
items to the list using a
series of append() calls.
Sisir Kumar Jena
Changing, adding, and deleting in List
• Inserting element at desired position
• You can add a new element at any position in your list by using the insert()
method.
Sisir Kumar Jena
Changing, adding, and deleting in List
• Removing element from a list
• If you know the position of the item you want to remove from a list, you can
use the del statement.
• You can no longer access the value that was removed from the list after the
del statement is used.
Sisir Kumar Jena
Changing, adding, and deleting in List
• Removing element from a list using pop()
• Sometimes you’ll want to use the value of an item after you remove it from a
list.
• The pop() method removes the last item in a list, but it lets you work with
that item after removing it.
• If you don’t specify the index position of an element, you can delete the last
element from the list.
• You can use pop() to remove an item from any position in a list by including
the index of the item you want to remove in parentheses.
• When you want to delete an item from a list and not use that item in any way,
use the del statement; if you want to use an item as you remove it, use the
pop() method.
Sisir Kumar Jena
Changing, adding, and deleting in List
• Removing element from a list using pop()
Sisir Kumar Jena
Changing, adding, and deleting in List
• Removing element from a list using pop()
Sisir Kumar Jena
Changing, adding, and deleting in List
• Removing an item by value
• Sometimes you won’t know the position of the value you want to remove
from a list. If you only know the value of the item you want to remove, you
can use the remove() method.
Sisir Kumar Jena
Changing, adding, and deleting in List
• Removing an item by value using remove() method
Sisir Kumar Jena
Changing, adding, and deleting in List
• Removing an item by value using remove() method
• NOTE
The remove() method deletes only the first occurrence of the value you
specify. If there’s a possibility the value appears more than once in the list,
you’ll need to use a loop to make sure all occurrences of the value are removed.
Sisir Kumar Jena
Organizing a List
• Python provides a number of different ways to organize your lists.
• Sorting a list permanently using sort() method.
• Python’s sort() method makes it relatively easy to sort a list in alphabetical
order.
Sisir Kumar Jena
Organizing a List
• Sorting a list permanently using sort() method.
• You can also sort this list in reverse alphabetical order by passing the
argument reverse=True to the sort() method.
Sisir Kumar Jena
Organizing a List
• Sorting a list temporarily using sorted() method.
• The sorted() function lets you display your list in a particular order but
doesn’t affect the actual order of the list.
Sisir Kumar Jena
Organizing a List
• Sorting a list temporarily using sorted() method.
• The sorted() function can also accept a reverse=True argument if you
want to display a list in reverse alphabetical order.
Sisir Kumar Jena
Organizing a List
• NOTE
• Sorting a list alphabetically is a bit more complicated when all the values are
not in lowercase. There are several ways to interpret capital letters when
determining a sort order and specifying the exact order can be more complex
than we want to deal with at this time.
Sisir Kumar Jena
Printing a List in reverse order
• To reverse the original order of a list, you can use the reverse()
method.
Sisir Kumar Jena
Printing a List in reverse order
• The reverse() method changes the order of a list permanently, but
you can revert to the original order anytime by applying reverse()
to the same list a second time.
Sisir Kumar Jena
Finding the length of a list
• You can quickly find the length of a list by using the len() function.
• Python counts the items in a list starting with one, so you shouldn’t
run into any off by-one errors when determining the length of a list.
Sisir Kumar Jena
References
• Book Reference
• Matthes, Eric. Python crash course: A hands-on, project-based
introduction to programming. no starch press, 2019.
Data Structures: Dictionary
and Tuple
Sisir Kumar Jena
Content
• Dictionary
• Tuple
Sisir Kumar Jena
Dictionary
Sisir Kumar Jena
What is dictionaries?
• A dictionary in Python is a collection of key-value pairs wrapped in
braces, {}.
d = {
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}
Sisir Kumar Jena
What is dictionaries?
• Each key is connected to a value, and you can use a key to access the
value associated with that key.
• A key’s value can be a number, a string, a list, or even another
dictionary.
• Every key is connected to its value by a colon, and individual key-value
pairs are separated by commas.
Sisir Kumar Jena
What is dictionaries?
• Once you’ve defined a dictionary, you can display its contents, the
same as you can do for a list.
Sisir Kumar Jena
Accessing Values in a Dictionary?
• Dictionary elements are not accessed by numerical index:
Sisir Kumar Jena
Accessing Values in a Dictionary?
• To get the value associated with a key, give the name of the dictionary
and then place the key inside a set of square brackets.
Sisir Kumar Jena
Adding New Key-Value Pairs
• To add a new key-value pair, you would give the name of the dictionary
followed by the new key in square brackets along with the new value.
• As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.
Sisir Kumar Jena
Updating New Key-Value Pairs
• If you want to update an entry, you can just assign a new value to an
existing key:
Sisir Kumar Jena
Removing Key-Value Pairs
• When you no longer need a piece of information that’s stored in a
dictionary, you can use the del statement to completely remove a
key-value pair.
Be
aware
that
the
deleted
key-value
pair
is
removed
permanently.
NOTE
Sisir Kumar Jena
Dictionary Key Vs. List Indices
• The syntax may look similar, but you can’t treat a dictionary like a list.
Because, in this example 0, 1, 2 … is treated as key; not index.
Sisir Kumar Jena
Starting with an Empty Dictionary
• It’s sometimes convenient, or even necessary, to start with an empty
dictionary and then add each new item to it.
Sisir Kumar Jena
Starting with an Empty Dictionary
Sisir Kumar Jena
Starting with an Empty Dictionary
• This example exhibits another feature of dictionaries:
• the values contained in the dictionary don’t need to be the same
type.
• In student,
• some of the values are strings,
• one is an integer,
• one is a list,
• and one is another dictionary.
Sisir Kumar Jena
Home Task
• Based on the previous slide, we know that “the values contained in
the dictionary don’t need to be the same type”. It can be strings,
integers, list, even dictionaries itself. How can you access the list item,
when the entire list is a part of a dictionary. Similarly, how can you
access a dictionary’s element when the entire dictionary is an
element of another dictionary.
Sisir Kumar Jena
Starting with an Empty Dictionary
• Just as the values in a dictionary don’t need to be of the same type,
the keys don’t either:
Sisir Kumar Jena
Tuples
Sisir Kumar Jena
What is Tuples?
• Sometimes you’ll want to create a list of items that cannot change.
Tuples allow you to do just that.
• A tuple is a collection which is ordered and unchangeable
(immutable).
• A tuple looks just like a list except you use parentheses instead of
square brackets.
• Once you define a tuple, you can access individual elements by using
each item’s index, just as you would for a list.
Sisir Kumar Jena
Creating a
Tuple
Sisir Kumar Jena
Creating a Tuple
• Tuples are technically defined by the presence of a comma; the
parentheses make them look neater and more readable. If you want
to define a tuple with one element, you need to include a trailing
comma:
Sisir Kumar Jena
Accessing Tuple elements
• Like lists, the
elements of a tuple
can also be
accessed through
their index
numbers.
• Accessing out of
index leads to
IndexError
34 87 -56 44 -32
0 1 2 3 4
-5 -4 -3 -2 -1
Tuple
index
index
Sisir Kumar Jena
Changing a Tuple
• Let’s see what happens if we try to change one of the items in the
tuple.
Sisir Kumar Jena
Slicing
• Like lists, you can also apply slicing operations on Tuples.
Sisir Kumar Jena
Concatenating two tuples
Sisir Kumar Jena
Repeat elements in a tuple
• We can also repeat the
elements in a tuple for a
given number of times using
the * operator.
Sisir Kumar Jena
Some other operations on Tuples
• Deleting a tuple
Sisir Kumar Jena
Some other operations on Tuples
• Methods that add items or remove items are not available with tuple.
Only the following two methods are available.
Sisir Kumar Jena
Some other operations on Tuples
• Membership Test
Sisir Kumar Jena
Home Task
• Prepare a brief note on the differences and similarities between Lists,
Dictionaries and Tuples.
Sisir Kumar Jena
References
• Book Reference
• Matthes, Eric. Python crash course: A hands-on, project-based
introduction to programming. no starch press, 2019.
• Website
• https://realpython.com/python-dicts/
• https://www.w3schools.com/python/python_dictionaries.asp
• https://www.programiz.com/python-programming/tuple
Control Statements
Sisir Kumar Jena
Content
• if statement
• else statement
• elif statement
• while loop
• break and continue
• for loop
• range()
• pass
• Nested loop
Sisir Kumar Jena
Selection with if statement
• An if statement’s clause (that is, the block following the if
statement) will execute if the statement’s condition is True. The
clause is skipped if the condition is False.
• In Python, an if statement consists of the following:
• The if keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the if clause)
Sisir Kumar Jena
Selection with if statement
• Syntax
if condition:
statement1
statement2
.
.
.
Other statements
condition
statement1
statement2
.
.
.
Other statements
False
True
Sisir Kumar Jena
Selection with if statement
• Example: Write a program to read four integers and find the highest
number between them.
Output
Program
Sisir Kumar Jena
else Statement
• An if clause can optionally be followed by an else statement. The
else clause is executed only when the if statement’s condition is
False.
• An else statement doesn’t have a condition, and in code, an else
statement always consists of the following:
• The else keyword
• A colon
• Starting on the next line, an indented block of code (called the else clause)
Sisir Kumar Jena
else Statement
• Example: Write a program to read in integer from the user and check
whether it is even or odd.
Output
Program
Sisir Kumar Jena
elif statement
• The elif statement is an “else if” statement that always follows an
if or another elif statement.
• It provides another condition that is checked only if all of the previous
conditions were False.
• In code, an elif statement always consists of the following:
• The elif keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the elif clause)
Sisir Kumar Jena
elif statement
Program Output
Let’s analyze the program code
and predict the output
Sisir Kumar Jena
elif statement Let’s analyze the previous code by
altering sequence and predict the output
Program Output
Sisir Kumar Jena
elif statement
• Optionally, you can have an
else statement after the
last elif statement.
• In that case, it is
guaranteed that at least
one (and only one) of the
clauses will be executed.
• If the conditions in every
if and elif statement are
False, then the else clause
is executed.
Execute the Program and see the output
Sisir Kumar Jena
while loop statement
• You can make a block of code execute over and over again using a
while statement.
• In code, a while statement always consists of the following:
• The while keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the while clause)
Sisir Kumar Jena
while loop statement
• Syntax
initialization
while condition:
statement1
statement2
.
.
increment/decrement
Other statements
Initialization
statement1
statement2
.
.
Increment/Decrement
Condition
Other Statements
True
True
False
Sisir Kumar Jena
while loop statement
• Example: Write a program to add the digits of a number
Program Output
Sisir Kumar Jena
break statement
• There is a shortcut to getting the program execution to break out of a
while loop’s clause early. If the execution reaches a break
statement, it immediately exits the while loop’s clause.
• In code, a break statement simply contains the break keyword.
Sisir Kumar Jena
break statement
Program Output
Sisir Kumar Jena
continue statement
• Like break statements, continue statements are used inside loops.
• When the program execution reaches a continue statement, the
program execution immediately jumps back to the start of the loop
and reevaluates the loop’s condition.
Sisir Kumar Jena
continue statement
Program Output
Sisir Kumar Jena
for loop
• The while loop keeps looping while its condition is True (which is the reason
for its name), but what if you want to execute a block of code only a certain
number of times? You can do this with a for loop statement.
• In code, a for statement looks something like for i in range(5): and
includes the following:
• The for keyword
• A variable name
• The in keyword
• A call to the range() method with up to three integers passed to it
• A colon
• Starting on the next line, an indented block of code (called the for clause)
Sisir Kumar Jena
for loop
• Syntax
for var_name in range(int, int, int):
statement1
statement2
.
.
.
Other statements
range can
take up to 3
integers
Sisir Kumar Jena
for loop
Program Output
Sisir Kumar Jena
for loop
Program Output
Sisir Kumar Jena
The Starting, Stopping, and Stepping
Arguments to range()
for k in range(5)
k varies from 0 to 4
for k in range(10, 20)
k varies from 10 to 19
for k in range(0, 10, 2)
k will have values:
0
2
4
6
8
Sisir Kumar Jena
The Starting, Stopping, and Stepping
Arguments to range()
Sisir Kumar Jena
The Starting, Stopping, and Stepping
Arguments to range()
• you can even use a negative number for the step argument to make
the for loop count down instead of up.
Sisir Kumar Jena
pass statement
• As its name suggests, pass statement does nothing.
• It is used when a statement or a condition is required to be present in
the program, but we do not want any command or code to execute.
• pass statement is usually used while creating a method, which we do
not want to use right now.
• The pass statement is used as a placeholder for future code!!
• Difference between pass and continue
• continue forces the loop to start at the next iteration whereas pass means
"there is no code to execute here" and will continue through the remainder of
the loop body.
Sisir Kumar Jena
pass statement
Program Output Program Output
Sisir Kumar Jena
Importing Modules
• Python also comes with a set of modules called the standard library.
• Each module is a Python program that contains a related group of
functions that can be embedded in your programs.
• For example, the math module has mathematics related functions, the
random module has random number-related functions, and so on.
• Before you can use the functions in a module, you must import the module
with an import statement.
• In code, an import statement consists of the following:
• The import keyword
• The name of the module
• Optionally, more module names, as long as they are separated by commas
Sisir Kumar Jena
Number Guessing Game
Program
Sisir Kumar Jena
Number Guessing Game
Output
Sisir Kumar Jena
Nested Loops
• Placing loop inside another loop is called nested loop.
• Loops can be nested to any desired levels.
• Proper indentation is necessary to use nested loop.
Program Output
Sisir Kumar Jena
Home Task
• Read more about nested loops and try to print the following patterns.
Sisir Kumar Jena
Home Task
1. While purchasing certain items, a discount of 10% is offered if the quantity purchased
is more than 1000. If the quantity and price per item are input through the keyboard,
write a program to calculate the total expenses.
2. Write a program that prints a number, its square, and cube repeatedly in the range (1,
n).
3. Write a program to print Floyd’s triangle.
4. Write a program to check a year is leap year or not.
5. Write a program to print the digits of a given number.
6. Write a program to find the factorial of a number.
7. Write a program to generate the Fibonacci series.
8. Write a program to reverse a number.
9. Write a program to check whether a number is a palindrome or not.
10. Write a program to generate the multiplication table up to 10 using a for loop.
Sisir Kumar Jena
References
• Book Reference
• Sweigart, Al. Automate the boring stuff with Python: practical
programming for total beginners. No Starch Press, 2019.
File Handling
Sisir Kumar Jena
Contents
• Introduction
• Types of File
• Opening and Closing a file
• File Opening Modes
• File Object Attributes
• Reading from and Writing to file
• write()
• writeline()
• read()
• readline()
• readlines()
• Loop over the content of a file
Sisir Kumar Jena
Introduction
• We write python code to process data coming from different sources.
• Until now, we process the data supplied by the user through console.
• But, what about processing data that comes from a file?
• We need to learn some file processing techniques and this talk is
dedicated in that respect.
Sisir Kumar Jena
Types of File
• Text Files
• Binary Files
Sisir Kumar Jena
Opening and Closing a File
Opening a file
Closing a file
Process
Sisir Kumar Jena
File Opening
• Example
• Output
• This line will open the file in
write mode
• The default mode is read mode
(if don’t specify the mode)
I suggest you
should print fp
Sisir Kumar Jena
File Opening Modes
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default
mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file.
This is the default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning
of the file.
Reference
https://www.tutorialspoint.com/python/python_files_io.htm
Sisir Kumar Jena
File Opening Modes
Reference
https://www.tutorialspoint.com/python/python_files_io.htm
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a
new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does
not exist, creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
Sisir Kumar Jena
File Opening Modes
Reference
https://www.tutorialspoint.com/python/python_files_io.htm
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is
in the append mode. If the file does not exist, it creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists.
The file opens in the append mode. If the file does not exist, it creates a new file for reading and
writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the
file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file
for reading and writing.
Sisir Kumar Jena
File Object Attributes
• fileObj.closed
• Returns true if file is closed
otherwise false
• fileObj.mode
• Returns the access mode
• fileObj.name
• Returns the name of the file
Output
Program
Sisir Kumar Jena
Reading from and Writing to Files
• write()
• writelines()
• read()
• readlines()
Sisir Kumar Jena
write() method
• The write() method is used to write a string to an already opened
file. This string may include numbers, special characters, or other
symbols.
• Write() method does not add a new line character to the end of the
string
• write() method returns nothing
fileObj.write(string)
Syntax
Sisir Kumar Jena
write() method
Program
Sisir Kumar Jena
writeline() method
• Used to write list of strings
fileObj.writeline(list_name)
Syntax
Sisir Kumar Jena
writeline() method
Program
Sisir Kumar Jena
writeline() method
• Home Task
• I want the file to look like this after writing. What to do?
Sisir Kumar Jena
read() method
• This method is used to read a string from an already opened file.
• Count is an optional parameter
• If count is missing or has a negative value, then it reads the entire
contents of the file.
• read method returns newline as 'n'
fileObj.read(10)
Syntax
Sisir Kumar Jena
read() method
Program
Output
Sisir Kumar Jena
Home Task
• Rewrite the above program and pass the count value as 10 and check
the output.
Sisir Kumar Jena
readline() method
• It is used to read a single line from the file.
• The method returns an empty strig when the end of file has been
reached.
• A blank line in a file also has an 'n' character, therefore the
readline() method will print a blank line at that place.
Sisir Kumar Jena
readline() method
Program
Output
Sisir Kumar Jena
readlines() method
Mark the s here
Program
Output
Sisir Kumar Jena
Loop over file content
• You can also loop over the file content and display it
Program
Output
Sisir Kumar Jena
Home Task
• Write a program to copy the content of one file to another file.
Sisir Kumar Jena
References
• Book Reference
• Reema, Thareja. "Python Programming: Using Problems Solving
Approach." (2020).

Mais conteúdo relacionado

Semelhante a Python_slides.pdf

python intro and installation.pptx
python intro and installation.pptxpython intro and installation.pptx
python intro and installation.pptxadityakumawat625
 
python classes in thane
python classes in thanepython classes in thane
python classes in thanefaizrashid1995
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unitmichaelaaron25322
 
Introduction to python for dummies
Introduction to python for dummiesIntroduction to python for dummies
Introduction to python for dummiesLalit Jain
 
Python_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxPython_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxlemonchoos
 
Python programming
Python programmingPython programming
Python programmingMegha V
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1Kanchilug
 
4_Introduction to Python Programming.pptx
4_Introduction to Python Programming.pptx4_Introduction to Python Programming.pptx
4_Introduction to Python Programming.pptxGnanesh12
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners Sujith Kumar
 
Python Tutorial | Python Programming Language
Python Tutorial | Python Programming LanguagePython Tutorial | Python Programming Language
Python Tutorial | Python Programming Languageanaveenkumar4
 
Python for students step by step guidance
Python for students step by step guidancePython for students step by step guidance
Python for students step by step guidanceMantoshKumar79
 
Introduction to Python Programming Basics
Introduction  to  Python  Programming BasicsIntroduction  to  Python  Programming Basics
Introduction to Python Programming BasicsDhana malar
 
Introduction-to-Python.pptx
Introduction-to-Python.pptxIntroduction-to-Python.pptx
Introduction-to-Python.pptxAyushDey1
 
Python tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyPython tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyTIB Academy
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1Ahmet Bulut
 
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.Niraj Bharambe
 
Training report 1923-b.e-eee-batchno--intern-54 (1).pdf
Training report 1923-b.e-eee-batchno--intern-54 (1).pdfTraining report 1923-b.e-eee-batchno--intern-54 (1).pdf
Training report 1923-b.e-eee-batchno--intern-54 (1).pdfYadavHarshKr
 

Semelhante a Python_slides.pdf (20)

python intro and installation.pptx
python intro and installation.pptxpython intro and installation.pptx
python intro and installation.pptx
 
python classes in thane
python classes in thanepython classes in thane
python classes in thane
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unit
 
Introduction to python for dummies
Introduction to python for dummiesIntroduction to python for dummies
Introduction to python for dummies
 
Python_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxPython_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptx
 
Python programming
Python programmingPython programming
Python programming
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
 
1-ppt-python.ppt
1-ppt-python.ppt1-ppt-python.ppt
1-ppt-python.ppt
 
4_Introduction to Python Programming.pptx
4_Introduction to Python Programming.pptx4_Introduction to Python Programming.pptx
4_Introduction to Python Programming.pptx
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
 
Python Tutorial | Python Programming Language
Python Tutorial | Python Programming LanguagePython Tutorial | Python Programming Language
Python Tutorial | Python Programming Language
 
Introduction python
Introduction pythonIntroduction python
Introduction python
 
Python for students step by step guidance
Python for students step by step guidancePython for students step by step guidance
Python for students step by step guidance
 
Introduction to Python Programming Basics
Introduction  to  Python  Programming BasicsIntroduction  to  Python  Programming Basics
Introduction to Python Programming Basics
 
Welcome_to_Python.pptx
Welcome_to_Python.pptxWelcome_to_Python.pptx
Welcome_to_Python.pptx
 
Introduction-to-Python.pptx
Introduction-to-Python.pptxIntroduction-to-Python.pptx
Introduction-to-Python.pptx
 
Python tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academyPython tutorial for beginners - Tib academy
Python tutorial for beginners - Tib academy
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
 
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
Python Book/Notes For Python Book/Notes For S.Y.B.Sc. I.T.
 
Training report 1923-b.e-eee-batchno--intern-54 (1).pdf
Training report 1923-b.e-eee-batchno--intern-54 (1).pdfTraining report 1923-b.e-eee-batchno--intern-54 (1).pdf
Training report 1923-b.e-eee-batchno--intern-54 (1).pdf
 

Último

BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleCeline George
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 

Último (20)

BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP Module
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 

Python_slides.pdf

  • 1. Introduction to Python Sisir Kumar Jena Assistant Professor, CSE Graphic Era Hill University
  • 2. Sisir Kumar Jena What is Python? • An object-oriented scripting language. • It is a high-level, interpreted, general-purpose programming language. • Released publicly in 1991. • Developed by: Guido van Rossum Guido van Rossum
  • 3. Sisir Kumar Jena Why Python in Popular? • Its open source, free and widely available with a massive open-source community. • It’s easier to learn than languages like C, C++, C# and Java, enabling novices and professional developers to get up to speed quickly. • It’s easier to read than many other popular programming languages. • It’s widely used in education. • It enhances developer productivity with extensive standard libraries and thousands of third-party open-source libraries, so programmers can write code faster and perform complex tasks with minimal code.
  • 4. Sisir Kumar Jena Why Python in Popular? • There are massive numbers of free open-source Python applications. • It’s popular in web development (e.g., Django, Flask). • It supports popular programming paradigms—procedural, functional, object oriented. • There are lots of capabilities for enhancing Python performance. • It’s used to build anything from simple scripts to complex apps with massive numbers of users, such as Dropbox, YouTube, Reddit, Instagram and Quora.
  • 5. Sisir Kumar Jena Why Python in Popular? • It’s popular in artificial intelligence, which is enjoying explosive growth, in part because of its special relationship with data science. • It’s widely used in the financial community. • There’s an extensive job market for Python programmers across many disciplines, especially in data-science-oriented positions, and Python jobs are among the highest paid of all programming jobs.
  • 6. Sisir Kumar Jena History • 1980s: Beginning the development of Python • Guido van Rossum worked that time in a project at the CWI, called Amoeba, a distributed operating system. • The language, he used at that time is the ABC language. • Van Rossum began exploring a scripting language with a syntax similar to ABC but with access to the Amoeba system calls. As a result, Van Rossum set out to create a new simple scripting language that could overcome ABC’s limitations. • He gave the name to its newly created language “Python”. • First released in 1991 as Python 0.9.0.
  • 7. Sisir Kumar Jena Why the name “Python” ? • Rossum, wanted his new language’s name to be short, original, and mysterious. • The name was inspired by Monty Python’s Flying Circus, a BBC comedy series.
  • 8. Sisir Kumar Jena Python Versions • First released it in 1991 as Python 0.9.0. • Python 2.0 was released in 16 October 2000 and introduced new features such as list comprehensions, cycle-detecting garbage collection, reference counting, and Unicode support. • Python 3.0, released in 3 December 2008, was a major revision that is not completely backward-compatible with earlier versions. • Python 2 was discontinued with version 2.7.18 in 2020. • Latest stable version is Python 3.10
  • 9. Sisir Kumar Jena Python versions Python 2 Python 3 Released Year: 2000 Relesed Year: 2008 More complex Syntax as compared to Python 3 Syntax is easy and simple By default, Strings are saved in ASCII format By default, String are saved in UNICODE format Print is a statement. Syntax: print “hello world” Print is a function. Syntax: print (“hello world”) Exception should be enclosed in notations Exception should be enclosed in parentheses To perform iterations, xrange() is used To perform iterations Range() is used
  • 10. Sisir Kumar Jena Features of Python • Open source: Python is publicly available open-source software. • Easy-to-learn: Popular (scripting/extension) language, clear and easy syntax, no type declarations, automatic memory management, high-level data types and operations, design to read (more English like syntax) and write (shorter code compared to C, C++, and Java) fast. • High-level Language: Python is an example of a high-level language like C, C++, Perl, and Java with low-level optimization. • Portable: High level languages are portable, which means they are able to run across all major hardware and software platforms with few or no change in source code. • Object-Oriented: Python is a full-featured object-oriented programming language, with features such as classes, inheritance, objects, and overloading.
  • 11. Sisir Kumar Jena Features of Python • Python is Interactive: Python has an interactive console where you get a Python prompt (command line) and interact with the interpreter directly to write and test your programs. This is useful for mathematical programming. • Interpreted: Python programs are interpreted, takes source code as input, and then compiles (to portable byte-code) each statement and executes it immediately. • Extendable: Python is often referred to as a "glue" language, meaning that it is capable of working in mixed-language environment. The Python interpreter is easily extended and can add a new built-in function or modules written in C/C++/Java code. • Libraries: Databases, web services, networking, numerical packages, graphical user interfaces, 3D graphics, others. • Supports: Support from online Python community
  • 12. Sisir Kumar Jena Setting up your programming environment • Python is a cross-platform programming language, which means it runs on all the major operating systems.
  • 13. Sisir Kumar Jena Python on Windows • Windows doesn’t always come with Python, so you’ll probably need to install it, and then install Sublime Text. • Check whether Python is installed on your system: • In the command prompt window, enter python in lowercase. If you get a Python prompt (>>>) in response, Python is installed on your system. • If error, goto https://www.python.org/downloads/
  • 16. Sisir Kumar Jena Python on Windows • Running Python in a terminal
  • 17. Sisir Kumar Jena Python on Windows • Enter the following line in your Python session, and make sure you see the output Hello Python interpreter! • To close the terminal session, press ctrl-Z and then press enter, or enter the command exit(). • You can install sublime text at https://sublimetext.com/.
  • 18. Sisir Kumar Jena Python on MacOS • Python is already installed on most macOS systems, but it’s most likely an outdated version that you won’t want to learn on. • Check whether Python is installed on your system: • Open a terminal window by going to Applications  Utilities  Terminal. • You can also press spacebar, type terminal, and then press enter.
  • 19. Sisir Kumar Jena Python on MacOS • To see which version of Python is installed, enter python with a lowercase p—this also starts the Python interpreter within the terminal, allowing you to enter Python commands. • Once you’ve seen this output, press ctrl-D or enter exit() to leave the Python prompt and return to a terminal prompt.
  • 20. Sisir Kumar Jena Python on MacOS • To check whether you have Python 3 installed, enter the command python3. • If Python 3 isn’t installed by default, you’ll need to install it manually. • When you’re finished, enter the following at a terminal prompt: $ python3 -- version Python 3.10.5
  • 21. Sisir Kumar Jena Python on Linux • Linux systems are designed for programming, so Python is already installed on most Linux computers. • Checking your version of Python • Open a terminal window by running the Terminal application on your system (in Ubuntu, you can press ctrl-alt-T). • To find out whether Python is installed, enter python with a lowercase p.
  • 22. Sisir Kumar Jena Python on Linux • To check for Python 3, you might have to specify that version; try the command python3:
  • 23. Sisir Kumar Jena Python on Linux • Installing a Text Editor • Geany is a simple text editor: it’s easy to install. • Running your first program • Open Geany • Save an empty Python file (File  Save As) called hello_world.py. The extension .py tells Geany your file will contain a Python program. • After you’ve saved your file, enter the following line:
  • 24. Sisir Kumar Jena Running your first program • Install Sublime text
  • 25. Sisir Kumar Jena Running your first program Install Sublime text
  • 26. Sisir Kumar Jena Running your first program • First create a folder at your desired location and name it as per your choice. • It’s best to use lowercase letters and underscores for spaces in file and folder names, because Python uses these naming conventions.
  • 27. Sisir Kumar Jena Running your first program • Type the first line as shown in the image. • Press ctrl+B to run your code. • The output is shown in the image on right.
  • 28. Sisir Kumar Jena References • Book Reference • Matthes, Eric. Python crash course: A hands-on, project-based introduction to programming. no starch press, 2019. • Deitel, P., and H. Deitel. "Introduction to Python for Computer Science and Data Science." (2020). • Cite Reference: accessed on 16th June 2022. • https://docs.python.org/3.4/tutorial/ • https://intellipaat.com/blog/tutorial/python-tutorial/ • https://www.w3schools.com/python/python_intro.asp • https://www.javatpoint.com/python-tutorial • https://www.scaler.com/topics/python/what-is-python/ • https://www.w3resource.com/python/python-tutorial.php
  • 30. Sisir Kumar Jena Content • IDLE • Comments • Variables • Keywords • Quotations • Input and Output
  • 31. Sisir Kumar Jena Getting Started • After the installation, you can see a python environment IDLE is installed in your Windows machine. • IDLE stands for Integrated Development and Learning Environment.
  • 32. Sisir Kumar Jena IDLE • Interactive Mode
  • 33. Sisir Kumar Jena IDLE • Interactive Mode • If we want to repeat prior command in interactive window, you can use  key to scroll backward through commands history and  key to scroll forward. Use Enter key to select it. Using these keys, your prior commands will be recalled and displayed, and we may edit or rerun them. • You can quit the interpreter by pressing Ctrl+D. • To restart the interpreter, you can type Ctrl+F6 will restart the shell. • You can also use commands as follows to know more: • credits • copyright • license() • help()
  • 34. Sisir Kumar Jena IDLE • Script Mode • In interactive mode you can run small piece of code and you can not save it. For running large programs and saving for future, you need to use script mode.
  • 35. Sisir Kumar Jena IDLE • Script Mode • Execute the code using RUN option or press Ctrl + F5
  • 36. Sisir Kumar Jena Comments • In Python we use # symbol to write comments. This is a comment line
  • 37. Sisir Kumar Jena Comments • When # is written inside two bouble quote it is considered as a character. • You can write multi line comment by putting a # in front of each line.
  • 38. Sisir Kumar Jena Variables • Variables are names given to memory locations. • We can store any value in that location and refer it by the variable name. 23 age A memory segment Variable Name Variable Value
  • 39. Sisir Kumar Jena Variables • In python, variable do not require declaration.
  • 40. Sisir Kumar Jena Variables • Let's try a simple example:
  • 41. Sisir Kumar Jena Variables • In python, a variable can store any type of data.
  • 42. Sisir Kumar Jena Variables • You can assign a single value to multiple variables or multiple values to multiple variables in a single statement.
  • 43. Sisir Kumar Jena Variables • Referring a variable that was not assigned a value causes error.
  • 44. Sisir Kumar Jena Variables • You can delete a variable in use at any point of time using del statement.
  • 45. Sisir Kumar Jena Variables • Naming a variable • Variable names can contain only letters, numbers, and underscores. They can start with a letter or an underscore, but not with a number. For instance, you can call a variable message_1 but not 1_message. • Spaces are not allowed in variable names, but underscores can be used to separate words in variable names. For example, greeting_message works, but greeting message will cause errors. • Avoid using Python keywords and function names as variable names; that is, do not use words that Python has reserved for a particular programmatic purpose, such as the word print.
  • 46. Sisir Kumar Jena Variables • Naming Variables • Variable names should be short but descriptive. For example, name is better than n, student_name is better than s_n, and name_length is better than length_of_persons_name. • Be careful when using the lowercase letter l and the uppercase letter O because they could be confused with the numbers 1 and 0. • It is better to use lower case letter to name a variable.
  • 47. Sisir Kumar Jena Keywords (Reserved Words) • These words have predefined meaning and known to Python interpreter. • We can not use these words for any other purpose; like declaring variables using these words causes error. and break continue del else exec for global import is not pass raise try with assert class def elif except finally from if in lambda or print return while yield
  • 48. Sisir Kumar Jena Keywords (Reserved Words) • What happen when I am trying to use keywords as variable name?
  • 49. Sisir Kumar Jena Indentation • Indentation is the leading whitespace ( spaces and tabs ) before any statement in Python. • Python treats the statements with the same indentation level (statements with an equal number of whitespaces before them) as a single code block.
  • 50. Sisir Kumar Jena Indentation • A program with proper indentation does not lead to any error.
  • 51. Sisir Kumar Jena Indentation • Improper indentation leads to syntactical error.
  • 52. Sisir Kumar Jena Indentation • You can use any number of space to indent your code, but it should be at least one. • Better way to indent is to use tab key.
  • 53. Sisir Kumar Jena Indentation • You have to use the same number of spaces in the same block of code.
  • 55. Sisir Kumar Jena Quotations • Python uses three types quotations to represent string: • Single quote ('string') • Double quote ("string") • Triple quote ('''string''') • The most common use of single quote and double quote is to enclose string.
  • 57. Sisir Kumar Jena Quotations • We should not mix the quotations, otherwise it will lead to error.
  • 58. Sisir Kumar Jena Quotations • If your string itself contains single or double quote, then escaping them is easy in Python. • Let your string contains a double quote (or a single quote) that you want to print, then enclose the entire string using single quote (or double quote).
  • 59. Sisir Kumar Jena Quotations • If your string contains both single quote and double quote and you want to print them, then use triple quote to enclose the entire string.
  • 60. Sisir Kumar Jena Quotations • Another use of triple quote to enclose multiple lines.
  • 61. Sisir Kumar Jena Input and Output • As like other programming language, the programmer sometimes require inputs from the user and act upon that input. • Python provides a function to read inputs from the user: • input() • input() • This function reads the input from the user, convert it into string, and then assign it to the variable.
  • 65. Sisir Kumar Jena References • Book Reference • Matthes, Eric. Python crash course: A hands-on, project-based introduction to programming. no starch press, 2019. • Deitel, P., and H. Deitel. "Introduction to Python for Computer Science and Data Science." (2020). • Reema, Thareja. "Python Programming: Using Problems Solving Approach." (2020). • Websites: Accessed on 5th July 2022 • https://www.w3schools.com/python/gloss_python_indentation.asp • https://www.scaler.com/topics/python/indentation-in-python/
  • 66. Data Types and Operators
  • 67. Sisir Kumar Jena Content • Data Types • Operators
  • 68. Sisir Kumar Jena Data Types • We can store different type of data in a variable. • Standard data types supported in Python is given below: Data Types Numbers String Lists Dictionary Tuple Sets Integers Floating Point Complex Boolean Sequences
  • 69. Sisir Kumar Jena Numbers • Integers • var = 45 • Floating Points • var = 8.98 • Complex • var = 45j
  • 70. Sisir Kumar Jena Strings • A string is a series of characters. • Anything inside quotes is considered a string in Python. • Example: • 'this is a string' • "this is a string" • '''this is a string'''
  • 71. Sisir Kumar Jena Strings • You can store an entire string inside a variable.
  • 72. Sisir Kumar Jena Strings • Individual characters in a string can be accessed through its index number. • Index numbers can be positive or negative.
  • 74. Sisir Kumar Jena String G R A P H I C E R A H I L L 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 String Index Index
  • 75. Sisir Kumar Jena String • String slicing
  • 76. Sisir Kumar Jena Strings • You can skip characters at regular interval. • You can reverse the string by using -1 as reverse skipping. • You can not slice string in reverse order.
  • 77. Sisir Kumar Jena Strings • Home Task • What happen to this code? >>> univ="Graphic Era Hill" >>> univ[::-2] >>> univ[:15:] >>> univ[:5:] >>> univ[:5:1] >>> univ[:5:2] >>> univ[:5:-1] >>> univ[0:16:1:1]
  • 78. Sisir Kumar Jena Strings • String Concatenation • String Repetition (Multiplication)
  • 79. Sisir Kumar Jena String Functions • len() • Find the length of a string • casefold() • Convert to lower case • lower() • Convert to lower case • upper() • Convert to upper case • title() • Convert first character of each word to upper case • swapcase() • Convert lower to upper and vice versa
  • 80. Sisir Kumar Jena String functions • capitalize() • Capitalize the first character of a string • count() • Count the number of occurrences of a substring • index() • Searches the string for a specified value and returns the position of where it was found • find() • Searches the string for a specified value and returns the position of where it was found
  • 81. Sisir Kumar Jena String Functions • isalnum() • Returns True if all characters in the string are alphanumeric • isalpha() • Returns True if all characters in the string are in the alphabet • isdigit() • Returns True if all characters in the string are digits
  • 82. Sisir Kumar Jena String Functions • You can find more string functions at: • https://www.w3schools.com/python/python_ref_string.asp
  • 83. Sisir Kumar Jena Operators • Operators are symbols used for performing an operation on operands. • In Python, the operators are classified as follows: • Arithmetic operators • Comparison (relational) operators • Logical operators • Assignment operators • Identity operators • Membership operators • Bitwise operators
  • 84. Sisir Kumar Jena Arithmetic Operators Operator Name Example + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y
  • 85. Sisir Kumar Jena Comparison Operator Operator Name Example == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y
  • 86. Sisir Kumar Jena Logical Operator Operator Description Example and Returns True if both x < 5 and x < 10 statements are true or Returns True if one of x < 5 or x < 4 the statements is true not Reverse the result, returns not(x < 5 and x < 10) False if the result is true
  • 88. Sisir Kumar Jena Assignment Operator Operator Example Same As = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3
  • 89. Sisir Kumar Jena Assignment Operator Operator Example Same As //= x //= 3 x = x // 3 **= x **= 3 x = x ** 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3
  • 90. Sisir Kumar Jena Identity Operator Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location. Operator Description Example is Returns True if both variables are the x is y same object is not Returns True if both variables are not x is not y the same object Not in Course
  • 91. Sisir Kumar Jena Membership Operator Membership operators are used to test if a sequence is presented in an object Operator Description Example in Returns True if a sequence with the x in y specified value is present in the object not in Returns True if a sequence with the x not in y specified value is not present in the object Not in Course
  • 92. Sisir Kumar Jena Bitwise Operator Operator Name Description & AND Sets each bit to 1 if both bits are 1 | OR Sets each bit to 1 if one of two bits is 1 ^ XOR Sets each bit to 1 if only one of two bits is 1 ~ NOT Inverts all the bits << Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off >> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
  • 94. Sisir Kumar Jena References • Book Reference • Matthes, Eric. Python crash course: A hands-on, project-based introduction to programming. no starch press, 2019. • Reema, Thareja. "Python Programming: Using Problems Solving Approach." (2020). • Websites: Accessed on 6th July 2022 • https://www.w3schools.com/python/python_operators.asp • https://www.w3schools.com/python/python_ref_string.asp
  • 96. Sisir Kumar Jena Content • Basics of List Data Structure • Changing, adding, and deleting in List • Organizing a List • Printing a list in reverse order • Finding the length of a list
  • 97. Sisir Kumar Jena Basics of List Data Structure • What is a List? • A list is a collection of items in a particular order. • You can put anything you want into a list, and the items in your list don’t have to be related in any particular way. • it’s a good idea to make the name of your list plural, such as letters, digits, or names. • In Python, square brackets ([]) indicate a list, and individual elements in the list are separated by commas.
  • 98. Sisir Kumar Jena Basics of List Data Structure • Lists are ordered collections; you can access any item by specifying its index number.
  • 99. Sisir Kumar Jena Basics of List Data Structure programming english math chemistry physics 0 1 2 3 4 -5 -4 -3 -2 -1 subjects
  • 100. Sisir Kumar Jena Basics of List Data Structure programming english math chemistry physics 0 1 2 3 4 -5 -4 -3 -2 -1 subjects
  • 101. Sisir Kumar Jena graphic era 2011 8.98 dehradun 25 0 1 2 3 4 -5 -4 -3 -2 -1 info Basics of List Data Structure
  • 102. Sisir Kumar Jena • You can format the elements of a list by using different string methods. programming english math chemistry physics 0 1 2 3 4 -5 -4 -3 -2 -1 subjects Basics of List Data Structure
  • 103. Sisir Kumar Jena Basics of List Data Structure • We can formulate messages by using list items. programming english math chemistry physics 0 1 2 3 4 -5 -4 -3 -2 -1 subjects
  • 104. Sisir Kumar Jena Changing, adding, and deleting in List • Changing a list item
  • 105. Sisir Kumar Jena Changing, adding, and deleting in List • Adding an element to the list • Simplest way to add a new element at the end of the list is to use the function append().
  • 106. Sisir Kumar Jena Changing, adding, and deleting in List • Adding elements to the list • The append() method makes it easy to build lists dynamically. For example, you can start with an empty list and then add items to the list using a series of append() calls.
  • 107. Sisir Kumar Jena Changing, adding, and deleting in List • Inserting element at desired position • You can add a new element at any position in your list by using the insert() method.
  • 108. Sisir Kumar Jena Changing, adding, and deleting in List • Removing element from a list • If you know the position of the item you want to remove from a list, you can use the del statement. • You can no longer access the value that was removed from the list after the del statement is used.
  • 109. Sisir Kumar Jena Changing, adding, and deleting in List • Removing element from a list using pop() • Sometimes you’ll want to use the value of an item after you remove it from a list. • The pop() method removes the last item in a list, but it lets you work with that item after removing it. • If you don’t specify the index position of an element, you can delete the last element from the list. • You can use pop() to remove an item from any position in a list by including the index of the item you want to remove in parentheses. • When you want to delete an item from a list and not use that item in any way, use the del statement; if you want to use an item as you remove it, use the pop() method.
  • 110. Sisir Kumar Jena Changing, adding, and deleting in List • Removing element from a list using pop()
  • 111. Sisir Kumar Jena Changing, adding, and deleting in List • Removing element from a list using pop()
  • 112. Sisir Kumar Jena Changing, adding, and deleting in List • Removing an item by value • Sometimes you won’t know the position of the value you want to remove from a list. If you only know the value of the item you want to remove, you can use the remove() method.
  • 113. Sisir Kumar Jena Changing, adding, and deleting in List • Removing an item by value using remove() method
  • 114. Sisir Kumar Jena Changing, adding, and deleting in List • Removing an item by value using remove() method • NOTE The remove() method deletes only the first occurrence of the value you specify. If there’s a possibility the value appears more than once in the list, you’ll need to use a loop to make sure all occurrences of the value are removed.
  • 115. Sisir Kumar Jena Organizing a List • Python provides a number of different ways to organize your lists. • Sorting a list permanently using sort() method. • Python’s sort() method makes it relatively easy to sort a list in alphabetical order.
  • 116. Sisir Kumar Jena Organizing a List • Sorting a list permanently using sort() method. • You can also sort this list in reverse alphabetical order by passing the argument reverse=True to the sort() method.
  • 117. Sisir Kumar Jena Organizing a List • Sorting a list temporarily using sorted() method. • The sorted() function lets you display your list in a particular order but doesn’t affect the actual order of the list.
  • 118. Sisir Kumar Jena Organizing a List • Sorting a list temporarily using sorted() method. • The sorted() function can also accept a reverse=True argument if you want to display a list in reverse alphabetical order.
  • 119. Sisir Kumar Jena Organizing a List • NOTE • Sorting a list alphabetically is a bit more complicated when all the values are not in lowercase. There are several ways to interpret capital letters when determining a sort order and specifying the exact order can be more complex than we want to deal with at this time.
  • 120. Sisir Kumar Jena Printing a List in reverse order • To reverse the original order of a list, you can use the reverse() method.
  • 121. Sisir Kumar Jena Printing a List in reverse order • The reverse() method changes the order of a list permanently, but you can revert to the original order anytime by applying reverse() to the same list a second time.
  • 122. Sisir Kumar Jena Finding the length of a list • You can quickly find the length of a list by using the len() function. • Python counts the items in a list starting with one, so you shouldn’t run into any off by-one errors when determining the length of a list.
  • 123. Sisir Kumar Jena References • Book Reference • Matthes, Eric. Python crash course: A hands-on, project-based introduction to programming. no starch press, 2019.
  • 125. Sisir Kumar Jena Content • Dictionary • Tuple
  • 127. Sisir Kumar Jena What is dictionaries? • A dictionary in Python is a collection of key-value pairs wrapped in braces, {}. d = { <key>: <value>, <key>: <value>, . . . <key>: <value> }
  • 128. Sisir Kumar Jena What is dictionaries? • Each key is connected to a value, and you can use a key to access the value associated with that key. • A key’s value can be a number, a string, a list, or even another dictionary. • Every key is connected to its value by a colon, and individual key-value pairs are separated by commas.
  • 129. Sisir Kumar Jena What is dictionaries? • Once you’ve defined a dictionary, you can display its contents, the same as you can do for a list.
  • 130. Sisir Kumar Jena Accessing Values in a Dictionary? • Dictionary elements are not accessed by numerical index:
  • 131. Sisir Kumar Jena Accessing Values in a Dictionary? • To get the value associated with a key, give the name of the dictionary and then place the key inside a set of square brackets.
  • 132. Sisir Kumar Jena Adding New Key-Value Pairs • To add a new key-value pair, you would give the name of the dictionary followed by the new key in square brackets along with the new value. • As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
  • 133. Sisir Kumar Jena Updating New Key-Value Pairs • If you want to update an entry, you can just assign a new value to an existing key:
  • 134. Sisir Kumar Jena Removing Key-Value Pairs • When you no longer need a piece of information that’s stored in a dictionary, you can use the del statement to completely remove a key-value pair. Be aware that the deleted key-value pair is removed permanently. NOTE
  • 135. Sisir Kumar Jena Dictionary Key Vs. List Indices • The syntax may look similar, but you can’t treat a dictionary like a list. Because, in this example 0, 1, 2 … is treated as key; not index.
  • 136. Sisir Kumar Jena Starting with an Empty Dictionary • It’s sometimes convenient, or even necessary, to start with an empty dictionary and then add each new item to it.
  • 137. Sisir Kumar Jena Starting with an Empty Dictionary
  • 138. Sisir Kumar Jena Starting with an Empty Dictionary • This example exhibits another feature of dictionaries: • the values contained in the dictionary don’t need to be the same type. • In student, • some of the values are strings, • one is an integer, • one is a list, • and one is another dictionary.
  • 139. Sisir Kumar Jena Home Task • Based on the previous slide, we know that “the values contained in the dictionary don’t need to be the same type”. It can be strings, integers, list, even dictionaries itself. How can you access the list item, when the entire list is a part of a dictionary. Similarly, how can you access a dictionary’s element when the entire dictionary is an element of another dictionary.
  • 140. Sisir Kumar Jena Starting with an Empty Dictionary • Just as the values in a dictionary don’t need to be of the same type, the keys don’t either:
  • 142. Sisir Kumar Jena What is Tuples? • Sometimes you’ll want to create a list of items that cannot change. Tuples allow you to do just that. • A tuple is a collection which is ordered and unchangeable (immutable). • A tuple looks just like a list except you use parentheses instead of square brackets. • Once you define a tuple, you can access individual elements by using each item’s index, just as you would for a list.
  • 144. Sisir Kumar Jena Creating a Tuple • Tuples are technically defined by the presence of a comma; the parentheses make them look neater and more readable. If you want to define a tuple with one element, you need to include a trailing comma:
  • 145. Sisir Kumar Jena Accessing Tuple elements • Like lists, the elements of a tuple can also be accessed through their index numbers. • Accessing out of index leads to IndexError 34 87 -56 44 -32 0 1 2 3 4 -5 -4 -3 -2 -1 Tuple index index
  • 146. Sisir Kumar Jena Changing a Tuple • Let’s see what happens if we try to change one of the items in the tuple.
  • 147. Sisir Kumar Jena Slicing • Like lists, you can also apply slicing operations on Tuples.
  • 149. Sisir Kumar Jena Repeat elements in a tuple • We can also repeat the elements in a tuple for a given number of times using the * operator.
  • 150. Sisir Kumar Jena Some other operations on Tuples • Deleting a tuple
  • 151. Sisir Kumar Jena Some other operations on Tuples • Methods that add items or remove items are not available with tuple. Only the following two methods are available.
  • 152. Sisir Kumar Jena Some other operations on Tuples • Membership Test
  • 153. Sisir Kumar Jena Home Task • Prepare a brief note on the differences and similarities between Lists, Dictionaries and Tuples.
  • 154. Sisir Kumar Jena References • Book Reference • Matthes, Eric. Python crash course: A hands-on, project-based introduction to programming. no starch press, 2019. • Website • https://realpython.com/python-dicts/ • https://www.w3schools.com/python/python_dictionaries.asp • https://www.programiz.com/python-programming/tuple
  • 156. Sisir Kumar Jena Content • if statement • else statement • elif statement • while loop • break and continue • for loop • range() • pass • Nested loop
  • 157. Sisir Kumar Jena Selection with if statement • An if statement’s clause (that is, the block following the if statement) will execute if the statement’s condition is True. The clause is skipped if the condition is False. • In Python, an if statement consists of the following: • The if keyword • A condition (that is, an expression that evaluates to True or False) • A colon • Starting on the next line, an indented block of code (called the if clause)
  • 158. Sisir Kumar Jena Selection with if statement • Syntax if condition: statement1 statement2 . . . Other statements condition statement1 statement2 . . . Other statements False True
  • 159. Sisir Kumar Jena Selection with if statement • Example: Write a program to read four integers and find the highest number between them. Output Program
  • 160. Sisir Kumar Jena else Statement • An if clause can optionally be followed by an else statement. The else clause is executed only when the if statement’s condition is False. • An else statement doesn’t have a condition, and in code, an else statement always consists of the following: • The else keyword • A colon • Starting on the next line, an indented block of code (called the else clause)
  • 161. Sisir Kumar Jena else Statement • Example: Write a program to read in integer from the user and check whether it is even or odd. Output Program
  • 162. Sisir Kumar Jena elif statement • The elif statement is an “else if” statement that always follows an if or another elif statement. • It provides another condition that is checked only if all of the previous conditions were False. • In code, an elif statement always consists of the following: • The elif keyword • A condition (that is, an expression that evaluates to True or False) • A colon • Starting on the next line, an indented block of code (called the elif clause)
  • 163. Sisir Kumar Jena elif statement Program Output Let’s analyze the program code and predict the output
  • 164. Sisir Kumar Jena elif statement Let’s analyze the previous code by altering sequence and predict the output Program Output
  • 165. Sisir Kumar Jena elif statement • Optionally, you can have an else statement after the last elif statement. • In that case, it is guaranteed that at least one (and only one) of the clauses will be executed. • If the conditions in every if and elif statement are False, then the else clause is executed. Execute the Program and see the output
  • 166. Sisir Kumar Jena while loop statement • You can make a block of code execute over and over again using a while statement. • In code, a while statement always consists of the following: • The while keyword • A condition (that is, an expression that evaluates to True or False) • A colon • Starting on the next line, an indented block of code (called the while clause)
  • 167. Sisir Kumar Jena while loop statement • Syntax initialization while condition: statement1 statement2 . . increment/decrement Other statements Initialization statement1 statement2 . . Increment/Decrement Condition Other Statements True True False
  • 168. Sisir Kumar Jena while loop statement • Example: Write a program to add the digits of a number Program Output
  • 169. Sisir Kumar Jena break statement • There is a shortcut to getting the program execution to break out of a while loop’s clause early. If the execution reaches a break statement, it immediately exits the while loop’s clause. • In code, a break statement simply contains the break keyword.
  • 170. Sisir Kumar Jena break statement Program Output
  • 171. Sisir Kumar Jena continue statement • Like break statements, continue statements are used inside loops. • When the program execution reaches a continue statement, the program execution immediately jumps back to the start of the loop and reevaluates the loop’s condition.
  • 172. Sisir Kumar Jena continue statement Program Output
  • 173. Sisir Kumar Jena for loop • The while loop keeps looping while its condition is True (which is the reason for its name), but what if you want to execute a block of code only a certain number of times? You can do this with a for loop statement. • In code, a for statement looks something like for i in range(5): and includes the following: • The for keyword • A variable name • The in keyword • A call to the range() method with up to three integers passed to it • A colon • Starting on the next line, an indented block of code (called the for clause)
  • 174. Sisir Kumar Jena for loop • Syntax for var_name in range(int, int, int): statement1 statement2 . . . Other statements range can take up to 3 integers
  • 175. Sisir Kumar Jena for loop Program Output
  • 176. Sisir Kumar Jena for loop Program Output
  • 177. Sisir Kumar Jena The Starting, Stopping, and Stepping Arguments to range() for k in range(5) k varies from 0 to 4 for k in range(10, 20) k varies from 10 to 19 for k in range(0, 10, 2) k will have values: 0 2 4 6 8
  • 178. Sisir Kumar Jena The Starting, Stopping, and Stepping Arguments to range()
  • 179. Sisir Kumar Jena The Starting, Stopping, and Stepping Arguments to range() • you can even use a negative number for the step argument to make the for loop count down instead of up.
  • 180. Sisir Kumar Jena pass statement • As its name suggests, pass statement does nothing. • It is used when a statement or a condition is required to be present in the program, but we do not want any command or code to execute. • pass statement is usually used while creating a method, which we do not want to use right now. • The pass statement is used as a placeholder for future code!! • Difference between pass and continue • continue forces the loop to start at the next iteration whereas pass means "there is no code to execute here" and will continue through the remainder of the loop body.
  • 181. Sisir Kumar Jena pass statement Program Output Program Output
  • 182. Sisir Kumar Jena Importing Modules • Python also comes with a set of modules called the standard library. • Each module is a Python program that contains a related group of functions that can be embedded in your programs. • For example, the math module has mathematics related functions, the random module has random number-related functions, and so on. • Before you can use the functions in a module, you must import the module with an import statement. • In code, an import statement consists of the following: • The import keyword • The name of the module • Optionally, more module names, as long as they are separated by commas
  • 183. Sisir Kumar Jena Number Guessing Game Program
  • 184. Sisir Kumar Jena Number Guessing Game Output
  • 185. Sisir Kumar Jena Nested Loops • Placing loop inside another loop is called nested loop. • Loops can be nested to any desired levels. • Proper indentation is necessary to use nested loop. Program Output
  • 186. Sisir Kumar Jena Home Task • Read more about nested loops and try to print the following patterns.
  • 187. Sisir Kumar Jena Home Task 1. While purchasing certain items, a discount of 10% is offered if the quantity purchased is more than 1000. If the quantity and price per item are input through the keyboard, write a program to calculate the total expenses. 2. Write a program that prints a number, its square, and cube repeatedly in the range (1, n). 3. Write a program to print Floyd’s triangle. 4. Write a program to check a year is leap year or not. 5. Write a program to print the digits of a given number. 6. Write a program to find the factorial of a number. 7. Write a program to generate the Fibonacci series. 8. Write a program to reverse a number. 9. Write a program to check whether a number is a palindrome or not. 10. Write a program to generate the multiplication table up to 10 using a for loop.
  • 188. Sisir Kumar Jena References • Book Reference • Sweigart, Al. Automate the boring stuff with Python: practical programming for total beginners. No Starch Press, 2019.
  • 190. Sisir Kumar Jena Contents • Introduction • Types of File • Opening and Closing a file • File Opening Modes • File Object Attributes • Reading from and Writing to file • write() • writeline() • read() • readline() • readlines() • Loop over the content of a file
  • 191. Sisir Kumar Jena Introduction • We write python code to process data coming from different sources. • Until now, we process the data supplied by the user through console. • But, what about processing data that comes from a file? • We need to learn some file processing techniques and this talk is dedicated in that respect.
  • 192. Sisir Kumar Jena Types of File • Text Files • Binary Files
  • 193. Sisir Kumar Jena Opening and Closing a File Opening a file Closing a file Process
  • 194. Sisir Kumar Jena File Opening • Example • Output • This line will open the file in write mode • The default mode is read mode (if don’t specify the mode) I suggest you should print fp
  • 195. Sisir Kumar Jena File Opening Modes r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode. r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file. rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file. Reference https://www.tutorialspoint.com/python/python_files_io.htm
  • 196. Sisir Kumar Jena File Opening Modes Reference https://www.tutorialspoint.com/python/python_files_io.htm w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
  • 197. Sisir Kumar Jena File Opening Modes Reference https://www.tutorialspoint.com/python/python_files_io.htm a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
  • 198. Sisir Kumar Jena File Object Attributes • fileObj.closed • Returns true if file is closed otherwise false • fileObj.mode • Returns the access mode • fileObj.name • Returns the name of the file Output Program
  • 199. Sisir Kumar Jena Reading from and Writing to Files • write() • writelines() • read() • readlines()
  • 200. Sisir Kumar Jena write() method • The write() method is used to write a string to an already opened file. This string may include numbers, special characters, or other symbols. • Write() method does not add a new line character to the end of the string • write() method returns nothing fileObj.write(string) Syntax
  • 201. Sisir Kumar Jena write() method Program
  • 202. Sisir Kumar Jena writeline() method • Used to write list of strings fileObj.writeline(list_name) Syntax
  • 203. Sisir Kumar Jena writeline() method Program
  • 204. Sisir Kumar Jena writeline() method • Home Task • I want the file to look like this after writing. What to do?
  • 205. Sisir Kumar Jena read() method • This method is used to read a string from an already opened file. • Count is an optional parameter • If count is missing or has a negative value, then it reads the entire contents of the file. • read method returns newline as 'n' fileObj.read(10) Syntax
  • 206. Sisir Kumar Jena read() method Program Output
  • 207. Sisir Kumar Jena Home Task • Rewrite the above program and pass the count value as 10 and check the output.
  • 208. Sisir Kumar Jena readline() method • It is used to read a single line from the file. • The method returns an empty strig when the end of file has been reached. • A blank line in a file also has an 'n' character, therefore the readline() method will print a blank line at that place.
  • 209. Sisir Kumar Jena readline() method Program Output
  • 210. Sisir Kumar Jena readlines() method Mark the s here Program Output
  • 211. Sisir Kumar Jena Loop over file content • You can also loop over the file content and display it Program Output
  • 212. Sisir Kumar Jena Home Task • Write a program to copy the content of one file to another file.
  • 213. Sisir Kumar Jena References • Book Reference • Reema, Thareja. "Python Programming: Using Problems Solving Approach." (2020).