You are on page 1of 40

1

2
3
4
Operators
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

Types of Operator
Python language supports the following types of operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

5
Let us have a look on all operators one by one.

Python Arithmetic Operators


Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example


+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
*
Multiplies values on either side of the operator a * b = 200
Multiplication
/ Division Divides left hand operand by right hand operand b/a=2
Divides left hand operand by right hand operand and
% Modulus b%a=0
returns remainder
Performs exponential (power) calculation on
** Exponent a**b =10 to the power 20
operators
Floor Division - The division of operands where the
result is the quotient in which the digits after the
9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -
// decimal point are removed. But if one of the
4.0
operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative infinity):

Python Comparison Operators


These operators compare the values on either sides of them and decide the relation among them. They are also called
Relational operators.
Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example


If the values of two operands are equal, then the
== (a == b) is not true.
condition becomes true.
If values of two operands are not equal, then condition
!=
becomes true.
If values of two operands are not equal, then condition
<> (a <> b) is true. This is similar to != operator.
becomes true.
If the value of left operand is greater than the value of
> (a > b) is not true.
right operand, then condition becomes true.
If the value of left operand is less than the value of
< (a < b) is true.
right operand, then condition becomes true.
If the value of left operand is greater than or equal to
>= the value of right operand, then condition becomes (a >= b) is not true.
true.
If the value of left operand is less than or equal to the
<= (a <= b) is true.
value of right operand, then condition becomes true.

Python Assignment Operators


Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example


Assigns values from right side operands to left side
= c = a + b assigns value of a + b into c
operand

6
+= Add It adds right operand to the left operand and assign the
c += a is equivalent to c = c + a
AND result to left operand
-= Subtract It subtracts right operand from the left operand and
c -= a is equivalent to c = c - a
AND assign the result to left operand
*=
It multiplies right operand with the left operand and
Multiply c *= a is equivalent to c = c * a
assign the result to left operand
AND
/= Divide It divides left operand with the right operand and c /= a is equivalent to c = c / ac /= a is equivalent to c
AND assign the result to left operand =c/a
%=
It takes modulus using two operands and assign the
Modulus c %= a is equivalent to c = c % a
result to left operand
AND
**=
Performs exponential (power) calculation on
Exponent c **= a is equivalent to c = c ** a
operators and assign value to the left operand
AND
//= Floor It performs floor division on operators and assign
c //= a is equivalent to c = c // a
Division value to the left operand

Python Bitwise Operators


Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they
will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language

Operator Description Example


