Introduction To Computer Programming Using Python Comp 111
Introduction To Computer Programming Using Python Comp 111
SCHOOL OF TECHNOLOGY
NJALA UNIVERSITY
NJALA CAMPUS
FOR
It is said you must crawl before you can walk, and walk before
you can ride a bicycle.
So, for those of you familiar with Java or C++, Python will
break the mold you have built for a typical programming
language. The above screenshot displays the trends of these
programming languages as per Google.
Python Interpreter:
Python Installation:
1. Go to www.python.org/downloads/
I am going to use PyCharm, you can use any other IDE that you
want.
Go to www.jetbrains.com/pycharm/download/#section=windows
Now, let us have a look at why one should even consider Python
as a preferred or first programming language.
Python Applications:
1. Artificial Intelligence
2. Desktop Application
3. Automation
4. Web Development
5. Data Wrangling, Exploration And Visualization
S = 10
print(S)
Numeric:
Integer type: It holds all the integer values i.e. all the
positive and negative whole numbers, example – 10.
Complex type: These are of the form a + bj, where a and b are
floats and J represents the square root of -1 (which is an
imaginary number), example – 10+6j.
Now you can even perform type conversion. For example, you can
convert the integer value to a float value and vice-versa.
Consider the example below:
A = 10
# Convert it into float type
B = float(A)
print(B)
A = 10.76
# Convert it into float type
B = int(A)
print(B)
List:
print(Subjects)
Let’s look at few operations that you can perform with Lists:
Tuples:
So the simple answer would be, Tuples are faster than Lists.
If you’re defining a constant set of values which you just
want to iterate, then use Tuple instead of a List.
Now, stop being lazy and don’t expect me to show all those
operations, try it yourself.
Strings:
S = "Welcome To Python!"
D = 'Python!'
Syntax Operation
print Slicing
(String_Name[Start:Stop])
Set:
Set_1 = {1, 2, 3}
Set_2 = {1, 2, 3, 3}
Union:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print ( A | B)
Intersection:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print ( A & B )
Output = {3, 4}
Difference:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A - B)
Output = {1, 2, 3}
Symmetric Difference:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A ^ B)
Output = {1, 2, 3, 6, 7, 8}
Dictionary:
Now you can consider the National ID number as a ‘Key’ and the
person’s detail as the ‘Value’ attached to that Key.
Output = Saurabh
Operators in Python:
Arithmetic Operators:
c = a + b
print(c)
c = a - b
print(c)
c = a * b
print(c)
c = a / b
print(c)
c = a % b
print(c)
a = 2
b = 3
c = a ** b
print(c)
Comparison Operators:
== (A == B) is
not true
If the values of two
operands are equal, then the
condition becomes true.
!= (A != B) is
true
If values of two operands
are not equal, then the
condition becomes true.
a = 21
b = 10
c = 0
if (a == b):
print("a is equal to b")
else:
print("a is not equal to b")
if (a != b):
print("a is not equal to b")
else:
print("a is equal to b")
if (a < b):
print("a is less than b")
else:
print("a is not less than b")
if (a > b):
print("a is greater than b")
else:
print("a is not greater than b")
a = 5
b = 20
if (a >= b):
print("a is either greater than or equal to
b")
else:
print("a is neither greater than nor equal to
b")
a is not equal to b
a is greater than b
Assignment Operators:
a = 21
b = 10
c = 0
c = a + b
print(c)
c += a
print(c)
c *= a
print(c)
c /= a
print(c)
c = 2
c %= a
print(c)
c **= a
print(c)
Bitwise Operators:
a = 58 # 111010
b = 13 # 1101
c = 0
c = a & b
print(c) # 8 = 1000
c = a | b
print(c) # 63 = 111111
c = a ^ b
print(c) # 55 = 110111
c = a >> 2
print(c) # 232 = 11101000
c = a << 2
print(c) # 14 = 1110
Output = 8,63,55,232,14
print('x or y is', x or y)
x or y is True
not x is False
Membership Operators:
Output = True
False
Identity Operators:
X2 = 1234
Y1 = 'Welcome To Python!'
Y2 = 1234
print(X1 is Y1)
print(X1 is X2)
Output = True
False
True
False
Python Statement
Multi-line statement
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
a = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
colors = ['red','blue','green']
a = 1; b = 2; c = 3
Python Indentation
In Python, all the code that you type is arranged via correct
whitespaces and therefore if at any instance you have a bad
indentation, the overall code will not run and the interpreter
will simply return an error function.
for i in range(1,11):
print(i)
if i == 5:
break
if True:
print('Hello')
a = 5
and
if True: print('Hello'); a = 5
both are valid and do the same thing, but the former style is
clearer.
spaces between your lines of code, then you will most likely
process.
● While coding you are using both the tab as well as space.
While in theory both of them serve the same purpose, if
used alternatively in a code, the interpreter gets
confused between which alteration to use and thus returns
an error.
● While programming you have placed an indentation in the
wrong place. Since python follows strict guidelines when
it comes to arranging the code, if you placed any
indentation in the wrong place, the indentation error is
mostly inevitable.
● Sometimes in the midst of finishing a long program, we
tend to miss out on indenting the compound statements
such as for, while and if and this in most cases will
lead to an indentation error.
● Last but not least, if you forget to use user defined
classes, then an indentation error will most likely pop
up.
#1 Solution
While there is no quick fix to this problem, one thing that
each line individually and find out which one contains the
error.
are having a hard time figuring out which line you have missed
of your code editor and enable the option which shows the tab
and whitespaces. Once this feature is turned on, you will see
Enabling this option will guide through each line of code and
show you exactly where your error lies. Although this method
Python Comments
#This is a comment
Run Code
Multi-line comments
"""This is also a
perfect example of
multi-line comments"""
Flow Control
Flow Control lets us define a flow in executing our programs.
To mimic the real world, you need to transform real world
situations into your program. For this you need to control the
execution of your program statements using Flow Controls.
1. if
2. for
3. while
4. break
If Statement
The Python compound statement ’if’ lets you conditionally
execute blocks of statements.
Syntax of If statement:
if expression:
statement (s)
elif expression:
statement (s)
elif expression:
statement (s)
...
else:
statement (s)
password = facebook_hash(input_password)
if password == hash_password
print('Login successful.')
else
print('Login failed. Incorrect password.')
For Statement
The for statement supports repeated execution of a statement
or block of statements that is controlled by an iterable
expression.
Syntax of For statement:
While Statement
The while statement in Python programming supports repeated
execution of a statement or block of statements that is
controlled by a conditional expression.
Syntax of While statement:
while expression:
statement (s)
count = 0
print('Printing numbers from 0 to 9')
while (count<10):
print('The count is ',count)
count = count+1
print('Good Bye')
Break Statement
The break statement is allowed only inside a loop body. When
break executes, the loop terminates. If a loop is nested
inside other loops, break terminates only the innermost nested
loop.
Syntax of Break statement:
Continue Statement
The continue statement is allowed only inside a loop body.
When continue executes, the current iteration of the loop body
terminates, and execution continues with the next iteration of
the loop.
F.Manna Introduction to Python 2019/2020
Syntax of Continue statement:
for x in some_container:
if not seems_ok(x): continue
lowbound, highbound = bounds_to_test()
if x<lowbound or x>=highbound: continue
if final_check(x):
do_processing(x)
Pass Statement
The pass statement, which performs no action, can be used as a
placeholder when a statement is syntactically required but you
have nothing specific to do.
Syntax of Pass statement:
Found a multiple of 5: 10
Found number: 11
Found number: 12
Found number: 13
Found number: 14
Found a multiple of 5: 15
Found number: 16
Found number: 17
Found number: 18
Found number: 19
Found a multiple of 5: 20
After learning the above six flow control statements, let us
now learn what functions are.
Uses Of Functions:
def reverse_a_string():
# Reading input from console
a_string = input("Enter a string")
new_strings = []
File Handling
File Handling refers to those operations that are used to read
or write a file.
To perform file handling, we need to perform these steps:
1. Open File
2. Read / Write File
3. Close File
Opening A File
Example program:
1 file =
2 open("C:/Users/Edureka/Hello.txt"
3 , "r")
for line in file:
print (line)
Writing To A File
Example program:
1 with
2 open("C:/Users/Edureka/Writing_Into_File.txt
3 ", "w") as f
4 f.write("First Line
5 ")
6 f.write("Second Line
7 ")
8
9 file = open("D:/Writing_Into_File.txt", "r")
for line in file:
print (line)
The output is as below:
First Line
Second Line
Example program:
1 file =
2 open("C:/Users/Edureka/Writing_Into_File.
3 txt", "r")
4 print(file.read(5))
print(file.read(4))
print(file.read())
The output is as below:
First Line
Second Line
Closing A File
Example program:
1 file =
2 open("C:/Users/Edureka/Hello.txt"
3 , "r")
4 text = file.readlines()
print(text)
file.close()
The output is as below:
['One
', 'Two
', 'Three']
Creating An Object
A Class object can be used to create new object instances
(instantiation) of that class. The procedure to create an
object is similar to a function call.
1 ob =
MyNewClass
We have thus learnt how to create an object from a given
class.
So this concludes our Python Programming blog. I hope you
enjoyed reading this blog and found it informative. By now,
you must have acquired a sound understanding of what Python
Programming Language is. Now go ahead and practice all the
examples
In the immensely fast moving world, one needs resourceful
coding techniques that could help the programmer to sum up
voluminous codes in the simplest and most convenient ways.
Arrays are one of the data structures that help you write a
number of values into a single variable, thereby reducing the
Conditional Statements:
else:
statements
X = 10
1 Y = 12
2
3 if X < Y: print('X is
4 less than Y')
5 elif X > Y:
6 print('X is greater
7 than Y')
8 else:
print('X and Y are
equal')
Loops:
Loops in Python:
● While
● For
● Nested
print ("Good
bye!")
Output = 0
Good bye!
For Loop: Like the While loop, the For loop also allows a code
block to be repeated certain number of times. The difference
is, in For loop we know the amount of iterations required
unlike While loop, where iterations depends on the condition.
for variable in
1 Sequence:
2 statements
Output = Banana
Apple
Grapes
count = 1
1 for i in
2 range(10):
3 print (str(i)
4 * i)
5
Output =
22
333
4444
55555
666666
7777777
88888888
999999999
Output = 30
● 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.
1 o = open("edureka.txt") # equivalent
2 to 'r' or 'rt'
3 o = open ("edureka.txt",'w') # write in
text mode
o = open ("img1.bmp",'rb' ) # read and
write in binary mode
Closing a file will free up the resources that were tied with
the file and is done using Python close() method.
1 o = open
2 ("edureka.txt")
o.close()
8. Web Development
7. Artificial Intelligence
6. Computer Graphics
Python is largely
used in small, large, online or offline projects. It is used
to build GUI and desktop applications. It uses ‘Tkinter‘
library to provide fast & easy way to create applications.
It is also used in game development where you can write the
logic of using a module ‘pygame’ which also runs on android
devices.
5. Testing Framework
4. Big Data
2. Data Science
● What is Python 3?
● Why Learn Python 3?
● Features of Python 3
● Comparison: Python 2 vs Python 3
● Fundamentals of Python
● Your First Python 3 program – Check Prime Number
What is Python 3?
Python is a free open source, multi-purpose programming
language, created by Guido Van Rossum in 1991. Since Python’s
first release, the language has gone through many changes and
improvements. It was built as a successor to programming
language ABC. Python’s primary advantage was that it had the
capability to handle exceptions and interface with an
operating system named ‘Amoeba‘. With time Python language has
evolved and grown manifolds. It’s time to study Python 3
language in detail.
● Python 3 vs Java
● Python 3 vs R
● Python 3 vs Go lang
Features of Python 3
Python 3 offers rich functionality making it the most
appropriate for solving real-life problems. I have written
down a few important features of Python, below:
● Platform independent
● Interpreted
● Extensive libraries
○ Numpy
Pandas
Matplotlib
○ ScikitLearn
○ Tkinter
Python 3 Applications
Few of the most important domains in which Python is used to
develop applications is described below:
● Web applications
● Game development
● 3D modeling
● Scientific and statistical analysis
Fundamentals of Python
I have written down the fundamental topics that you should
study in order to get started with Python 3.
● Interfaces
● Web development
● Testing
I hope you were able to read through the article and get a
fair understanding to learn Python 3 programming. Python 3 is
like a Swiss knife of functionalities, that a programming
language can execute. As a result, get inspired and learn
Python 3 today!
Python Installation
Let us now move on to installing Python on a Windows systems.
1. Datatypes
2. Flow Control
3. Functions
4. File Handling
5. Object & Class
Datatypes
All data values in Python are represented by objects and each
object or value has a datatype.
1. Boolean
2. Numbers
3. Strings
4. Bytes & Byte Arrays
5. Lists
6. Tuples
7. Sets
8. Dictionaries
num1 is 125
num2 is 10
num3 is 10.666666666666666
5
['India', 'Australia', 'United States', 'Canada', 'Singapore']
['India', 'Australia', 'United States', 'Canada', 'Singapore',
'Brazil']
['India', 'Australia', 'United Kingdom', 'United States',
'Canada', 'Singapore', 'Brazil']
Creating an Array:
Arrays in Python can be created after importing the array
module as follows –
→ import array as arr
The array(data type, value list) function takes two
parameters, the first being the data type of the value to be
stored and the second is the value list. The data type can be
anything such as int, float, double, etc. Please make a note
that arr is the alias name and is for ease of use. You can
import without alias as well. There is another way to import
the array module which is –
→ from array import *
This means you want to import all functions from the array
module.
The following syntax is used to create an array.
i int 2
I int 2
u unicode character 2
h int 2
H int 2
l int 4
L int 4
f float 4
d float 8
Array Concatenation :
Any two arrays can be concatenated using the + symbol.
Example:
1 a=arr.array('d',[1.1 , 2.1
2 ,3.1,2.6,7.8])
3 b=arr.array('d',[3.7,8.6])
4 c=arr.array('d')
5 c=a+b
print("Array c = ",c)
Output –
Array c= array(‘d’, [1.1, 2.1, 3.1, 2.6, 7.8, 3.7, 8.6])
The resulting array c contains concatenated elements of arrays
a and b.
Now, let us see how you can remove or delete items from an
array.
Slicing an array :
An array can be sliced using the : symbol. This returns a
range of elements that we have specified by the index numbers.
Example:
1 a=arr.array('d',[1.1 , 2.1
2 ,3.1,2.6,7.8])
print(a[0:3])
Output –
array(‘d’, [1.1, 2.1, 3.1])
The above output shows the result using for loop. When we use
for loop without any specific parameters, the result contains
all the elements of the array given one at a time. In the
second for loop, the result contains only the elements that
are specified using the index values. Please note that the
result does not contain the value at index number 3.
.
Now let us move ahead and see how to create sets in Python.
Set Operations
A number of operations can be performed on sets such as adding
elements, deleting elements, finding the length of a set, etc.
To know what all methods can be used on sets, you can use the
dir() function.
Example:
1 My_Set={1,'s'
2 ,7.8}
dir(My_Set)
Output:
[‘__and__’,’__class__’,’__contains__’,’__delattr__’,’__dir__’,
’__doc__’,’__eq__’,’__format__’,’__ge__’,’__getattribute__’,
‘__gt__’, ‘__hash__’, ‘__iand__’, ‘__init__’,
‘__init_subclass__’, ‘__ior__’, ‘__isub__’, ‘__iter__’,
‘__ixor__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__ne__’,
‘__new__’, ‘__or__’, ‘__rand__’, ‘__reduce__’,
‘__reduce_ex__’, ‘__repr__’, ‘__ror__’, ‘__rsub__’,
‘__rxor__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__sub__’,
‘__subclasshook__’, ‘__xor__’, ‘add’, ‘clear’, ‘copy’,
‘difference’, ‘difference_update’, ‘discard’, ‘intersection’,
Union of Sets
Union of sets refers to the concatenation of two or more sets
into a single set by adding all unique elements present in
both sets. This can be done in two ways:
● Using pipeline
● Using union() function
Example:
Difference of Sets:
The difference of sets produces a new set consisting of
elements that are present only in one of those sets. This
means that all elements except the common elements of those
sets will be returned.
This can be done in two ways:
Conditional Statements
Conditional statements in Python support the usual logical
conditions from mathematics.
For example:
● Equals: a == b
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
‘if’ Statement
An if statement is written using the ‘if’ keyword, The syntax
is the keyword ‘if’ followed with the condition.
Below is the flowchart of the if statement:
‘else’ Statement
The else keyword catches anything that is not caught by the
preceding conditions. When the condition is false for the if
statement, the execution will move to the else statement.
Lets take a look at the flowchart of else statement below:
As you can see, when the if statement was false the execution
moved to the body of else. Lets understand this with an
example.
‘elif’ Statement
elif statement in layman term means “try this condition
instead”. Rest of the conditions can be used by using the elif
keyword.
Let us look at the code below:
1 a = 10
2 b = 20
3 if a < b :
4 print(" b is
5 greater")
6 elif a == b :
7 print(" a is equal
8 to b ")
else:
print(" a is
greater")
“When the if statement is not true, the execution will move to
the elif statement and check if it holds true. And in the end
the else statement if and elif are false.
Since a != b, “b is greater” will get printed here.
Note: python relies on indentation, other programming
languages use curly brackets for loops.
Range Function
Range function requires a specific sequence of numbers. It
starts at 0 and then the value increments by 1 until the
specified number is reached.
For example:
1 for x in
2 range(3)
print(x)
It will print from 0-2, the output will look like
0
1
2
Note: the range (3) does not mean the values from 0-3 but the
values from 0-2.
Below is another example using the condition statements:
‘while’ Loop
The ‘while’ loop executes the set of statements as long as the
condition is true.
It consists of a condition block and the body with the set of
statements, It will keep on executing the statement until the
condition becomes false. There is no guarantee to see how long
the loop will keep iterating.
Following is the flowchart for while loop:
Break
Break statement is used to terminate the execution of the loop
containing it. As soon as the loop comes across a break
statement, the loop terminates and the execution transfers to
the next statement following the loop.
As you can see the execution moves to the statement below the
loop, when the break returns true.
Let us understand this better with an example:
1 for val in
2 "string" :
3 if val ==
4 "i":
5 break
Output:
s
t
r
The end
Here the execution will stop as soon as the string “i” is
encountered in the string. And then the execution will jump to
the next statement.
Continue
The continue statement is used to skip the rest of the code in
the loop for the current iteration. It does not terminate the
loop like the break statement and continues with the remaining
iterations.
print(val)
print("the
end")
Output:
s
t
r
n
g
It will skip the string “i” in the output and the rest of the
iterations will still execute. All letters in the string
except “i” will be printed.
Pass
The pass statement is a null operation. It basically means
that the statement is required syntactically but you do not
wish to execute any command or code.
Take a look at the code below:
1 for val in
2 "please":
3 if val == "a":
4 pass
5 print("pass
block")
print(val)
Output:
p
l
e
pass block
a
s
e
The execution will not be affected and it will just print the
pass block once it encounters the “a” string. And the
execution will start at “a” and execute the rest of the
remaining iterations.
break
i
+= 1
Output: it will print 1 2
The execution will be terminated when the iteration comes to 3
and the next statement will be executed.
continue
i +=
1
Output: 1 2 4 5
Here the execution will be skipped, and the rest of the
iterations will be executed.
Nested Loops
Python allows us to use one loop inside another loop,
Following are a few examples
Python Functions
Example
1 # random integer
2 integer = -20
3 print('Absolute value of -20 is:',
4 abs(integer))
5
6 #random floating number
7 floating = -30.33
print('Absolute value of -30.33 is:',
abs(floating))
Output
Absolute value of -20 is: 20 Absolute value of -30.33 is:
30.33
Example
print('Pythn is
interesting')
Output
'Python is interesting'
'Pythn is interesting'
Pythön is interesting
Example
1 number = 5
2 print('The binary equivalent of 5
is:', bin(number))
Output
The binary equivalent of 5 is: 0b101
Example
1 codeInString = 'a = 5
2 b=6
3 sum=a+b
4 print("sum =",sum)'
5 codeObejct = compile(codeInString,
6 'sumstring', 'exec')
7
exec(codeObejct)
Output
sum = 11
Example
Example
Example
Example
1 class Person:
2 age = 23
3 name = "Adam"
4
5 person = Person()
6 print('The age is:',
7 getattr(person, "age"))
print('The age is:',
person.age)
Output
The age is: 23
The age is: 23
Example
1 # using max(arg1, arg2,
2 *args)
3 print('Maximum is:', max(1,
4 3, 2, 5, 4))
5
6 # using max(iterable)
num = [1, 3, 2, 8, 5, 10, 6]
print('Maximum is:',
max(num))
Output
Maximum is: 5
Maximum is: 10
Example
1 # using min(arg1, arg2,
2 *args)
3 print('Minimum is:', min(1,
4 3, 2, 5, 4))
5
6 # using min(iterable)
num = [3, 2, 8, 5, 10, 6]
print('Minimum is:',
min(num))
Output
Minimum is: 1
Minimum is: 2
Example
1 # decimal number
2 print('oct(10) is:',
3 oct(10))
4
5 # binary number
6 print('oct(0b101) is:',
7 oct(0b101))
8
# hexadecimal number
print('oct(0XA) is:',
oct(0XA))
Output
oct(10) is: 0o12
oct(0b101) is: 0o5
oct(0XA) is: 0o12
Example
1 # positive x, positive
2 y (x**y)
3 print(pow(2, 2))
4
5 # negative x, positive
6 y
7 print(pow(-2, 2))
8
9 # positive x, negative
1 y (x**-y)
0 print(pow(2, -2))
1
1 # negative x, negative
y
print(pow(-2, -2))
Output
4
4
0.25
0.25
Example
1 # for string
2 seqString = 'Python'
3 print(list(reversed(seqString
4 )))
5
6 # for tuple
7 seqTuple = ('P', 'y', 't',
8 'h', 'o', 'n')
9 print(list(reversed(seqTuple)
1 ))
0
1 # for range
1 seqRange = range(5, 9)
1 print(list(reversed(seqRange)
2 ))
1
3 # for list
1 seqList = [1, 2, 4, 3, 5]
4 print(list(reversed(seqList))
1 )
5
Output
['n', 'o', 'h', 't', 'y', 'P']
['n', 'o', 'h', 't', 'y', 'P']
Example
1 numbers = [2.5, 3, 4,
2 -5]
3
4 # start parameter is
5 not provided
6 numbersSum =
7 sum(numbers)
8 print(numbersSum)
9
# start = 10
numbersSum =
sum(numbers, 10)
print(numbersSum)
Output
4.5
14.5
Example
1 numberList = [1, 2]
2 print(type(numberList))
3
4 numberDict = {1: 'one',
5 2: 'two'}
6 print(type(numberDict))
7
8 class Foo:
9 a = 0
1
0 InstanceOfFoo = Foo()
1 print(type(InstanceOfFo
1 o))
Output
<class 'dict'>
<class 'Foo'>
Next up on this Python Functions blog, let us check out the
Recursive Function in Python.
Advantages of Recursion
Disadvantages of Recursion
Lambda functions can have any number of arguments but only one
expression. The expression is evaluated and returned. Lambda
functions can be used wherever function objects are required.
Example
1 # Program to show the use of
2 lambda functions
3
4 double = lambda x: x * 2
5
6 # Output: 10
print(double(5))
Output
10
In [1]:
In the above program, lambda x: x * 2 is the Lambda function.
Here x is the argument and x * 2 is the expression that gets
evaluated and returned.
This function has no name. It returns a function object which
is assigned to the identifierdouble We can now call it as a
normal function. The statement
double = lambda x: x * 2
Syntax
def function_name(argument1, argument2, ...) :
statement_1
statement_2
....
Example
1 # Program to illustrate
2 # the use of user-defined
3 functions
4
5 def add_numbers(x,y):
6 sum = x + y
7 return sum
8
9 num1 = 5
● Binary
● Text
● Create
● Read
● Update
● Delete
However, do note that there are many other operations that can
be performed with the files as well. Such as, copying a file
or changing the properties of the file and filter.
All of these operations are important to manipulate the file.
This manipulation ensures that the file operations can be
performed as per the exact requirement of the user working on
the file.
Open Modes:
These are the various modes available to open a file. We can
open in read mode, write mode, append mode and create mode as
well. Pretty straightforward. But do note that the default
mode is the read mode.
Including a mode argument is optional because a default value
of ‘r’ will be assumed if it is omitted. The ‘r’ value stands
for read mode, which is just one of many.
The modes are:
‘r’ – Read mode which is used when the file is only being read
‘w’ – Write mode which is used to edit and write new
information to the file (any existing files with the same name
will be erased when this mode is activated)
‘a’ – Appending mode, which is used to add new data to the end
of the file; that is new information is automatically amended
to the end
‘r+’ – Special read and write mode, which is used to handle
both actions when working with a file
Note that you can open a file in read more only if it exists
as well. If you try to read something that doesn’t exist then
Python will greet you with a beautiful error message.
In addition, you can specify if the file should be handled as
binary or text mode along with the mode as well. You can have
the mode as WT so it means that the file is to be opened in
the write mode and the file Python is opening is a text file.
Example
1 f =
2 open(“workfile”,”
w”)
print file.read(5)
Notice how we’re using the same file.read() method, only this
time we specify the number of characters to process?
The output for this will look like:
Hello
If you want to read a file line by line – as opposed to
pulling the content of the entire file at once – use the
readline() function.
Why would you use something like this?
Let’s say you only want to see the first line of the file – or
the third. You would execute the readline()function as many
times as possible to get the data you were looking for.
Each time you run the method, it will return a string of
characters that contains a single line of information from the
file.
1 file =
2 open(“demo.txt”,
“r”)
print
file.readline():
This would return the first line of the file, like so:
Hello World
If we wanted to return only the third line in the file, we
would use this:
1 file =
2 open(“testfile.txt”,
“r”)
print file.readline(3):
file.close()
Obviously, this will amend our current file to include the two
new lines of text. There’s no need to show output.
Next up on this “File Handling in Python” blog, let us look at
how we can close a text file using Python.
Now, let us move ahead and see how it works in PyCharm. To get
started, first have a look at the syntax of a python class.
Syntax:
1 class
2 Class_name:
3 statement-1
4 .
5 .
statement-N
Here, the “class” statement creates a new class definition.
The name of the class immediately follows the keyword “class”
in python which is followed by a colon. To create a class in
python, consider the below example:
1 class employee:
2 pass
3 #no attributes and methods
4 emp_1=employee()
5 emp_2=employee()
6 #instance variable can be
7 created manually
8 emp_1.first='aayushi'
9 emp_1.last='Johari'
1
0 emp_1.email='[email protected]
1 '
1 emp_1.pay=10000
1
2 emp_2.first='test'
print(emp_1.__dict__)
●
After executing it, you will get output such as:
{‘fname’: ‘aayushi’, ‘lname’: ‘johari’, ‘sal’: 350000,
’email’: ‘[email protected]’}
● Attributes defined by Users: Attributes are created
inside the class definition. We can dynamically create
new attributes for existing instances of a class.
Attributes can be bound to class names as well.
OOPs Concepts
OOPs refers to the Object-Oriented Programming in Python.
Well, Python is not completely object-oriented as it contains
some procedural functions. Now, you must be wondering what is
the difference between a procedural and object-oriented
programming. To clear your doubt, in a procedural programming,
the entire code is written into one long procedure even though
it might contain functions and subroutines. It is not
manageable as both data and logic get mixed together. But when
we talk about object-oriented programming, the program is
split into self-contained objects or several mini-programs.
Each object is representing a different part of the
application which has its own data and logic to communicate
among themselves. For example, a website has different objects
such as images, videos etc.
Object-Oriented programming includes the concept of Python
class, object, Inheritance, Polymorphism, Abstraction etc.
Let’s understand these topics in detail.
As
we can see in the image, a child inherits the properties from
the father. Similarly, in python, there are two classes:
1. Parent class ( Super or Base class)
2. Child class (Subclass or Derived class )
A class which inherits the properties is known as Child Class
whereas a class whose properties are inherited is known as
Parent class.
● Process-based
● Thread-based
Python RegEx:
Regular Expressions can be used to search, edit and manipulate
text. This opens up a vast variety of applications in all of
the sub-domains under Python. Python RegEx is widely used by
almost all of the startups and has good industry traction for
their applications as well as making Regular Expressions an
asset for the modern day programmer.
In this Python RegEx blog, we will be checking out the
following concepts:
● Java
● Python
● Ruby
● Swift
● Scala
● Groovy
● C#
● PHP
● Javascript
Among all of the data from the given string, let us say we
require only the City. This can be converted into a dictionary
with just the name and the city in a formatted way. The
question now is that, can we identify a pattern to guess the
for i in allStr:
print(i)
What is common in the string? You can see that the letters ‘a’
and ‘t’ are common among all of the input strings. [shmp] in
for i in someStr:
print(i)
Output:
hat
mat
Let us now change the above program very slightly to obtain a
very different result. Check out the below code and try to
catch the difference between the above one and the below one:
print(Food)
In the above example, the word rat is replaced with the word
food. The final output will look like this. The substitute
method of the Regular Expressions is made use of this case and
it has a vast variety of practical use cases as well.
Output:
hat food mat pat
Next up on this Python RegEx blog, we will check out a unique
problem to Python called the Python Backslash problem.
The Backslash Problem:
Consider an example code shown below:
1 import re
2
3 randstr = "Here is
4 Edureka"
5
print(randstr)
Output:
Here is Edureka
This is the backslash problem. One of the slashes vanished
from the output. This particular problem can be fixed using
Regular Expressions.
1 import re
2
3 randstr = "Here is
4 Edureka"
5
print(re.search(r"Edureka"
, randstr))
The output can be as follows:
<re.Match object; span=(8, 16), match='Edureka'>
As you can check out, the match for the double slashes has
been found. And this is how simple it is to solve the
backslash problem using Regular Expressions.
● : Backspace
● : Formfeed
●
: Carriage Return
● : Tab
● : Vertical Tab
● 444-122-1234
● 123-122-78999
● 111-123-23
● 67-7890-2019
● [email protected]
● Anirudh @ com
● AC .com
● 123 @.com
Code: