Você está na página 1de 94

From Scratch

Mrs. Nimrita Koul


Assistant Professor, School of Computing & IT
Contents

 Python Introduction –Installation, Keywords and Identifiers, Statements and


Comments, Datatypes, Import, Operators
 Python Native Datatypes – Numbers, List, Tuple, String, Set, Dictionary
 Python Flow Control-if-else, for loop, while loop, break and continue
 Python Functions – Arguments, Parameter Passing, Recursion.
 Python Files – File Modes, File operations (reading and writing)
 Python Exception Handling
 Project Modules
Stepwise Install Instructions

 1. Go to www.python.org
 2. Click on Downloads
 3. From the drop down list, click on Windows
 4. Then click on Latest Python 3 Release - Python 3.6.3
 5. In the page that opens i.e.
https://www.python.org/downloads/release/python-363/
 Scroll down to Files Section
 6.For 64 bit Windows click on Windows x86-64 executable installer
 7 For 32 bit windows click on Windows x86 executable installer
Stepwise Install Instructions

 8. python-3.6.3-amd64.exe file will start downloading on your system


 9. After the exe downloads completely, click on it, click on RUN
 10. Check the Radio Button for Add Python to Path
 11. Follow the instructions and Click on Next, Next and then Finish
 12. Done Installation
 13. To Test the installation – open command prompt by clicking on Start, then
command
 14. On command prompt, type Python, you should get the Python Prompt>>>
 15. Congrats!!! You have completed the installation.
Installation Screens
Python – The Snake?
 No – The name “Python” comes from the name of BBC Sketch comedy series
“Monty Python's Flying Circus” from 1970s. The draft of it was being read by
Guido van Rossum, the inventor of Python.

 Monty Python is the name of Comedy Group consisting of Graham


Chapman, John Cleese, Terry Gilliam, Eric Idle, Terry Jones, and Michael
Palin.

 Guido van Rossum needed a name that was short, unique, and slightly
mysterious, so he decided to call the language Python.

 The logo was later matched to the name being synonymous with Snake.
Python Prompt and IDLE
 Python prompt is >>>. It is command line interpreter for Python code,
executes one line of code at a time.
 IDLE: Python’s Integrated Development and Learning Environment.
 Coded in 100% pure python using tkinter GUI toolkit
 Cross platform- works same on Windows, Unix and Mac
 It is python shell window(interactive interpreter)with colorizing of code input,
output and error messages.
 Multi-window text editor with multiple undo, colorizing , smart indent, call
tips, auto completion.
 Search and replace, debugger, configuration, browsers and other dialogs
Comments

 A Comments starts with a # character and ends at physical line on screen.


 It is ignored by syntax checker
 #This is hello world program
 >>>print(“hello world”)
Explicit and Implicit Line Joining

 Explicit - Using \ character we can join two or more physical lines into one
logical line
 If 1900 < year < 2100 and 1<=month <=12 \
 and 1<= day<= 31 and 0<= hour<24\
 and 0<=minute<60 and 0<=second < 60:
 return 1
 Implicit – Expressions in parentheses, square brackets or curly braces can be
split over more than one physical line without using backslashes.
 Month_names=[‘Jan’,’feb’,’mar’,’apr’,
 ‘may’,’jun’,’jul’,’aug’,
 ‘sep’,’oct’,’nov’,’dec’]
Indentation

 Leading whitespaces(spaces and tabs) at beginning of a logical line is used to


compute the indentation level of the line, which is used to determine the
grouping of statements.

 Correct indentation is essential for correctness of the program.


Identifiers

 Names of variables, functions, constants , literals


 They should not start with a number, should not contain a space.
 Avoid using _ at beginning of variable name as this is used in case of
internationalization.
 Literals are notations for constant values of some built-in types.
Escape Sequence
 \newline- Backslash and newline ignored
 \\ : Backslash \
 \’: Single Quote
 \”: Double Quote
 \a: ASCII BEL(System Beep)
 \b: Ascii Backspace
 \f: Ascii formfeed
 \n: Ascii Linefeed
 \r: Ascii Carriage Return
 \t: Acsii Horiontal Tab
 \v: Ascii Vertical Tab etc