Operator copies a bit to the result if it exists in
& Binary AND (a & b) (means 0000 1100)
both operands
| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011 1101)
It copies the bit if it is set in one operand but not
^ Binary XOR (a ^ b) = 49 (means 0011 0001)
both.
~ Binary Ones (~a ) = -61 (means 1100 0011 in 2's complement
It is unary and has the effect of 'flipping' bits.
Complement form due to a signed binary number.
<< Binary Left The left operands value is moved left by the
a << = 240 (means 1111 0000)
Shift number of bits specified by the right operand.
>> Binary Right The left operands value is moved right by the
a >> = 15 (means 0000 1111)
Shift number of bits specified by the right operand.

logical operators

There are following logical operators supported by Python language. Assume variable a holds 10 and variable b
holds 20 then
Operator Description Example
and Logical AND If both the operands are true then condition becomes true. (a and b) is true.

7
If any of the two operands are non-zero then condition
or Logical OR (a or b) is true.
becomes true.
not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is false.

Python Operators Precedence


The following table lists all operators from highest precedence to lowest.

Operator Description
** Exponentiation (raise to the power)
Ccomplement, unary plus and minus (method names for the last two are +@ and -
~+-
@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators

8
format specifies ෙයාදා ගැ ම.

Format String Meaning Data Type


%d Integer Decimal int,
%o Octal Decimal int
%x Hexadecimal int
%f Floating Point (Decimal Notation) float
%e Floating Point (1.E notation) float
%c First Character or argument is printed char
%s Argument is taken to be a string string
%r convert argument to python object any python type

format specifies ෙයාදා ගැ ම.


>>>Print (“Hello %s” % (“world”)) Hello world
>>>Print (“include an integer : % d ” % 5) include an integer: 5
>>>Print (“include a float : % f ” % 1.25) include a float :1.25
>>>Print (“include a float : % .2f ” % 1.254657) include a float : 1.25

Escape format specifies


>>>Print (“using %d to add integers” % 5 ) using 5 to add integers
>>>Print (“using% %d to add integers : %d “ % 5 ) using %d to add integers:5
>>>Print (“using% %f to add float : %f“ % 5 ) Using %f to add float:5.000000

octal බවට ප ව තනය hexadecimal බවට ප ව තනය


>>> print (“%O” % 100) 124 >>> print (“%X” % 100) 64

Python වල ද ත ව ග

Numbers Integer, Real, Boolean ,Complex


Sequence Immutable sequence-string, tuple, bytes
Mutable sequence-list
Set type Sets, frozen sets
Dictionary dict

9
ද ත ව ගය බැ ම
>>>Y=”%x”%100 <class ’str’>
>>>Type(Y)
>>>S=1.23453 < class ‘Float’>
>>>Type (s)
>>>t=1234 < class ‘int’>
>>>Type (t)
>>>A=[‘mango’,’ apple’,’ orange’, 1234] <class ’list’>
>>>Type (a)
>>>x=true This is wrong
>>>x=True <class ’bool’>
>>>type(x)

 Mutable සහ Immutable ෙලස Python භාෂාෙ ද ත ප ව ග කල හැක.Mutable ගණයට ගැෙනන ද ත පය ෙ


වස් ෙ අගය එම වස් මාණෙය ප ඕනෑම අවස්ථාවක ෙවනස් කල හැක.න Immutable එෙස් කල
ෙනාහැක.
 Immutable ගණයට Numbers, String ,Tuple අය වන අතර List/Dictionary ,Mutable ගණයට අය ෙ ,
 Python භාෂාෙ එකවරකට එක අවයවය බැ දා හ ය හැ ආකාරෙ ද ත එක ව iterable Objects න ෙ

LIST

Most languages have some kind of simple syntax for making lists of things. In python it is extremely easy and intuitive to make a list
of things, for example:
> mylist = [] # Make an empty list
> mylist = [1, 1.0+3j, "aperitivo", True] # Make a list containing four entities

Using lists is easy and intuitive. Notice that lists can contain objects of any data type. Try entering the following lines.
> mylist = [1,2,3,4]
> mylist[2] = 1.0 + 2j # Modify an element
> mylist.append("test") # Add an element to the end of the list
> mylist= mylist+[7] # Add an element to the end of the list

> print len(mylist) # print the length of mylist (5)

> mylist = [1,9,7,32,2.0]


> del(mylist[2]) # Remove element 2 from the list

> mylist = [1,5,4,2]; mylist.sort() # Sort the list

The colon, :, provides a syntax for ranges.


> print mylist[1:4] # Prints a list containing elements 1 2 and 3 from mylist

Remember that there is an element 0, so this prints [4, 6, 8]


> print mylist[-2] # Print the second element from the end of the list (8)

>a=[‘a’,2,[3,’b’,4],[6,’abc’9],8]
>print(a[2][2])
output=4

10
Dictionaries

Lists aren't the only compound data type. Another really useful one is a dictionary (referred to as a map in many other languages).
Dictionaries allow you to set/access elements using a key value relationship. You can create dictionaries as shown below:
> mydictionary = {} # Make an empty dictionary
> mydictionary = {"one" : 1, "two" : 2, "three" : 3} # Initialize a dictionary with some
values

> print (type(mydictionary)) # Tells you mydictionary is of type "dict"


> print (mydictionary["one"]) # Prints the number 1
> print (mydictionary["two"]) # Prints the number 2
> mydictionary["four"] = 4 # Insert an element into the dictionary
> mydictionary["list"] = [1,2,3] # Sets the element "list" to a list containing
> the numbers 1, 2, and 3

Sets

It turns out there is a third type of container in Python that only stores unique things: it's called a set.
> s = set()
> s = set([1,1,2,3,4]) # Note that there are 2 1's in the input list.
> print s
set([1, 2, 3, 4])
> 1 in s
True
> 5 in s
False
> s.add(5)
> 5 in s
True
> anotherSet = set([1,2,"hello"])
> s.intersection(anotherSet)
set([1, 2])

Creating Sets
If we want to create a set, we can call the built-in set function with a sequence or another iterable object.

In the following example, a string is singularized into its characters to build the resulting set x:
>>> x = set("A Python Tutorial")
>>> x
set(['A', ' ', 'i', 'h', 'l', 'o', 'n', 'P', 'r', 'u', 't', 'a', 'y', 'T'])
>>> type(x)
<type 'set'>
>>>

We can pass a list to the built-in set function, as we can see in the following:
>>> x = set(["Perl", "Python", "Java"])
>>> x
set(['Python', 'Java', 'Perl'])
>>>

We want to show now, what happens, if we pass a tuple with reappearing elements to the set function - in our example the city
"Paris":
>>> cities = set(("Paris", "Lyon", "London","Berlin","Paris","Birmingham"))
>>> cities
set(['Paris', 'Birmingham', 'Lyon', 'London', 'Berlin'])
>>>

As we have expected, no doublets are in the resulting set of cities.

11
Immutable Sets
Sets are implemented in a way, which doesn't allow mutable objects. The following example demonstrates that we cannot include
for example lists as elements:
>>> cities = set((("Python","Perl"), ("Paris", "Berlin", "London")))
>>> cities = set((["Python","Perl"], ["Paris", "Berlin", "London"]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>

Frozensets
Though sets can't contain mutable objects, sets are mutable:
>>> cities = set(["Frankfurt", "Basel","Freiburg"])
>>> cities.add("Strasbourg")
>>> cities
set(['Freiburg', 'Basel', 'Frankfurt', 'Strasbourg'])
>>>

Frozensets are like sets except that they cannot be changed, i.e. they are immutable:
>>> cities = frozenset(["Frankfurt", "Basel","Freiburg"])
>>> cities.add("Strasbourg")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>>

Example : Appending/Adding vs Updating

There are two methods to add element(s) to a list: append and update. Likewise, there are two methods to add element(s) to a set: add
and update. What is the difference?
> myList = [1,2,3]
> myAppendedList = myList.append([4,5])
> myUpdatedList = myList.update([4,5])

What is the difference between the appended list and the updated list? Why did this happen?

1. Try the same thing with the add() and update() functions on a set. The key is that containers can hold other containers.

Tuples

There is one other compound data type - the tuple. Think of a tuple as a list that you can't change. The example below demonstrates
how to create and use tuples:
> mytuple = (1,2,3,4) # Create a four element tuple
> mytuple[2] = 4 # ERROR - tuples can't be modified
> print mytuple[2], len(mytuple)

> myonetuple = ("hello",) # Create a tuple containing only one element (note the trailing
comma)

You might be asking yourself, why do we need tuples if we have lists? The answer is that tuples are used internally in Python in a lot
of places. One of the basic differences is that dictionaries cannot use a list as a key, but they can use a tuple:
> d = {}
> d[(1,2)] = 'numbers'
> d
{(1, 2): 'numbers'}
> d[ [1,2] ] = 'listOnumbers'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

12
පාලන ව හ Control Structures
iEu mß.Kl l%uf,aLhl u my; i|yka md,k jHqyhka tlla fyda Bg jeä .Kkla Ndú; flf¾'
1' wkql%uh (sequence)
2' jrKh (selection)
3' mqk¾lrKh (repetition/iteration)
mß.Kl l%uf,aL ;=< we;s j.ka;s l%shd;aul lrk wkqms<sfj< md,k jHqyhka u.ska md,kh flf¾'
1' wkql%uh
l%uf,aLhl we;s j.ka;s tlsfkl wkqms<sfj<ska § we;s wdldrhg l%shd;aul lsÍu wkql%uh kñka y÷kajkq ,efí'
WodyrK 1(
celsius=float(input(“Enter Celsius temperature: “))
fahrenheit = 1.8 * celsius + 32
print “Fahrenheit = “, Fahrenheit

fuu l%uf,aLh u.ska WIaK;ajh fi,aishia w.hla jYfhka ,ndf.k th *erkayhsÜ w.hla njg m;alr th m%;sodkh
lrkq ,efí' fuys we;s Wmfoia ish,a, wkql%ñlj l%shd;aul lrkq,efí'
WodyrK 2(
price=float(input(“Enter Price Rs: “))
qty=int(input(“Enter Quantity: “))
24
amount=price*qty
print “Amount is Rs: “, amount

fuu l%uf,aLh u.ska NdKavhl ñ, iy ñ, § .;a NdKav ixLHdj lshjd ,ndf.k ta i|ydf.úh hq;= uq¿ uqo, .Kkh
flf¾'
2' jrKh
fuys È f;dard .ekSu i|yd úl,am m%ldYk iuQyhla we;s úg fok ,o fldkafoaishla mÍlaId lrtla úl,amhla muKla
f;dard .ekSu isÿfõ'
a). ir, jrKh
ldrl Í;sh
if expression:
statement 1
statement 2
else: statement 1
statement 2

WodyrK 3(
a=int(input(“Enter a Number: “))
if a%2==0:
print “Even number”

by; WodyrKfha § ixLHdjla ,ndf.k th 2ka fn¥ úg b;=rejk w.h 0 kï th brÜfÜ ixLHdjla hehs m%;sodkh
flf¾'
WodyrK 4(
a=int(input(“Enter a number: “))
if a%2==0:
print “Even number”
else:
print “Odd number”

fuu WodyrKfha § ixLHdjla ,ndf.k th 2ka fn¥ úg b;=rejk w.h 0 kï print '''Even number'hk m%ldYkh o
tfia fkdue;skï print "Odd number"hk m%ldYkh l%shd;aul flf¾'
:.
b). nyq jrKh

13
ldrl Í;sh
if expression 1:
statement 1
statement 2
elif expression 2:
statement 1
statement 2
else:
statement 1
statement 2
WodyrK 5(
price=int(input(“Enter Price Rs: “))
if price>1000:
discount=price*10/100
elif price>=500:
discount=price*5/100
else:
discount=price*2/100
net_price=price-discount
print “Net Price is Rs: “, net_price

fuu WodyrKh u.ska NdKavhl ñ, ,ndf.k ta i|yd ysñjk jÜgu .Kkh flf¾' NdKavfha ñ, re' 1000'00 jeä kï
10] jÜgula o tys ñ, 500 isg 1000 olajd kï 5]l jÜgula o tfia fkdue;s tajd i|yd 2] jÜgula o ysñfõ'
WodyrK 6(
num1=int(input(“Enter first number: “))
num2=int(input(“Enter second number: “))
print “1. Add”
print “2. Subtract”
print “3. Multiply”
:.
:.
:.
print “4. Divide”
choice=int(input(“Enter Choice: “))
if choice==1:
print num1, “+” , num2, “=”, num1+num2
elif choice==2:
print num1, “-” , num2, “=”, num1-num2
elif choice==3:
print num1, “*” , num2, “=”,num1*num2
elif choice==4:
print num1, “/” , num2, “=”,num1/num2
else:
print “Invalid Entry!”

fuu WodyrKh ixLHd folla ,ndf.k th fukqjlska f;dard.;a .Ks; l¾uhg wod< m%;sM,h
m%;sodkh lrhs'
3' mqk¾lrKh
j.ka;s tlla fyda lsysmhla kej; kej; l%shd;aul lsÍu mqk¾lrKh f,i ye¢kafõ'
a) for m%ldYkh
j.ka;s tlla fyda jeä.Kkla fyda hï ksYaÑ; jdr .Kkla mqk¾lrKh lsÍu i|yd fuu m%ldYkh Ndú; flf¾' fuh
fhdod.; yelafla wjia:d foll § muKs'
i) hï ixLHd mrdihla ;=< mqk¾lrKh isÿ lsÍu'
ldrl Í;s
for var-name in range (start-num,stop-num)
ii) o;a; ,ehsia;=jla iu. Ndú; lsÍu'
ldrl Í;s
14
for list-item in list
statement(s)
WodyrK 7(
for num in range(1, 5):
print (num)

fuu WodyrKh 1 isg 4 olajd ixLHd m%;sodkh lrhs' fuu WodyrKfha we;s range hkak u.ska ,ndfok ,o wdrïNl
w.h jk 1 isg wjika w.h jk 5 olajd ixLHd iuQyhla ckkh lrkq ,efí' ^fuys wjika w.h jk 5 we;=<;a fkdfõ'&

WodyrK 8(
numbers=[10,30,40,60,50]
for num in numbers:
print (num)

by; WodyrKh for m%ldYkh o;a; ,ehsia;=jla iu. Ndú; flf¾' fuys § uq, § ixLHd,ehsia;=j fhdod .kq ,efí'
WodyrK 9(
for letter in “Computer”:
print (letter)

b) while m%ldYkh
fuu m%ldYkh i|yd ,nd fok fldkafoaishla i;Hj mj;sk f;la mqk¾lrKh isÿfõ'
WodyrK 10(
num = int (input ('''Enter Number'))
while num>0:
if num%2==0:
count + = 1
num = int (input ('''Enter Number'))
print "Total Even numbers", count

by; WodyrKfha § uq,ska u ,nd .kakd ixLHdj Ok ixLHdjla kï num>0 fldkafoaish i;Hfõ' tfia kï while
m%ldYkh ;=<g meñfKa' tys § tu ixLHdj brÜfÜ ixLHdjla oehs mÍlaIdflf¾' tfia kï count ys w.h tllska jeä
flf¾' bkamiq kej; ixLHdjla ,nd .efka' ,nd§ we;s fldkafoaish (num>0) wi;H jk ;dla mqk¾lrKh isÿflf¾'
,ndÿka uq¿ brÜfÜ ixLHd.Kk fuu l%uf,aLh u.ska m%;sodkh flf¾'

break uq,jok
for Æmh fyda while Æmhl l,ska bj;a ùu i|yd break hkak Ndú; flf¾'

WodyrK 11(
i=I
while 1<10:
print i
if i==5:
print "stoping the loop"
break
i+=1
by; WodyrKh u.ska 1 isg 5 olajd ixLHd m%;sodkh flf¾' i i|yd wdfoaY lr we;s w.h 1 neúka while m%ldYkfha
fldkafoaish i<10 i;H fõ' túg Æmh ;=<g meñK i ys w.h m%;sodkh flf¾' bkamiq if m%ldYkh u.ska i ys w.h 5 g
iudkoehs mÍlaId flf¾' hï wjia:djl i ys w.h 5 iudk jk úg "stopping the loop" hkqfjka m%;sodkh lr break
m%ldYkh u.ska while Æmfhka bj;a fõ'

Continue
WodyrKh 12(
while True:
name = input ("Enter a name less than four charactors or "quit" to stop")
if name=="quit":
break
if len (name)>5:
continue
else:
print name
15
x = 2
Python : Functions print('Changed local x to', x)

Functions func(x)
python ත මාණය සදහා def යන keyword print('x is still', x)
එකඋපෙය කර ග . Output:
$ python3 func_local.py
Example (save as function1.py): x is 50
def sayHello(): Changed local x to 2
print('Hello World!') # block x is still 50
belonging to the function
# End of function # Using The global Statement
බා ඇ variable සදහා තය ල global
sayHello() # call the function කාශනය ලබා ට තය ල බා ර variable
sayHello() # call the function again සදහා බලපෑම ඇ කළ හැක.
Output: Example (save as func_global.py):
$ python3 function1.py
x = 50
Hello World!
Hello World!
def func():
global x
Function Parameters
print('x is', x)
තය ල අ ත ගතය parameters ෙලස x = 2
හ ව . print('Changed global x to', x)
Example (save as func_param.py):
func()
def printMax(a, b): print('Value of x is', x)
if a > b: Output:
print(a, 'is maximum') $ python3 func_global.py
elif a == b: x is 50
print(a, 'is equal to', b) Changed global x to 2
else: Value of x is 2
print(b, 'is maximum')
Default Argument Values
printMax(3, 4) # directly give literal ෙමම parameters සදහා ක අගය ලබා ය
values හැක. එ ට එම parameter එක සදහ අගය
ට ඇ අගය default අගය ෙලස ලබා ග .
x = 5
y = 7
Example (save as func_default.py):
def say(message, times = 1):
print(message * times)
printMax(x, y) # give variables as
arguments
say('Hello')
Output: say('World', 5)
$ python3 func_param.py
4 is maximum
Output:
$ python3 func_default.py
7 is maximum
Hello
WorldWorldWorldWorldWorld
Keyword Arguments
Local Variables Example (save as func_key.py):
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and
තයට බා ඇ variable අගය හට තය c is', c)
ල එම න ම ලබා ෙදන variable ව
බලපෑම ෙනාෙ func(3, 7)
func(25, c=24)
func(c=50, a=100)
Example (save as func_local.py):
x = 50 Output:
$ python3 func_key.py
def func(x): a is 3 and b is 7 and c is 10
print('x is', x) a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

16
VarArgs parameters x = int(x) # convert to integers, if
possible
y = int(y)
def total(initial=5, *numbers,
**keywords): if x > y:
count = initial print(x, 'is maximum')
for number in numbers: else:
count += number print(y, 'is maximum')
for key in keywords:
count += keywords[key] printMax(3, 5)
return count print(printMax.__doc__)
Output:
print(total(10, 1, 2, 3, vegetables=50, $ python3 func_doc.py
fruits=100)) 5 is maximum
Output: Prints the maximum of two numbers.
$ python3 total.py
166 The two values must be integers.
Keyword-only Parameters
def total(initial=5, *numbers,
extra_number):
count = initial
for number in numbers:
count += number
count += extra_number
print(count)

total(10, 1, 2, 3, extra_number=50)
total(10, 1, 2, 3)
# Raises error because we have not
supplied a default argument value for
'extra_number' #
Output:
$ python3 keyword_only.py
66
Traceback (most recent call last):
File "keyword_only.py", line 12, in
<module>
total(10, 1, 2, 3)
TypeError: total() needs keyword-only
argument extra_number
The return Statement
Example (save as func_return.py):
def maximum(x, y):
if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
return y

print(maximum(2, 3))
Output:
$ python3 func_return.py
3
DocStrings
Example (save as func_doc.py):
def printMax(x, y):
'''Prints the maximum of two numbers.

The two values must be integers.'''

17
Python Reading Files
Opening a File in Python
test.txt
I am a test file.
Maybe someday, he will promote me to a real file.
Man, I long to be a real file
and hang out with all my new real file friends.
Example
f = open("test.txt", "r") #opens file with name of "test.txt"

Python File Reading Methods

 file.read(n) - This method reads n number of characters from the file, or if n is blank it reads the entire file.
 file.readline(n) - This method reads an entire line from the text file.
Example
f = open("test.txt","r") #opens file with name of "test.txt"
print(f.read(1))
print(f.read())
Result I
am a test file.
Maybe someday, he will promote me to a real file.
Man, I long to be a real file
and hang out with all my new real file friends.
Example
f = open("test.txt","r") #opens file with name of "test.txt"
print(f.readline())
print(f.readline())
Result
I am a test file.
Maybe someday, he will promote me to a real file.
Example
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
myList.append(line)
print(myList)
Result
['I am a test file.\n', 'Maybe someday, he will promote me to a real file.\n', 'Man, I long to be a real file\n',
'and hang out with all my new real file friends.']

Don't forget to close the file!


Example
f = open("test.txt","r") #opens file with name of "test.txt"
print(f.read(1))

18
print(f.read())
f.close()

Python Writing to Files


Example
f = open("test.txt","w") #opens file with name of "test.txt"
f.write("I am a test file.")
f.write("Maybe someday, he will promote me to a real file.")
f.write("Man, I long to be a real file")
f.write("and hang out with all my new real file friends.")
f.close()

Writing Lines to a File


Example
f.write("Maybe someday, he will promote me to a real file.\n")

Appending to a File
Example
f = open("test.txt","a") #opens file with name of "test.txt"
f.write("and can I get some pickles on that")
f.close()

19
WHILE TRUE EXAMPLE
True
invalid = True
while invalid:
number = int(input("Please enter a number in the range 10 to 20: "))
if number >= 10 and number <= 20:
invalid = False
else:
print("Sorry number must be between 10 and 20")
print("Please try again")
print("You entered {0}".format(number))
print("This is a valid number")
1) import random 2) n,t=0,0
# A while-true loop. while(True):
while True: n=int(input("Enter number"))
n = random.randint(0, 100) if n!=0:
print(n) t+=n
# Break on even random number. else:
if n % 2 == 0: break
break print(t)

Split EXAMPLE -Python has a very neat function for breaking up strings into
smaller strings. The split function splits a single string into a string array
using the separator defined. If no separator is defined, whitespace is used.

Let's look at some examples: w=s.split(",")


x = 'blue,red,green' for word in w:
x.split(",")
a=a+word.count(",")
['blue', 'red', 'green'] print(a)
>>>
>>> a,b,c = x.split(",")
>>> a
'blue'
>>> b
'red'
>>> c
'green'

Let's show one more example.


>>> word = "This is some random
text"
>>> words2 = word.split(" ")
>>> words2
['This', 'is', 'some', 'random',
'text']
a=0
s="hello world"

20
Python: Difference between print and return
Posted by Ed on December 9, 2011

When I began programming I was confused by the difference between print and return. Here, I
want shed some light on the difference.

Consider the following code:

1def square1(x):
2 print(x*x)
3
4def square2(x):
return x*x
5

Save the code in a file square.py and execute the file, e.g. in IDLE press F5.
Then, type the following in the Python-Shell:

1>>> square1(5)
225
3>>> square2(5)
425

In line 1 we have called the function square1() and passed the value 5 to it. As a result the
Python-Shell printed 25.
In line 3 we have called the function square2() and passed the value 5 to it. Here, the Python-
Shell also printed 25.

What is the difference?


In both cases we seem to get the same result. But while square1() only prints the square,
square2() returns it. The difference becomes obvious if we try to save the squared value:

Consider square2():

1>>> r2 = square2(5)
2>>> r2
325
4>>> print(r2)
525
>>> type(r2)
6<class 'int'>
7

– In line 1 we call square2(5) and assign the returned value to r2.


– In line 2 and 5 we both check the value that is stored in r2.
– In line 6 we check the type of the variable r2.
We have been successful with storing the square number in r2.

21
Consider square1():

1>>> r1 = square1(5)
225
3>>> r1
4>>> print(r1)
5None
>>> type(r1)
6<class 'NoneType'>
7

– In line 1 we call square1(5) and try to assign a value to r1.


– In line 2 we note that the value 25 is printed, which is exactly what the function should do.
– In line 3 we try to check what is stored in r1. We note that nothing happens!
– In line 4 we try to check again what is stored in r1. This time the Python-Shell responds with
‘None’.
– In line 6 we check the type of r1 whereupon the Python-Shell tells us r1 is a ‘NonType’.
This shows that we cannot use square1() to save the squared result in a variable.
[Hint: For those who know Java or C++, None corresponds to null]

The confusion with print and return comes from the behavior of the Python-Shell. When we call
a function that returns a value, e.g. the square number, the function also prints it.

22

You might also like