Professional Documents
Culture Documents
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.
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
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.
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 ෙයාදා ගැ ම.
Python වල ද ත ව ග
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)
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
>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
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'])
>>>
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'
>>>
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.
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"
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.']
18
print(f.read())
f.close()
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.
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.
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.
Consider square2():
1>>> r2 = square2(5)
2>>> r2
325
4>>> print(r2)
525
>>> type(r2)
6<class 'int'>
7
21
Consider square1():
1>>> r1 = square1(5)
225
3>>> r1
4>>> print(r1)
5None
>>> type(r1)
6<class 'NoneType'>
7
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