Python
Index
1. Python Installation
2. Variables and Data types
3. Working with strings
4. String Methods
5. String Concatenation
6. Formatting Strings
7. Indexing
8. Working with numbers
9. Boolean
10. Operators
11. Getting input from users
12. Lists
13. List Functions
14. Slices
15. Sorting
16. Tuples
17. Functions
18. Print Delimiter
19. Return statement
20. If statement (Conditional statements)
21. If statements and comparisons
22. Dictionaries
23. While loop
24. For loop
25. Exponent Function
26. 2D lists and nested loop
27. Comments
28. Exception Handing – Try/Except
29. Reading and Writing a file
30. Modules and pip
31. Classes and Objects
32. Object Function
33. Inheritance
34. Python interpreter
1. Python Installation
https://www.python.org/ > Downloads > Download the latest available version.
IDE — Integrated Development Environment
Python’s default IDE is IDLE — Integrated DeveLopment Environment
We can verify version in command prompt (cmd) by executing ‘python –version’.
The execution of python script from cmd is ‘python give_path\file_name.py’
2. Variables and Data types
Variables are names that store values. Variable names are case sensitive and should start with letter but not with number. They can contain numbers and underscore. In Python no need to define data type for variables as it analyses internally due to type casting.
Valid variable names:
i. variable_name = ‘value’
ii. variableName = ‘value’
iii. variablename = ‘value’
iv. variablename1 = ‘value’
Here value could be any string or number.
3. Working with strings
String represents text and can be enclosed in single or double quotes.
i. variable = ‘string’
ii. variable = “string”
iii. variable = ‘String having “double quotes” can be represented in this manner’
iv. variable = “String having ‘single quotes’ can be represented in this manner”
v. variable = ‘String having both \’Single quotes\’ and \”double quotes\”‘
vi. variable = “String having both \’Single quotes\’ and \”double quotes\””
vii. sentence_in_double = “She said, \”That’s a great tasting apple!\””
viii. sentence_in_single = ‘She said, “That\’s a great tasting apple!”‘
4. String Methods
• Everything is an object in Python.
• Every object has a type. Objects can have methods. Methods are functions that operate on an object
• variable = ‘python’
• ‘python’ is an object of ‘str’ type. Here variable and python, both are string objects.
• Methods are functions run against an object like object.method ()
• String Methods:
i. upper() – Returns the entire string in upper case
ii. lower() – Returns the entire string in lower case
iii. format() – Returns the formatted version of the string
• Ex: lower() string method.
• variable = ‘Python’
• print(variable.lower()) — python
• print(variable.uper()) — PYTHON
5. String Concatenation
>>> print('Python '+'is '+'a'+' programming'+' language') Python is a programming language >>> print('Python'+'is'+'a'+'programming'+'language') Pythonisaprogramminglanguage
Spaces have to be defined explicitly.
>>> print('*'*10) ********** >>> print('-'*10) ---------- >>> var = 'Python '*3 >>> print(var) Python Python Python >>> version = 3 >>> print('Python '+version) TypeError: can only concatenate str (not "int") to str >>> print('Python '+str(version)) Python 3
6. Formatting Strings
print(‘{0:10} | {1:10}’.format(‘EMPID’, ‘ENAME’))
print(‘{0:10} | {1:10}’.format(1234, ‘ABC’))
print(‘{0:10} | {1:10}’.format(5678, ‘DEF’))
Alignments:
< is for left
^ is for center
> is for right
print(‘{0:10} | {1:<10}’.format(‘EMPID’, ‘ENAME’))
print(‘{0:10} | {1:<10}’.format(1234, ‘ABC’))
print(‘{0:10} | {1:<10}’.format(5678, ‘DEF’))
Float – f
.nf where n = number of decimal places
print(‘{0:10} | {1:<10.2f}’.format(‘Apple’, 1234.56789))
age = 30 name = "Srikanth" print(f"Hello. I am {name} and I am {age} years old.") print("Hello. I am {} and I am {} years old.".format(name, age))
7. Indexing
Each character in a string is assigned an index.
string | P | y | t | h | o | n |
indexing | 0 | 1 | 2 | 3 | 4 | 5 |
string = ‘Python’
print(variable[0]) — P
print(variable[3]) — h
print(variable[5]) — n
print(variable[-1]) — n
8. Working with numbers
We can use numbers directly in source code with quotations.
We have two datatypes – int for integer and float for float.
To convert string to an integer use int() function.
To convert string to a float use float() function.
+ Addition
– Subtraction
* Multiplication
/ Division
** Exponential (Power of)
% Modulus (Returns remainder)
# The cost of one server per hour. cost_per_hour = 0.51 # Compute the costs for one server. cost_per_day = 24 * cost_per_hour cost_per_month = 30 * cost_per_day # Compute the costs for twenty servers cost_per_day_twenty = 20 * cost_per_day cost_per_month_twenty = 20 * cost_per_month # Budgeting budget = 918 operational_days = budget / cost_per_day # Display the results. print('Cost to operate one server per day is ${:.2f}.'.format(cost_per_day)) print('Cost to operate one server per month is ${:.2f}.'.format(cost_per_month)) print('Cost to operate twenty servers per day is ${:.2f}.'.format(cost_per_day_twenty)) print('Cost to operate twenty servers per month is ${:.2f}.'.format(cost_per_month_twenty)) print('A server can operate on a ${0:.2f} budget for {1:.0f} days.'.format(budget, operational_days)) ====================================== Cost to operate one server per day is $12.24. Cost to operate one server per month is $367.20. Cost to operate twenty servers per day is $244.80. Cost to operate twenty servers per month is $7344.00. A server can operate on a $918.00 budget for 75 days.
9. Boolean
Can only be True or False
is_valid = True is_not_valid = False print(is_valid) print(is_not_valid) ====================================== True False
10. Operators
Relational or Conditional: ==, >, >=, <, <=, !=
Boolean or Logical operators: and, or, not
and — Evaluates to True if both the statements are True else False
or — Evaluates to True if either of the statements is True else False
not — Negates the statement
**The order boolean operators is not, and, or and in real time environments its ideal to control the order of operators using parenthesis().
11. Getting input from users
input(‘Enter some input value’)
12. Lists
A list is a datatype that holds an ordered collection of items. These items can be of various datatypes. We can even have lists of lists. They are created using comma separated values between square brackets. Lists are mutable.
list_name = [item_1, item_2,…item_n]
list_name = [] #Empty list
list_name[index]
#different datatypes list_name = ['Apple', 'Orange', 'Mango', 12345, True, False, 1.23] print(list_name) ###################################### ['Apple', 'Orange', 'Mango', 12345, True, False, 1.23]
list_name = ['Apple', 'Orange', 'Mango'] print(list_name[0]) print(list_name[1]) print(list_name[2]) ###################################### Apple Orange Mango
list_name = ['Apple', 'Orange', 'Mango'] print(list_name[0]) list_name[0] = 'Apricot' print(list_name[0]) ###################################### Apple Apricot
list_name = ['Apple', 'Orange', 'Mango'] print(list_name[-1]) print(list_name[-2]) print(list_name[-3]) ###################################### Mango Orange Apple
#Add new item to list list_name = ['Apple', 'Orange', 'Mango'] print(len(list_name)) list_name.append('Apricot') print(list_name[-1]) print(list_name) print(len(list_name)) ###################################### 3 Apricot ['Apple', 'Orange', 'Mango', 'Apricot'] 4
#Add multiple items to list list_name_1 = ['Apple', 'Orange', 'Mango'] list_name_1.extend(['Apricot', 'Plum']) print(list_name_1) list_name_2 = ['Guava', 'Banana'] list_name_1.extend(list_name_2) print(list_name_1) print(list_name_2) ###################################### ['Apple', 'Orange', 'Mango', 'Apricot', 'Plum'] ['Apple', 'Orange', 'Mango', 'Apricot', 'Plum', 'Guava', 'Banana'] ['Guava', 'Banana']
#Add items to list in required order list_name = ['Apple', 'Orange', 'Mango'] list_name.insert(0, 'Apricot') print(list_name) list_name.insert(2, 'Plum') print(list_name) ###################################### ['Apricot', 'Apple', 'Orange', 'Mango'] ['Apricot', 'Apple', 'Plum', 'Orange', 'Mango']
list_name_1 = ['Apple', 'Orange', 'Mango'] list_name_2 = ['Apricot', 'Plum'] list_name_3 = list_name_1 + list_name_2 print(list_name_3) ###################################### ['Apple', 'Orange', 'Mango', 'Apricot', 'Plum']
#delete items list_name = ['Apple', 'Orange', 'Mango'] del(list_name[1]) print(list_name) ###################################### ['Apple', 'Mango']
13. List Functions
14. Slices
list[index1:index2] list[:index2] list[index1:]
list_name = ['Apple', 'Orange', 'Mango', 'Apricot', 'Plum'] list_name_slice = list_name[1:4] print(list_name_slice) list_name_slice = list_name[0:3] print(list_name_slice) list_name_slice = list_name[:3] print(list_name_slice) list_name_slice = list_name[1:] print(list_name_slice) list_name_slice = list_name[2:] print(list_name_slice) list_name_slice = list_name[-2:] print(list_name_slice) ====================================== ['Orange', 'Mango', 'Apricot'] ['Apple', 'Orange', 'Mango'] ['Apple', 'Orange', 'Mango'] ['Orange', 'Mango', 'Apricot', 'Plum'] ['Mango', 'Apricot', 'Plum'] ['Apricot', 'Plum']
part_of_string = 'Orange'[1:3] print(part_of_string) ====================================== ra
15. Sorting
list_name = ['Apple', 'Orange', 'Mango'] sorted_list_name = sorted(list_name) print(list_name) print(sorted_list_name) list_name.sort() print(list_name) ====================================== ['Apple', 'Orange', 'Mango'] ['Apple', 'Mango', 'Orange'] ['Apple', 'Mango', 'Orange']
16. Tuples
A tuple is an immutable list and they are ordered. Values accessed by index and use Tuple when data should not change. We cannot modify values in Tuple but we can delete entire tuple.
tuple_name = (item_1, item_2,…item_n)
days_of_the_week = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursdady', 'Friday', 'Saturday') monday = days_of_the_week[0] print(monday) print() for day in days_of_the_week: print(day) ====================================== Sunday Sunday Monday Tuesday Wednesday Thursdady Friday Saturday
days_of_the_week = ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursdady', 'Friday', 'Saturday') print(days_of_the_week) del days_of_the_week #The below will raise exception since the tuple was deleted. print(days_of_the_week) ====================================== ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursdady', 'Friday', 'Saturday') Traceback (most recent call last): File "C:\Users\gdsri\Desktop\Float.py", line 5, in <module> print(days_of_the_week) NameError: name 'days_of_the_week' is not defined
weekday_tuple = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday') weekday_list = list(weekday_tuple) print(type(weekday_tuple)) print(type(weekday_list)) print(weekday_tuple) print(weekday_list) ====================================== <class 'tuple'> <class 'list'> ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday') ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
weekday_list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] weekday_tuple = tuple(weekday_list) print(type(weekday_tuple)) print(type(weekday_list)) print(weekday_tuple) print(weekday_list) ====================================== <class 'tuple'> <class 'list'> ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday') ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
for i in tuple_name: #code block
#for loop weekend_days = ('Saturday', 'Sunday') for day in weekend_days: print(day) ====================================== Saturday Sunday
#Assign values to multiple variables weekend_days = ('Saturday', 'Sunday') (sat, sun) = weekend_days print(sat) print(sun) ====================================== Saturday Sunday
#Assign list values to Tuples weekend_days = ['Saturday', 'Sunday'] (sat, sun) = weekend_days print(sat) print(sun) ====================================== Saturday Sunday
#Determine highest and lowest number def high_low(number): """Function to determine highest and lowest number in a list""" highest = max(number) lowest = min(number) return(highest, lowest) series_numbers = [12, 82, 35, 14, 99, 32, 78] (highest, lowest) = high_low(series_numbers) print('The highest number in list is {}'.format(highest)) print('The lowest number in list is {}'.format(lowest)) series_numbers = (12, 82, 35, 14, 99, 32, 78) (highest, lowest) = high_low(series_numbers) print('The highest number in tuple is {}'.format(highest)) print('The lowest number in tuple is {}'.format(lowest)) ====================================== The highest number in list is 99 The lowest number in list is 12 The highest number in tuple is 99 The lowest number in tuple is 12
contacts = [('Mike', '123-4567'), ('Henry', '789-1234')] for (name, phone) in contacts: print("{}'s phone number is {}".format(name, phone)) ====================================== Mike's phone number is 123-4567 Henry's phone number is 789-1234
Tuples can be converted to lists using the list() built-in function.
Lists can be converted to tuples using the tuple() built-in function.
17. Functions
DRY: Don’t repeat yourself. Write one time and use many times.
Built-in functions:
print () – Display output to the screen
len() – Returns length of item
str() – Returns a string object
input() – Accepts standard input from the keyboard
sorted() – Sorts the items in a list
range() – Gives the range and often used in for loop
list() – Returns a list
tuple() – Returns a tuple
type() – Returns an object type
open() – Opens a file and returns a file object
A function must be defined before it is called.
#function without parameters def function_name(): #code
def hello_world(): print('Hi..!!') hello_world() ====================================== Hi..!!
def hello_world(name): print('Hello {}! How are you?'.format(name)) hello_world('Mick') hello_world('Smith') ====================================== Hello Mick! How are you? Hello Smith! How are you?
#Default value for name parameter is assigned def hello_world(name = 'User'): print('Hello {}! How are you?'.format(name)) hello_world() hello_world('Smith') ====================================== Hello User! How are you? Hello Smith! How are you?
#Multiple parameters def hello_world(firstName, LastName): print('Hello {} {}! How are you?'.format(firstName, LastName)) hello_world('Mike', 'P') ====================================== Hello Mike P! How are you?
#Positional parameters def hello_world(firstName, lastName): print('Hello {} {}! How are you?'.format(firstName, lastName)) hello_world(firstName = 'Mike', lastName = 'P') hello_world(lastName = 'P', firstName = 'Mike') ====================================== Hello Mike P! How are you? Hello Mike P! How are you?
#Required and default parameters def hello_world(firstName, lastName = 'lastName'): print('Hello {} {}! How are you?'.format(firstName, lastName)) hello_world('Mike') hello_world('Mike', 'P') ====================================== Hello Mike lastName! How are you? Hello Mike P! How are you?
#built-in help function is used to get help with an object. def hello_world(firstName, lastName = 'lastName'): """This is considered as doc string. When supplying a function to help() the docstring contained within the function is displayed """ #Single line comment print('Hello {} {}! How are you?'.format(firstName, lastName)) help(hello_world) ====================================== Help on function hello_world in module __main__: hello_world(firstName, lastName='lastName') This is considered as doc string. When supplying a function to help() the docstring contained within the function is displayed
# The return statement exits the function and passes back what follows return #Even or odd number def even_odd(number): """Determine if a number is even or odd""" if number % 2 == 0: return 'Even' else: return 'Odd' even_odd_num = even_odd(10) print(even_odd_num) ====================================== Even
#odd number def is_odd(number): """Determine if a number odd""" if number % 2 == 0: return False else: return True print(is_odd(10)) ====================================== False
#function getting called from another function def get_name(): """Get Name""" name = input('Please enter your name ') return name def say_name(name): print('Your name is {}'.format(name)) def get_say_name(): """Get and display name""" name = get_name() say_name(name) print('get_say_name function') get_say_name() ====================================== Please enter your name Srikanth Your name is Srikanth get_say_name function
18. Print Delimiter
print is a function that can be executed by passing multiple parameters with , delimiter. When comma is given the o/p is generated with space between actual values. When comma is excluded then the o/p is generated w/o space between actual values.
>>> print("Srikanth G D") Srikanth G D >>> print("Srikanth", "G", "D") Srikanth G D >>> print("Srikanth" "G" "D") SrikanthGD >>> print(250) 250 >>> print(250.60) 250.6 >>> print(250.61) 250.61 >>> print("Srikanth G D", 123, 123.45) Srikanth G D 123 123.45 >>> print("Srikanth G D" 123 123.45) File "<stdin>", line 1 print("Srikanth G D" 123 123.45) ^ SyntaxError: invalid syntax >>> print(123, 123.45) 123 123.45 >>> print(123 123.45) File "<stdin>", line 1 print(123 123.45) ^ SyntaxError: invalid syntax >>> print(123 123) File "<stdin>", line 1 print(123 123) ^ SyntaxError: invalid syntax
19. Return statement
20. If statement (Conditional statements)
age = 25 if age >= 35: print('You are old enough to be a Project Manager') elif age >= 30: print('You are old enough to be a Team Leader') else: print('You are old enough to be a Team Member') print('Have a good day..!!') ====================================== You are old enough to be a Team Member Have a good day..!!
age = 50 if age >= 35: print('You are old enough to be a Project Manager') elif age >= 30: print('You are old enough to be a Team Leader') else: print('You are old enough to be a Team Member') print('Have a good day..!!') ====================================== You are old enough to be a Project Manager Have a good day..!!
# Ask for the distance. distance = input('How far would you like to travel in miles? ') # Convert the distance to an integer. distance = int(distance) # Determine what mode of transport to use. if distance < 3: mode_of_transport = 'walking' elif distance < 300: mode_of_transport = 'driving' else: mode_of_transport = 'flying' # Display the result. print('I suggest {} to your destination. The distance is {}'.format(mode_of_transport, distance)) print('I suggest ' + mode_of_transport + ' to your destination.') ====================================== How far would you like to travel in miles? 1000 I suggest flying to your destination. The distance is 1000 I suggest flying to your destination.
21. If statements and comparisons
22. Dictionaries
They hold key-value pairs called items. Access the values stored in a dictionary by key.
dictionary_name = {key_1: value_1, key_2: value_2, key_n: value_n} dictionary_name = {} dictionary_name[key]
contacts = {'Mike':'123-4567', 'Henry':'789-1234'} mike_contact = contacts['Mike'] henry_contact = contacts['Henry'] print('Dial {} to contact Mike'.format(mike_contact)) print('Dial {} to contact Henry'.format(henry_contact)) ====================================== Dial 123-4567 to contact Mike Dial 789-1234 to contact Henry
#Assigning new value to key contacts = {'Mike':'123-4567', 'Henry':'789-1234'} contacts['Mike'] = '001-2345' mike_contact = contacts['Mike'] print('Dial {} to contact Mike'.format(mike_contact)) ====================================== Dial 001-2345 to contact Mike
#Assign new key-value pair to dictionary contacts = {'Mike':'123-4567', 'Henry':'789-1234'} contacts['Tony'] = '456-7890' print(contacts) print(len(contacts)) ====================================== {'Mike': '123-4567', 'Henry': '789-1234', 'Tony': '456-7890'} 3
#Remove items from dictionary contacts = {'Mike':'123-4567', 'Henry':'789-1234'} del contacts['Mike'] print(contacts) print(len(contacts)) ====================================== {'Henry': '789-1234'} 1
#Value stored in dictionary need not be same data type. #Mike is having list datatype and Henry holding string datatype contacts = {'Mike':['123-4567', '456-7890'], 'Henry':'789-1234'} print(contacts) print(len(contacts)) print(contacts['Mike']) print(contacts['Henry']) ====================================== {'Mike': ['123-4567', '456-7890'], 'Henry': '789-1234'} 2 ['123-4567', '456-7890'] 789-1234
#for loop contacts = {'Mike':['123-4567', '456-7890'], 'Henry':'789-1234'} for i in contacts['Mike']: print('Phone: {}'.format(i)) ====================================== Phone: 123-4567 Phone: 456-7890
#for loop contacts = {'Mike':['123-4567', '456-7890'], 'Henry':'789-1234'} for i in contacts: print('The contact number of {0} is {1}'.format((i), contacts[i])) ====================================== The contact number of Mike is ['123-4567', '456-7890'] The contact number of Henry is 789-1234
#Tony key do not exist in dictionary so no value returned contacts = {'Mike':['123-4567', '456-7890'], 'Henry':'789-1234'} if 'Mike' in contacts.keys(): print(contacts['Mike'][0]) if 'Tony' in contacts.keys(): print(contacts['Tony'][0]) ====================================== 123-4567
#Check existence of particular value in dictionary contacts = {'Mike':['123-4567', '456-7890'], 'Henry':'789-1234'} print('789-1234' in contacts.values()) ====================================== True
#looping with two variables for key_variable, value_variable in dictionary_name.items(): #code block
#looping with two variables contacts = {'Mike':['123-4567', '456-7890'], 'Henry':'789-1234'} for person, number in contacts.items(): print('The contact number of {0} is {1}'.format(person, number)) ====================================== The contact number of Mike is ['123-4567', '456-7890'] The contact number of Henry is 789-1234
#nested dictionary contacts = { 'Mike':{'phone': '123-4567', 'email':'mike@abc.com'}, 'Henry':{'phone': '789-1234', 'email':'henry@abc.com'}, 'Tony':{'phone': ['456-1234', '345-1234'], 'email':'tony@abc.com'} } for person, number in contacts.items(): print('The contact details of {0} is {1}'.format(person, number)) for contact in contacts: print("{}'s contact number is {} and email is {}".format(contact, contacts[contact]['phone'], contacts[contact]['email'])) ====================================== The contact details of Mike is {'phone': '123-4567', 'email': 'mike@abc.com'} The contact details of Henry is {'phone': '789-1234', 'email': 'henry@abc.com'} The contact details of Tony is {'phone': ['456-1234', '345-1234'], 'email': 'tony@abc.com'} Mike's contact number is 123-4567 and email is mike@abc.com Henry's contact number is 789-1234 and email is henry@abc.com Tony's contact number is ['456-1234', '345-1234'] and email is tony@abc.com
23. While loop
list_name = ['Apple', 'Orange', 'Mango'] index = 0 while index < len(list_name): print(list_name[index]) index += 1 ====================================== Apple Orange Mango
**To break infinite loop in Python use Ctrl+C
24. For loop
list_name = ['Apple', 'Orange', 'Mango'] for variable_name in list_name: print(variable_name) ====================================== Apple Orange Mango
for number in range(5): print(number) ====================================== 0 1 2 3 4
for number in range(2, 6): print(number) ====================================== 2 3 4 5
#increment by 2 for number in range(1, 10, 2): print(number) ====================================== 1 3 5 7 9
#increment by 2 item_list = ['Apple', 'Orange', 'Mango', 'Apricot', 'Plum', 'Guava'] for number in range(0, len(item_list), 2): print(item_list[number]) ====================================== Apple Mango Plum
25. Exponent Function
26. 2D lists and nested loop
27. Comments
Single line comment we use # (hash)
#This is single line comment #This is single line comment
Multi line comment we use “”” (triple quotes) and make sure to close the triple quotes.
""" We use triple quotes for multi line comment in Python"""
28. Exception Handing – Try/Except
list_name = ['Apple', 'Orange', 'Mango'] orange_list_name = list_name.index('Orange') print(orange_list_name) ====================================== 1
list_name = ['Apple', 'Orange', 'Mango'] plum_list_name = list_name.index('Plum') print(plum_list_name) ====================================== Traceback (most recent call last): File "C:\Users\gdsri\Desktop\Float.py", line 2, in <module> plum_list_name = list_name.index('Plum') ValueError: 'Plum' is not in list
list_name = ['Apple', 'Orange', 'Mango'] try: plum_list_name = list_name.index('Plum') except: plum_list_name = 'No Plum Found' print(plum_list_name) ====================================== No Plum Found
29. Reading and Writing a file
open() – Built in function that opens a file and returns a file object.
open(file_path)
Here file_path can be absolute or relative.
In absolute we have to define entire path and in relative we can define partial path by ensuring we are in correct directory (pwd).
hosts = open('C:\Windows\System32\drivers\etc\hosts') hosts_file_contents = hosts.read() print(hosts_file_contents) ====================================== # Copyright (c) 1993-2009 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. #
read() – Returns the entire file
seek(offset) – Change the current position to offset
seek(0) – Go to the beginning of the file
seek(5) – Go to the 5th byte of the file
tell() – Determine the current position in the file
hosts = open('C:\Windows\System32\drivers\etc\hosts') print('First Current position {}'.format(hosts.tell())) print(hosts.read()) print('Second Current position {}'.format(hosts.tell())) print(hosts.read()) hosts.seek(0) print('Third Current position {}'.format(hosts.tell())) print(hosts.read()) ====================================== First Current position 0 # Copyright (c) 1993-2009 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. # # This file contains the mappings of IP addresses to host names. Each # entry should be kept on an individual line. The IP address should # be placed in the first column followed by the corresponding host name. # The IP address and the host name should be separated by at least one # space. # # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a '#' symbol. # # For example: # # 102.54.94.97 rhino.acme.com # source server # 38.25.63.10 x.acme.com # x client host # localhost name resolution is handled within DNS itself. # 127.0.0.1 localhost # ::1 localhost Second Current position 824 Third Current position 0 # Copyright (c) 1993-2009 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. # # This file contains the mappings of IP addresses to host names. Each # entry should be kept on an individual line. The IP address should # be placed in the first column followed by the corresponding host name. # The IP address and the host name should be separated by at least one # space. # # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a '#' symbol. # # For example: # # 102.54.94.97 rhino.acme.com # source server # 38.25.63.10 x.acme.com # x client host # localhost name resolution is handled within DNS itself. # 127.0.0.1 localhost # ::1 localhost
hosts = open('C:\Windows\System32\drivers\etc\hosts') print('First Three Characters {}'.format(hosts.read(3))) print(hosts.tell()) ====================================== First Three Characters # C 3
#Good practise to close a file hosts = open('C:\Windows\System32\drivers\etc\hosts') hosts_file_contents = hosts.read() print(hosts_file_contents) hosts.close()
#Good practise to close a file hosts = open('C:\Windows\System32\drivers\etc\hosts') hosts_file_contents = hosts.read() print("Is file closed? {}".format(hosts.closed)) if not hosts.closed: hosts.close() print("Is file closed? {}".format(hosts.closed)) ====================================== Is file closed? False Is file closed? True
Automatically close a file:
with open(file_path) as file_object_variable_name:
#code block
#Good practise to close a file print('Start reading the file') with open('C:\Windows\System32\drivers\etc\hosts') as hosts: print("Is file closed? {}".format(hosts.closed)) print(hosts.read(10)) print('Finished reading the file') print("Is file closed? {}".format(hosts.closed)) ====================================== Start reading the file Is file closed? False # Copyrigh Finished reading the file Is file closed? True
#Reading line by line with open('C:\Windows\System32\drivers\etc\hosts') as file: for line in file: print(line) ====================================== # Copyright (c) 1993-2009 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. #
#Removing trailing spaces with open('C:\Windows\System32\drivers\etc\hosts') as file: for line in file: print(line.rstrip()) ====================================== # Copyright (c) 1993-2009 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. #
open(file_path, mode) and different modes are:
i. r – reading (default)
ii. w – writing
iii. x – Create a new file and open it for writing
iv. a – Open for writing, appending to file
v. + – Read or write same file
vi. b – Binary mode
vii. t – Text mode (default)
Check current file mode:
with open(‘file_txt’) as file:
print(file.mode)
with open('C:\Windows\System32\drivers\etc\write_text.txt', 'w') as file: file.write('Enter some text here') file.write('Enter some more text here') with open('C:\Windows\System32\drivers\etc\write_text.txt', 'r') as file: print(file.read()) ====================================== Enter some text hereEnter some more text here
\r – Carriage returns
\n – New line
\r\n – Line endings
#Text in new line with open('C:\Windows\System32\drivers\etc\write_text.txt', 'w') as file: file.write('Enter some text here\n') file.write('Enter some more text here') with open('C:\Windows\System32\drivers\etc\write_text.txt', 'r') as file: print(file.read()) ====================================== Enter some text here Enter some more text here
#Exception handling #Open a file and assign its contents to a variable #If file is not available, create an empty variable try: file = open('file_text.txt').read() except: file = 'No file available' print(file) ====================================== No file available
30. Modules and pip
Modules are files that have .py extension. They can implement a set of attributes(variables), methods(functions) and classes (types). A module can be included in another Python program by using the import statement followed by the module name.
import module_name module_name.method_name() or from module_name import method_name method_name() or from module_name import method_name_1,..., method_name_n
import time print(time.asctime()) or from time import asctime print(asctime()) or from time import asctime, sleep print(asctime()) sleep(2) print(asctime())
Use dir built-in function to get details of attributes, methods and classes exist within a module.
import time print(dir(time)) ====================================== ['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'monotonic_ns', 'perf_counter', 'perf_counter_ns', 'process_time', 'process_time_ns', 'sleep', 'strftime', 'strptime', 'struct_time', 'thread_time', 'thread_time_ns', 'time', 'time_ns', 'timezone', 'tzname']
sys.path – Returns the search path for modules.
import sys print(sys.path)
import sys for path in sys.path: print(path) ====================================== C:\Users\gdsri\Desktop C:\MyWorks\Python\Python37\Lib\idlelib C:\MyWorks\Python\Python37\python37.zip C:\MyWorks\Python\Python37\DLLs C:\MyWorks\Python\Python37\lib C:\MyWorks\Python\Python37 C:\MyWorks\Python\Python37\lib\site-packages C:\MyWorks\Python\Python37\lib\site-packages\win32 C:\MyWorks\Python\Python37\lib\site-packages\win32\lib C:\MyWorks\Python\Python37\lib\site-packages\Pythonwin
Python has large library of modules and check the standard library before writing any code. Refer to ‘http://docs.python.org/3/library’
import sys file_name = 'text.txt' try: with open(file_name) as test_file: for line in test_file: print(line) except: print('Could not open {}'.format(file_name)) sys.exit(1) ====================================== Could not open text.txt
31. Classes and Objects
32. Object Function
33. Inheritance
34. Python interpreter