Operators

 +, -, *, **, /, //, %,<<,>>,&,|,^,~,<,>,>=,<=,==,!=


 Delimiters
 (,),[,],{,},,,;,:,.,@ etc
Keywords

 Keywords- Keywords are the reserved words in Python. We cannot use a


keyword as variable name, function name or any other identifier.
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
 >>>import keyword
 >>>print(keyword.kwlist)
None- Returned by void Functions
 None is a special constant that represents absence of a value or a null value.
 It is object of NoneType
 >>>None == 0
 False
 >>>None==“ “
 False
 >>> None==[]
 False
 >>> x=None
 >>>y=None
 >>>x==y
 True
As- for creating an alias

 >>>import math as mymath


 >>>mymath.cos(mymath.pi)
 -1
Datatypes

 In Python, every value has a datatype,


 but you don’t need to declare the datatype of variables.
 How does that work?
 Based on each variable’s original assignment, Python figures out what type it
is and keeps tracks of that internally.
Python has many native datatypes. Here are the important ones:

1.Booleans are either True or False.


2.Numbers can be integers (1 and 2), floats (1.1 and 1.2),
fractions (1/2 and 2/3), or even complex numbers.
3.Strings are sequences of Unicode characters, e.g. an html document.
4.Bytes and byte arrays, e.g. a jpeg image file.
5.Lists are ordered sequences of values.
6.Tuples are ordered, immutable sequences of values.
7.Sets are unordered bags of values.
8.Dictionaries are unordered bags of key-value pairs

Everything is an object in Python, so there are types like module, function, class,
method, file, and even compiled code
Try Boolean

>>> size = 1
>>> size < 0
False
>>> size = 0
>>> size < 0
False
>>> size = -1
>>> size < 0
True
Numbers
 Python supports both integers and floating point numbers. There’s no type
declaration to distinguish them;
 Python tells them apart by the presence or absence of a decimal point.
 >>> type(1)
 <class 'int'>
 >>> isinstance(1, int)
 True
 >>> 1 + 1
 2.0
 >>> type(2.0)
 <class 'float'>
Type Casting

>>> float(2)
2.0
>>> int(2.0)
2
>>> int(2.5)
2
>>> int(-2.5)
-2
>>> type(1000000000000000)
<class 'int'>
FRACTIONS

>>> import fractions


>>> x = fractions.Fraction(1, 3)
>>> x
Fraction(1, 3)
>>> x * 2
Fraction(2, 3)
>>> fractions.Fraction(6, 4)
Fraction(3, 2)
>>> fractions.Fraction(0, 0)
Traceback (most recent call last): File "<stdin>", line 1, in <module> File
"fractions.py", line 96, in __new__ raise ZeroDivisionError('Fraction(%s, 0)' %
numerator) ZeroDivisionError: Fraction(0, 0)
TRIGONOMETRY
>>> import math
>>> math.pi
3.1415926535897931
>>> math.sin(math.pi / 2)
1.0
>>> math.tan(math.pi / 4)
0.99999999999999989
Lists

 A list in python can store elements of different datatypes and its size can
grow arbitrarily.
 It is mutable
 Creating a list is easy: use square brackets to wrap a comma-separated list of
values.
 >>> a_list = ['a', 'b', 'mpilgrim', 'z', 'example']
 >>> a_list
 ['a', 'b', 'mpilgrim', 'z', 'example']
 >>> a_list[0]
 'a'
 >>> a_list[4]
 'example‘
 >>> a_list[-1]
 'example‘
 >>> a_list[-3]
 'mpilgrim'
Slicing a List
 Once you’ve defined a list, you can get any part of it as a new list. This is
called slicing the list.
 >>> a_list
 ['a', 'b', 'mpilgrim', 'z', 'example']
 >>> a_list[1:3]
 ['b', 'mpilgrim']
 >>> a_list[1:-1]
 ['b', 'mpilgrim', 'z']
 >>> a_list[0:3]
 ['a', 'b', 'mpilgrim']
 >>> a_list[3:]
 ['z', 'example']
 >>> a_list[:]
 ['a', 'b', 'mpilgrim', 'z', 'example']
 >>> a_list[:3]
 ['a', 'b', 'mpilgrim']
Adding items to list
>>> a_list = ['a']
>>> a_list = a_list + [2.0, 3]
>>> a_list
['a', 2.0, 3]
>>> a_list.append(True)
>>> a_list ['a', 2.0, 3, True]
>>> a_list.extend(['four', 'Ω'])
>>> a_list ['a', 2.0, 3, True, 'four', 'Ω']
>>> a_list.insert(0, 'Ω')
>>> a_list
['Ω', 'a', 2.0, 3, True, 'four', 'Ω']
SEARCHING FOR VALUES IN A LIST

>>> a_list = ['a', 'b', 'new', 'mpilgrim', 'new']

>>> a_list.count('new')
2
>>> 'new' in a_list
True
>>> 'c' in a_list
False
>>> a_list.index('mpilgrim')
3
>>> a_list.index('new')
2
>>> a_list.index('c') #see output
REMOVING ITEMS FROM A LIST

>>> a_list = ['a', 'b', 'new', 'mpilgrim', 'new']


>>> a_list[1]
'b'
>>> del a_list[1]
>>> a_list ['a', 'new', 'mpilgrim', 'new']
>>> a_list[1]
'new'
>>> a_list.remove('new')
>>> a_list
['a', 'mpilgrim', 'new']
>>> a_list = ['a', 'b', 'new', 'mpilgrim']
>>> a_list.pop()
'mpilgrim'
>>> a_list.pop(1)
'b‘
>>> a_list
['a', 'new']
Tuples - A tuple is an immutable list. It can’t
be changed in any way once it is created.
>>> a_tuple = ("a", "b", "mpilgrim", "z", "example")
>>> a_tuple ('a', 'b', 'mpilgrim', 'z', 'example')
>>> a_tuple[0]
'a'
>>> a_tuple[-1]
'example'
>>> a_tuple[1:3]
('b', 'mpilgrim')

List methods append(), extend(), insert(), remove(), pop() don’t work fro Tuples.
We can slice a tuple, it creates new tuples, we can check if tuple contains a
particular value.
Tuple Vs List

•Tuples are faster than lists.

•If you’re defining a constant set of values , use a tuple instead of a list.

•It makes your code safer if you “write-protect” data that doesn’t need to be changed.

•Using a tuple instead of a list is like having an implied assert statement that shows this data is constant
• Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values
like strings, numbers, and other tuples).
• Lists can never be used as dictionary keys, because lists are mutable.

Tuples can be converted into lists, and vice-versa.


The built-in tuple() function takes a list and returns a tuple with the same elements,
and the list() function takes a tuple and returns a list.
SETS
 A set is an unordered “bag” of unique values.
 A single set can contain values of any immutable datatype.
 Once you have two sets, you can do standard set operations like union,
intersection, and set difference.
 >>> a_set = {1}
 >>> a_set
 {1}
 >>> type(a_set)
 <class 'set'>
 >>> a_set = {1, 2}
 >>> a_set
 {1, 2}
Converting List to Set

>>> a_list = ['a', 'b', 'mpilgrim', True, False, 42]


>>> a_set = set(a_list)
>>> a_set
{'a', False, 'b', True, 'mpilgrim', 42}
>>> a_list
['a', 'b', 'mpilgrim', True, False, 42]
>>> a_set = {1, 2}
>>> a_set.add(4)
>>> a_set {1, 2, 4}
>>> len(a_set)
>>> 3
>>> a_set.update({2, 4, 6})
>>> a_set
{1, 2, 3, 4, 6}
>>> a_set.update({3, 6, 9}, {1, 2, 3, 5, 8, 13})
>>> a_set
{1, 2, 3, 4, 5, 6, 8, 9, 13}
>>> a_set.update([10, 20, 30])
>>> a_set
{1, 2, 3, 4, 5, 6, 8, 9, 10, 13, 20, 30}
Set Operations

>>> a_set = {2, 4, 5, 9, 12, 21, 30, 51, 76, 127, 195}
>>> 30 in a_set
True
>>> 31 in a_set
False
>>> b_set = {1, 2, 3, 5, 6, 8, 9, 12, 15, 17, 18, 21}
>>> a_set.union(b_set)
{1, 2, 195, 4, 5, 6, 8, 12, 76, 15, 17, 18, 3, 21, 30, 51, 9, 127}
>>> a_set.intersection(b_set)
{9, 2, 12, 5, 21}
>>> a_set.difference(b_set)
{195, 4, 76, 51, 30, 127}
>>> a_set.symmetric_difference(b_set)
{1, 3, 4, 6, 8, 76, 15, 17, 18, 195, 127, 30, 51}
DICTIONARIES
A dictionary is an unordered set of key-value pairs. When you add a key
to a dictionary, you must also add a value for that key

>>> a_dict = {'server': 'db.diveintopython3.org', 'database': 'mysql'}


>>> a_dict
{'server': 'db.diveintopython3.org', 'database': 'mysql'}
>>> a_dict['server']
'db.diveintopython3.org'
>>> a_dict['database']
'mysql'
>>> a_dict['database'] = 'blog‘
>>> a_dict
{'server': 'db.diveintopython3.org', 'database': 'blog'}
None

 None is a special constant in Python.


 It is a null value.
 None is not the same as False. None is not 0. None is not an empty string.
 Comparing None to anything other than None will always return False.
 None is the only null value. It has its own datatype (NoneType).
 You can assign None to any variable, but you can not create other NoneType
objects.
 All variables whose value is None are equal to each other
>> type(None)
<class 'NoneType'>
>>> None == False
False
>>> None == 0
False
>>> None == '' False
>>> None == None
True
>>> x = None
>>> x == None
True
>>> y = None
>>> x == y
True
Strings

 Built in class str.


 String literals can be enclosed by either double or single quotes.
 A double quoted string literal can contain single quotes.
 String literals inside triple quotes, """" or ''', can span multiple lines of text.
 Python strings are "immutable" which means they cannot be changed after
they are created.
 Since strings can't be changed, we construct *new* strings as we go to
represent computed values.
 So for example the expression ('hello' + 'there') takes in the 2 strings 'hello'
and 'there' and builds a new string 'hellothere'.
 >>>S=“hi”
 >>> print(s[1])
 >>> print(len(s))
 >>> print(s + “there”)
String Methods
 s.lower(), s.upper() -- returns the lowercase or uppercase version of the string
 s.strip() -- returns a string with whitespace removed from the start and end
 s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string chars are in the various
character classes
 s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the
given other string
 s.find('other') -- searches for the given other string (not a regular expression)
within s, and returns the first index where it begins or -1 if not found
 s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been
replaced by 'new'
 s.split('delim') -- returns a list of substrings separated by the given delimiter. The
delimiter is not a regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa',
'bbb', 'ccc']. As a convenient special case s.split() (with no arguments) splits on all
whitespace chars.
 s.join(list) -- opposite of split(), joins the elements in the given list together using
the string as the delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc
String Slicing

•s[1:4] is 'ell' -- chars starting at index 1 and extending up to but not including index 4
•s[1:] is 'ello' -- omitting either index defaults to the start or end of the string
•s[:] is 'Hello' -- omitting both always gives us a copy of the whole thing (this is the pythonic way
to copy a sequence like a string or list)
•s[1:100] is 'ello' -- an index that is too big is truncated down to the string length
s[-1] is 'o' -- last char (1st from the end)
s[-4] is 'e' -- 4th from the end
s[:-3] is 'He' -- going up to but not including the last 3 chars.
s[-3:] is 'llo' -- starting with the 3rd char from the end and extending to the end of the string
String %
Python has a printf()-like facility to put together a string.

The % operator takes a printf-type format string on the left (%d int, %s string,
%f/%g floating point), and the matching values in a tuple on the right (a tuple is
made of values separated by commas, typically grouped inside parentheses):

text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow
down')
Input / Output

 Print() for output to screen


 Input() for input from keyboard
 >>>print('This sentence is output to the screen')
 This sentence is output to the screen
 >>>a = 5
 >>>print('The value of a is', a)
 The value of a is 5
 Syntax of print()
 print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Output Formatting

>>> x = 5; y = 10

>>> print('The value of x is {} and y is {}'.format(x,y))


The value of x is 5 and y is 10
>>> print('I love {0} and {1}'.format('bread','butter'))
I love bread and butter
>>> print('I love {1} and {0}'.format('bread','butter'))
I love butter and bread
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
Input- input([prompt])

>>> num =input(“Enter a Number”)


Enter a number:
10
>>> num
'10'
>>> int('10')
10
>>> float('10')
10.0
import
 When our program grows bigger, it is a good idea to break it into different
modules.
 A module is a file containing Python definitions and statements.
 Python modules have a filename and end with the extension .py.
 Definitions inside a module can be imported to another module or the interactive
interpreter in Python. We use the import keyword to do this.
 For example, we can import the math module by typing in
 >>> import math
 Now all the definitions inside math module are available in our scope. We can also
import some specific attributes and functions only, using the from keyword.
 For example:
 >>> from math import pi
 >>> pi
 3.141592653589793
Sys.path

 While importing a module, Python looks at several places defined in sys.path.


 It is a list of directory locations
 >>> import sys
 >>> sys.path
 ['',
 'C:\\Python33\\Lib\\idlelib',
 'C:\\Windows\\system32\\python33.zip',
 'C:\\Python33\\DLLs',
 'C:\\Python33\\lib',
 'C:\\Python33',
 'C:\\Python33\\lib\\site-packages']
Flow Control – if-else

 >>> num = 3
 if num > 0:
 print(num, "is a positive number.")
 print("This is always printed.")
 num = -1
 if num > 0:
 print(num, "is a positive number.")
 print("This is also always printed.")
If - else

 num = -5
 if num >= 0:
 print("Positive or Zero")
 else:
 print("Negative number")
If-elif-else

 num = 3.4
 if num > 0:
 print("Positive number")
 elif num == 0:
 print("Zero")
 else:
 print("Negative number")
Nested if

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


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Leap Year Program

 # Python program to check if the input year is a leap year or notyear = 2000# To get year
(integer input) from the user#
 year = int(input("Enter a year: "))
 if (year % 4) == 0:
 if (year % 100) == 0:
 if (year % 400) == 0:
 print("{0} is a leap year".format(year))
 else:
 print("{0} is not a leap year".format(year))
 else:
 print("{0} is a leap year".format(year))
 else:
 print("{0} is not a leap year".format(year))
To Display Calendar

 import calendar
 yy = 2014
 mm = 11
 # To ask month and year from the user#
 yy = int(input("Enter year: "))
 mm = int(input("Enter month: "))
 # display the calendar
 print(calendar.month(yy, mm))
Looping
 a=0
 While a<5 :
 print(a)
 a=a+1

 What does above code mean -


 'a' now equals 0
 As long as 'a' is less than 5, do the following:
 print on-screen what 'a' is now worth
 Make 'a' one larger than what it already is.
What does it mean
 Is 'a' less than 5? YES (its 0)
 print on-screen what 'a' is (0)
 Make 'a' one larger (now 1)

 Is 'a' less than 5? YES (its 1)


 print on-screen what 'a' is (1)
 Make 'a' one larger (now 2)

 Is 'a' less than 5? YES (its 2)


 print on-screen what 'a' is (2)
 Make 'a' one larger (now 3)
 Is 'a' less than 5? YES (its 3)
 print on-screen what 'a' is (3)
 Make 'a' one larger (now 4)

 Is 'a' less than 5? Yes (its 4)


 print on-screen what 'a' is (4)
 Make 'a' one larger (now 5)
 Is 'a' less than 5? No (its 5 , not less than 5)
 Don't do the loop
 There's no code left to do, so the program ends
for loop – to find sum of list of numbers

 for val in sequence:


 Body of for

 # List of numbers
 numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
 # variable to store the sum
 sum = 0
 for val in numbers:
 sum = sum+val
 print("The sum is", sum)
For with else

 A for loop can have an optional else block as well. The else part is executed if
the items in the sequence used in for loop exhausts
 digits = [0, 1, 5]
 for i in digits:
 print(i)
 else:
 print("No items left.").
Range()

 >>> print(range(10))
 print(list(range(2, 8)))
 print(list(range(2, 20, 3)))
 genre = ['pop', 'rock', 'jazz']
 # iterate over the list using index
 for i in range(len(genre)):
 print("I like", genre[i])
While – Program to print sum of n
natural numbers
 # Program to add natural numbers upto n, sum = 1+2+3+...+n
 n = int(input("Enter n: "))
 10
 sum = 0
 i=1
 while i <= n:
 sum = sum + i
 i = i+1
 print("The sum is", sum)
While with else

 counter = 0
 while counter < 3:
 print("Inside loop")
 counter = counter + 1
 else:
 print("Inside else")
Break and continue statement
Break

 for val in "string":


 if val == "i":
 break
 print(val)
 print("The end")
continue
continue

 for val in "string":


 if val == "i":
 continue
 print(val)
 print("The end")
Pass statement

 To indicate no operation.

 sequence = {'p', 'a', 's', 's'}


 for val in sequence:
 pass
Python Functions – Arguments,
Parameter Passing, Recursion
 In Python, function is a group of related statements that perform a specific
task.

 Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.

 Furthermore, it avoids repetition and makes code reusable.


Syntax of Function
 def function_name(parameters):
 """docstring"""
 statement(s)

 Keyword def marks the start of function header.


 A function name to uniquely identify it
 Parameters (arguments) through which we pass values to a function.
 A colon (:) to mark the end of function header.
 Optional documentation string (docstring) to describe what the function does.
 One or more valid python statements that make up the function body.
 Statements must have same indentation level (usually 4 spaces).
 An optional return statement to return a value from the function.
example

 def greet(name):
 """This function greets to the person passed in as parameter"""
 print("Hello, " + name + ". Good morning!")

 >>> greet('Paul')
 Hello, Paul. Good morning!
 >>> print(greet("May"))
 Hello, May. Good morning!
 None
Example to print absolute value

 def absolute_value(num):
 """This function returns the absolute value of the entered number"""
 if num >= 0:
 return num
 else:
 return -num
 # Output: 2
 print(absolute_value(2))
 # Output: 4
 print(absolute_value(-4))
How functions work
HCF of two numbers
def computeHCF(x, y):
# choose the smaller number
 if x > y:
 smaller = y
 else:
 smaller = x
 for i in range(1, smaller+1):
 if((x % i == 0) and (y % i == 0)):
 hcf = i
 return hcf
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))
Python Package
 Just as Similar files are kept in the same directory, analogous to this, Python
has packages for directories and modules for files.
 Module=collection of similar files
 Package=collection of similar directories
 A directory must contain a file named __init__.py in order for Python to
consider it as a package. This file can be left empty but we generally place
the initialization code for that package in this file.
 Similar, as a directory can contain sub-directories and files, a Python package
can have sub-packages and modules.
Import module from package

 Import Game.Level.start
 Now if this module contains a function named select_difficulty(), we must use the full name
to reference it.
 Game.Level.start.select_difficulty(2)
 Or, we can import the module without the package prefix as follows.
 from Game.Level import start
 We can now call the function simply as follows.
 start.select_difficulty(2)
 Yet another way of importing just the required function (or class or variable) form a module
within a package would be as follows.
 from Game.Level.start import select_difficulty
 Now we can directly call this function.
 select_difficulty(2)
Files

 File is a named location on disk to store related information. It is used to


permanently store data in a non-volatile memory (e.g. hard disk).

 When we want to read from or write to a file we need to open it first. When
we are done, it needs to be closed, so that resources that are tied with the
file are freed.

 Hence, in Python, a file operation takes place in the following order.


 Open a file
 Read or write (perform operation)
 Close the file
How to open a file?
 Python has a built-in function open() to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
 >>> f = open("test.txt") # open file in current directory
 >>> f = open("C:/Python33/README.txt") # specifying full path
 We can specify the mode while opening a file. In mode, we specify whether we
want to read 'r', write 'w' or append 'a' to the file. We also specify if we want to
open the file in text mode or binary mode.

 The default is reading in text mode. In this mode, we get strings when reading
from the file.

 On the other hand, binary mode returns bytes and this is the mode to be used
when dealing with non-text files like image or exe files.
Modes

Mode Description

'r' Open a file for reading. (default)

Open a file for writing. Creates a new


'w' file if it does not exist or truncates the
file if it exists.

Open a file for exclusive creation. If the


'x'
file already exists, the operation fails.

Open for appending at the end of the file


'a' without truncating it. Creates a new file
if it does not exist.

't' Open in text mode. (default)

'b' Open in binary mode.

Open a file for updating (reading and


'+'
writing)
How to close a file Using Python?
 When we are done with operations to the file, we need to properly close the file.
 Closing a file will free up the resources that were tied with the file and is done using Python
close() method.
 Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to
close the file.
 f = open("test.txt", encoding = 'utf-8')
 # perform file operations
 f.close()
 try:
 f = open("test.txt",encoding = 'utf-8')
 # perform file operations
 finally:
 f.close()
How to write to File Using Python?
 In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive
creation 'x' mode.

 We need to be careful with the 'w' mode as it will overwrite into the file if it already exists.
All previous data are erased.

 Writing a string or sequence of bytes (for binary files) is done using write() method. This
method returns the number of characters written to the file.

 with open("test.txt",'w',encoding = 'utf-8') as f:


 f.write("my first file\n")
 f.write("This file\n\n")
 f.write("contains three lines\n")
How to read files in Python?
 To read a file in Python, we must open the file in reading mode.
 There are various methods available for this purpose. We can use the read(size)
method to read in size number of data. If size parameter is not specified, it reads
and returns up to the end of the file.

 >>> f = open("test.txt",'r',encoding = 'utf-8')


 >>> f.read(4) # read the first 4 data
 'This'
 >>> f.read(4) # read the next 4 data
 ' is '
 >>> f.read() # read in the rest till end of file
 'my first file\nThis file\ncontains three lines\n'
 >>> f.read() # further reading returns empty sting
We can read a file line-by-line using a for
loop. This is both efficient and fast.

 >>> for line in f:


 ... print(line, end = '')
 ...
 This is my first file
 This file
 contains three lines
readline() and readlines()

 Alternately, we can use readline() method to read individual lines of a file.


This method reads a file till the newline, including the newline character.
 >>> f.readline()
 'This is my first file\n'
 >>> f.readline()
 'This file\n‘
 The readlines() method returns a list of remaining lines of the entire file.
 All these reading methods return empty values when end of file (EOF) is
reached.
 >>> f.readlines()
 ['This is my first file\n', 'This file\n', 'contains three lines\n']
Exception Handling

 An exception is an error that happens during execution of a program. When


that error occurs, Python generate an exception that can be handled, which
avoids your program to crash.
 Why use Exceptions? - When you think that you have a code which can
produce an error then you can use exception handling.
 Raising an Exception - You can raise an exception in your own program by
using the raise exception statement.
 Raising an exception breaks current code execution and returns the exception
back until it is handled.
Some common types of Exceptions

 IOError - If the file cannot be opened.


 ImportError - If python cannot find the module
 ValueError - Raised when a built-in operation or function receives an
argument that has the right type but an inappropriate value
 KeyboardInterrupt - Raised when the user hits the interrupt key (normally
Control-C or Delete)
 EOFError - Raised when one of the built-in functions (input() or raw_input())
hits an end-of-file condition (EOF) without reading any data
Examples

 try:
 print(1/0)
 except ZeroDivisionError:
 print("You can't divide by zero”)
Example

 import sys
 try:
 number = int(input("Enter a number between 1 - 10 "))

 except ValueError:
 print("Err.. numbers only")
 sys.exit()

 print("you entered number", number)


Try ... except ... else clause

 The else clause in a try , except statement must follow all except clauses,
and is useful for code that must be executed if the try clause does not raise
an exception.
 try:
 data = something_that_can_go_wrong
 except IOError:
 handle_the_exception_error
 else:
 doing_different_exception_handling
Try ... finally clause

 The finally clause is optional. It is intended to define clean-up actions that must
be executed under all circumstances
 try:
 raise KeyboardInterrupt
 finally:
 print 'Goodbye, world!'
 ...
 Goodbye, world!
 KeyboardInterrupt
 A finally clause is always executed before leaving the try statement, whether an
 exception has occurred or not.
Example

 try:
 handler=open("trees.txt")
 tree_numbers=0
 for line in handler:
 split_line=line.split(",")
 tree_numbers=tree_numbers+split_line[2]
 except:
 print "An error has been caught!"
Anaconda

 Anaconda is a free open source distribution of the Python and R programming


languages. It has all python packages required for :
1. large-scale data processing
2. predictive analytics
3. scientific computing.

 It simplifies package management and deployment.


 Package versions are managed by the package management system conda.
Thank You.

Você também pode gostar