0% found this document useful (0 votes)
4 views48 pages

Python Lab

Python is a versatile, high-level programming language known for its simplicity and readability, making it suitable for various applications such as web development and data science. The document covers Python's syntax, basic data types, operators, control flow statements, and functions, providing examples and explanations of each concept. It highlights Python's features like dynamic typing, automatic memory management, and its open-source nature.

Uploaded by

selinagirmay46
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views48 pages

Python Lab

Python is a versatile, high-level programming language known for its simplicity and readability, making it suitable for various applications such as web development and data science. The document covers Python's syntax, basic data types, operators, control flow statements, and functions, providing examples and explanations of each concept. It highlights Python's features like dynamic typing, automatic memory management, and its open-source nature.

Uploaded by

selinagirmay46
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 48

PYTHON PROGRAMMING LANGUAGE

 Define Python
 Python syntax
 Basic Data types
 Basic Statements
 Compound data types
 Functions

G/meskel N. (MSc CS)


About Python
• Python is a general- purpose programming
language that is used for a wide variety of tasks,
including
 Web development,
 Software development
 Machine learning,
 Data science, and scripting
Sample python code
# This program adds two numbers provided by the user

# Store input numbers


num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

# Add two numbers


sum = float(num1) + float(num2)

# Display the sum


print('The sum=‘, sum)
What is python?
 Python is an Interpreter programming language with
powerful typing and object oriented features.
– Great for text processing.
– Useful built-in types (lists, dictionaries).
– It's easy to learn: Structure and syntax are pretty intuitive and
easy to grasp
 python is
– Object oriented language
– Support dynamic data type
– Independent from platforms
– Simple and easy grammar
– High-level internal object data types
– Automatic memory management
 It’s free (open source)!
– Downloading and installing Python is free and easy
Look at a sample of code…
# Python Program to find the area of rentangle
# two sides of the rentangle a and b are provided by the user

a = float(input('Enter first side: '))


b = float(input('Enter second side: '))
# calculate the area
area = a * b
print('The area of the rentangle is', area)
output
Enter first side: 4
Enter second side: 2
The area of the rentangle is 8.0
Python syntax:
 Key Syntax Rules:
 No semicolons needed at line endings
 Case sensitive
 Variables don't need declaration
 Single Comments start with #
 Multiple Comments start with ’”kkkkkkkkkkkkkkkkk”’
 print() is a function that outputs text to the console
 Text strings are enclosed in quotes (single or double)
Python syntax: Variables
• No type declarations, just assigned! >>> x = 7
– Variable types don’t need to be >>> x
declared. Python figures out the 7
variable types on its own. >>> x = 'hello'
– The variable is created the first time you >>> x
assign it a value 'hello’

• Once a variable is assigned string, it only accepts values


with string type.
• So, you can’t just append an integer to a string. You
must first convert the integer to a string itself.
x = “the answer is ” # Decides x is string.
y = 23 # Decides y is integer.
print x + y # Python will complain about
this.
Python syntax: Operators
• Arithmetic operators
– For arithmetic operations the usual symbols are used (such as
+, -, *, /, %).
• Special use of + for string concatenation.
• Special use of % for string, integer and float formatting.

• Logical operators
– For Logical comparison the following words are used (such as
and, or, not)
– not symbols (&&, ||, !).

• Other operators:
– Assignment operators is = (e.g. x=8)
– comparison uses == if x == 8:
sum += x
Python syntax
• Naming Rules
– Names are case sensitive and cannot start with a number.
They can contain letters, numbers, and underscores.
bob Bob _bob _2_bob_ bob_2 BoB
– There are some reserved words:
and, assert, break, class, continue,
def, del, elif, else, except, exec,
finally, for, from, global, if,
import, in, is, lambda, not, or,
pass, print, raise, return, try,
while

• The basic output printing command is “print.”


– Basic input command: raw_input()
Output: The print Statement
• You can print a string to the screen using
>>> print ('hello‘)
print.
• Elements separated by commas print with a hello
space between them >>> print ('hello',’there'
• A comma at the end of the statement (print ) hello there
‘hello’,) will not print a newline character
• Format the output text using the % string operator in combination
with the print command.note: %s-for string and %d-for digit
(<formatted string> % <elements to insert>)
>>> print (“%s xyz %d” % (“abc”, 34))
abc xyz 34
• “Print” automatically adds a newline to the end of the string. If you
include a list of strings, it will concatenate them with a space
between them.
>>> print (“abc”) >>> print “abc”, “def”
abc abc def
Input
• The raw_input(string) method returns a line of us er input as a
string
– The parameter is used as a prompt
• The string can be converted by using the conversion methods:
– int(string), float(int), etc.
print ("What's your name?“)
name = raw_input("> ")
print ("What year were you born?”)
birthyear = int(raw_input("> "))
print (“%s is %d years old!" % (name, 2011 - birthyear))
~: python input.py
What's your name?
>Belew
What year were you born?
>1990
Belew is 21 years old!
Starting and exiting python
• Python scripts can be written in text files with the suffix .py. The
scripts can be read into the interpreter in several ways:
• Examples:
• To execute the script and return to the terminal afterwards
$ python script.py
• To keep the interpreter open after the script is finished
running use -i flag
$ python -i script.py

• To execute the file from the command line use execfile


command: it reads in scripts and executes them immediately,
as though they had been typed into the interpreter directly
$ python
>>> execfile('script.py')
Basic Data types: Types of Numbers
Python supports several different numeric types
• Integers (default for numbers)
Examples: 0, 1, 1234, -56
Note: dividing an integer by another integer will return only the
integer part of the quotient,
e.g. z = 5 / 2 # Answer is 2, integer division.

• Floating point numbers


Examples: 0., 1.0, 3.456, 1e10, 3.14e-2, 6.99E4
Division works normally for floating point numbers:
x = 7./2. = 3.5
Operations involving both floats and integers will yield floats:
y = 6.4 – 2 = 4.4
Basic Data types: Operations on Numbers
• Basic algebraic operations
arithmetic operations (like C/C++): a+b, a-b, a*b, a/b, a%b
Exponentiation: a**b

Comparison operators
– Greater than, less than, etc.: a < b, a > b, a <= b, a >= b
– Identity tests: a == b, a != b

To add or subtract: +=, -= etc… (no ++ or --) sum += x

Assignment using = (but it has different semantics!)


a=1
a = "foo" # OK
You can also assign to multiple names at the same time.
>>> x, y = 2, 3
Basic Data types: Strings
• characters are strings of length 1
– There is no char type like in C++ or Java
• Strings are ordered blocks of text
Strings are enclosed in single or double quotation marks
E.g.: 'abc', “abc” (they have the same meaning)
Use triple double-quotes for multiple line strings or strings that
contain both ‘ and “ inside of them:
>>> 'I am a string'
'I am a string'
>>> "So am I!"
'So am I!'
>>> """And me too!
... though I am much longer
... than the others :)"""
'And me too!\nthough I am much longer\nthan the others :)'
Basic Data types: Operations on Strings
• Concatenation and repetition >>> 'abc'+'def'
Strings are concatenated with the + sign: 'abcdef'

Strings are repeated with the * sign: >>> 'abc'*3


'abcabcabc‘
• Methods
• Len(‘string’) – returns the number of >>> len(‘abcdef’)
characters in the String 6
• str(Object) – returns a String
>>> str(10.3)
representation of the Object '10.3'
• ‘string’.upper() - string operations to
perform some formatting operations on
>>> “hello”.upper()
strings: ‘HELLO’
Substrings
• Python starts indexing at 0. A string s will have indexes
running from 0 to len(s)-1 (where len(s) is the length of s) in
integer quantities.
s[i] fetches the ith element in s >>> s = 'string'
>>> s[1]
s[i:j] fetches elements i (inclusive) through j 't'
(not inclusive)
>>> s[1:4]
s[:j] fetches all elements up to (not including) j 'tri'

s[i:] fetches all elements from i onward, inclusive >>> s[:3]


‘str'
s[i:j:k] extracts every kth element starting with
index i (inlcusive) and ending with index j (not >>> s[2:]
inclusive) ‘ring'
>>> s[0:5:2]
‘srn'
Basic Statements: The If Statement
• If statements have the following basic structure:
# inside a script
if condition:
action
• Notes: No Braces???
› blocks delimited by indentation! Python uses indentation
instead of braces to determine the scope of expressions
› All lines must be indented the same amount to be part of the
scope (or indented more if part of an inner scope). This forces
the programmer to use proper indentation since the indenting
is part of the program!
› A statement typed into an interpreter ends once an empty
line is entered, and a statement in a script ends once an
unindented line appears. The same is true for defining
functions.
› colon (:) used at end of lines containing control flow keywords
(such as if, elif, else, while, …)
Basic Statements: If Statements
• if, if/else, if/elif/else
• If statements can be combined with else if (elif) and else
statements as follows:
if condition1: # if condition1 is true, execute action1
action1
elif condition2: # if condition1 is not true, but condition2 is, execute
action2 # action2
else: # if neither condition1 nor condition2 is true, execute
action3 # action3

• Example:
if a == 0:
print ("zero!”)
elif a < 0:
print ("negative!”)
else:
print ("positive!”)
Basic Statements: If Statement
• Conditions in if statements may be combined using and & or
statements
if condition1 and condition2:
action1
# if both condition1 and condition2 are true, execute action1
if condition1 or condition2:
action2
# if either condition1 or condition2 is true, execute action2
• Conditions may be expressed using the following operations:
<, <=, >, >=, ==, !=, in
x = 2; y = 3; L = [0,1,2]
if(1<x<=3 and 4>y>=2) or (x==y) or 1 in L:
print 'Hello world'
#Hello world
Basic Statements: The While Statement
• While statements have the following basic structure:
# inside a script
while condition:
action
• As long as the condition is true, the while statement will
execute the action
• Example:
x = 1
while x < 4: # as long as x < 4...
print (x**2) # print the square of x
x = x+1 # increment x by +1
# only the squares of 1, 2, and 3 are printed, because
# once x = 4, the condition is false
Basic Statements: The While Statement
• Pitfall to avoid:
– While statements are intended to be used with changing
conditions. If the condition in a while statement does not
change, the program will be stuck in an infinite loop until the
user hits ctrl-C.
• Example:
x = 1
while x == 1:
print ('Hello world‘)

• Since x does not change, Python will continue to print “Hello


world” until interrupted
Control flow: Loops
 while loops  for loops
• Short way of writing the
a = 10 control flow of a code
while a > 0:
print (a) for a in range(10):
a -= 1 print a
• What is wrong with
this while loop?
Basic Statements: The For Statement
• For statements have the following basic structure:
for item i in set s:
action on item i
# item and set are not statements here; they are merely
# intended to clarify the relationships between i and s
• Example:
for i in range(1,7):
print (i, i**2, i**3, i**4)

1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
5 25 125 625
6 36 216 1296
Basic Statements: The For Statement
• The item i is often used to refer to an index in a list, tuple, or array
• Example:
L = [0,1,2,3] # or, equivalently, range(4)
for i in range(len(L)):
L[i] = L[i]**2
print (L)

• The value of L is updated to L = [0,1,4,9]

• Of course, we could accomplish this particular task more


compactly using arrays:
>>> L = range(4)
>>> L = L**2
>>> L
[0,1,4,9,]
Basic Statements: Combining Statements
• The user may combine statements in a myriad of ways

• Example:
L = [0,1,2,3] # or, equivalently, range(4)
for i in range(len(L)):
j = i/2.
if j – int(j) == 0.0:
L[i] = L[i]+1
else: L[i] = -i**2
print (L)
[1,-1,3,-9]
Loop Control Statements
break Jumps out of the closest
enclosing loop
continue Jumps to the top of the closest
enclosing loop like in C
pass Does nothing, empty statement
placeholder
a = [3, 1, 4, 1, 5, 9]
for i in range(len(a)):
if a == 0:
pass # do nothing
else:
print (a[i]) # whatever
Sequences
• Sequence represents ordered set of objects
indexed by nonnegative integers
– It includes strings, lists and tuples.
• Strings are sequences of characters.
– Lists and Tuple are sequences of arbitrary python
object such as numbers, strings, and/or nested
sublists.
• Lists are mutable and allow insertion, deletion and
substitution of elements.
– Strings
>>> and tuples>>>
L = [0,2,3] are simmutable
= 'string'
>>> L[0] = 1 >>> s[3] = 'o'
>>> L Traceback (most recent call last):
[1,2,3] File "<stdin>", line 1, in ?
TypeError: object does not support
item assignment
Compound data types: Lists
• Lists are ordered collection of data, contained in square
brackets []
• Lists can contain data of different types:
– Numbers: L1 = [0,1,2,3]
– Strings: L2 = ['zero', 'one']
– Nested sublists: L3 = [0,1,[2,3],'three',
['four,one']]
– Nothing/empty: L4 = []
• Lists are mutable: individual elements can be reassigned
in place. Moreover, they can grow and shrink in place.
– Example: >>> L1 = [0,1,2,3]
>>> L1 = [0,1,2,3] >>> L1.append(4)
>>> L1[0] = 4 >>> L1
>>> L1 [0, 1, 2, 3, 4]
[4, 1, 2, 3]
• Same subset operations is also possible as Strings
Operations on Lists
Index and slice assignment:
Indexing: L1[i], L2[i][j] >>> x = [1,2,3]
Slicing: L3[i:j] >>> y = x
> L2 = [1,4,5,2,3] >>> x[1] = 15
> L1[i] = 1 # reassigns value 1 the 4th element >>> x
> L2[1:4] = [4,5,2]
[1, 15, 3]
Concatenation: >>> y
>>> L1 = [0,1,2]; L2 = [3,4,5] [1, 15, 3]
>>> L1+L2
[0,1,2,3,4,5] >>> x = x + [9,10]
Repetition: >>> x
>>> L1*3 [1, 2, 3, 12, 9, 10]
[0,1,2,0,1,2,0,1,2]
Built-in Functions on Lists
Sorting: sorts items of L3 in place
>>> L3 = [2,1,4,3]
>>> L3.sort()
[1,2,3,4]
Reversal: reverse items of L4 in place
>>> L4 = [4,3,2,1]
>>> L4.reverse()
>>> L4
[1,2,3,4]
Shrinking:
>>> del L4[2] #delete value at index 2
>>> L4[i:j] = [] #delete values from index i to j with empty

• Appending: >>> x = [1,2,3]


>>> x.append(12)
>>> L1.append(3) >>> x
[0,1,2,3] [1, 2, 3, 12]
Compound data types: Tuples
Tuples are contained in parentheses ()
Tuples can contain
• Numbers: t1 = (0,1,2,3)
• Strings: t2 = ('zero', 'one‘)
• Nested sub-tuples: t3=(0,1,(2,3),'two',(‘six,one'))
• Nothing: t4 = ()
As long as you're not nesting tuples, you can omit the
parentheses
• Example: t1 = 0,1,2,3 is the same as t1 = (0,1,2,3)
Tuples are immutable: individual elements cannot be reassigned
in place.
>>> L = (0,2,3)
>>> L[0] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object does not support item assignment
Operations on Tuples: basic
operations
Tuple indexing works just like string and list indexing
 Indexing: L1[i]
Concatenation:
>>> t1 = (0,1,2,3); t2 = (4,5,6)
>>> t1+t2
(0,1,2,3,4,5,6)

Repetition:
>>> t1*2
(0,1,2,3,0,1,2,3)

Length: (this also works for lists and strings)


len(t1)
Sequence Operations
• There are various built-in functions for sequences operation
Operation Result Notes
returns True if an item The x in S operator checks whether
Membership testing
of s is equal to x, else object x equals any item in the
(x in s)
False sequence S
Concatenation the concatenation of s the + operator concatenate sequences
(s + t) and t of the same type
Repetition n copies of s the * operator multiply a sequence S
(s * n , n * s) concatenated by an integer n
Indexing (s[i]) ith item of s,
Slicing (s[i:j]) slice of s from i to j
slice of s from i to j
Slicing (s[i:j:k])
with step k
returns the number of items in the
len function (len(s)) length of s
container.
Min function (min(s)) smallest item of s return the smallest items
max function( max(s)) largest item of s return the largest items
Functions
• Functions are objects and treated
like any other variable in python, def f1(x):
return x*(x-1)
the def statement simply assigns a
>>> f1(3)
function to a variable 6
• Usually, function definitions have
the following basic structure:
def funcName(args):
def maths(x):
return values y = 10 * x + 2
return y
• Regardless of the arguments,
(including the case of no Arguments passed by value
arguments) a function call must
end with parentheses.
Functions: Multiple Input and/or Output
• Functions may contain multiple
def f2(x,y):
input and/or output variables return x+y,x-y
and also can take multiple types >>> f2(3,2)
(integer, tuples, …) as input (5,1)
and/or outputs
def foo(x = 3) :
• Parameters: Defaults print x
– Can assign default values to
parameters >>> foo()
– They are overridden if a 3
parameter is given for them >>> foo(10)
10
– The type of the default doesn’t
>>> foo('hello')
limit the type of a parameter
hello
Functions: Variables are Local
• All variables are local unless specified as global
Anything calculated inside a function but not specified
as an output quantity (either with return or global)
will be deleted once the function stops running
def f5(x,y):
a = x+y
b = x-y
return a**2,b**2

>>> f5(3,2)
(25,1)
• If we try to call a or b, we get an error message:
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'a' is not defined
Functions: As Parameters
• The function doo takes two
def doo(f, a) :
parameters and applies the first as return f(a)
a function with the second as its
def f(x) :
parameter
retun x * x
>>> doo(bar, 3)
• Since they are like any other
9
object, you can have functions
inside functions def doo (x,y) :
def bar (z) :
return z * 2
• One Function can return the other return bar(x) + y
function >>> doo(2,3)
7
Files: Input & Output
input = open(‘data’, ‘r’) Open the file for input
S = input.read() Read whole file into one String
S = input.read(N) Reads N bytes (N >= 1)
L = input.readline() Returns a list of line strings
input.close() Close opened file for reading

output = open(‘data’, ‘w’) Open the file for writing


output.write(S) Writes the string S to file
output.writeline(L) Writes each of the lines in list L to
file
output.close() Close opened file for writing
File: open and read
• while loop expression for file reading:
f = open(filename, "r")
line = f.readline()
while line: # do something with line
print line
line = f.readline()
f.close()
• open() and file()are identical:
f = open(filename, "r")
f = file(filename, "r")

• Instead of using while loop to iterate through file, more


concisely one can write with for loop:
for line in file(filename, "r“):
print line
Importing modules
• Import to access other codes
– Such as: import sys, import string, import
math, import random
• Math functions: Many math functions in the math
module
>>> import math
>>> dir(math)
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2',
'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod',
'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow',
'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
>>>
How to Import modules?
import Brings all elements of import
mymodule mymodule in, but must refer math
to as mymodule.<elem>
from mymodule Imports x from mymodule from math
import x right into this namespace import
sqrt
from mymodule Imports all elements of from math
import * mymodule into this import *
namespace
Can import multiple modules on one line:
import sys, string, math
For example:
import math
print math.sqrt(20)
Exercises
• Count the number of vowels in the string : “Sena sold strong cups.”
• Create a function that will read in a string and give you the character
frequency count (14 E’s, 12 T’s, 8 A’s, etc.)
• Create a function that will test to see if a string is palindromic (e.g.,
“Racecar” spelled backwards is “racecar”).
• Write a program that asks the user about textbook prices & reports
how overpriced the textbooks are.
– Your program should ask users: How much do they want to pay for each textbook,
How much did the average textbook actually cost & how many books did you buy?
– It displays whether each book is overpriced or not; by how much
• Write a program that asks for information about a loan & prints the
monthly payment.
– your program accepts Loan amount, Number of years, & Interest rate. Then
output payment amount.
• Write a program that determines the given number is prime or not.
– Hint: To count the factors of some integer n, use a loop that tests every integer
less than n to see whether n is divisible by it. (How do you know whether one
integer is divisible by another?)
Exercise
Write a Python program to process grades. An example run:
• Enter the type of grade: lab, exam, or ‘e’ to end program: lab
– Enter the 3 lab grades: 50,60,70
• Enter the type of grade: lab, exam or ‘e’ to end program: exam
– Enter the 2 exam grades: 70,60
• Enter the type of grade: lab, exam, or ‘e’ to end program: wrong
– Invalid type of grade
• Enter the type of grade: lab, exam, or ‘e’ to end program: end
• Compute Lab average: 60.0
– Compute Exam average: 65.0
– Compute Class average: 60.0 PASSED
• Instructions: Your program has a main function that provides options to
process lab and exam mark.
– It has two functions that compute labaverage & examaverage. These
functions ask the user for the grades for that type, calculates the average &
returns it to main. After the user enters “end”, the main function prints the
grades as “PASSED” or “FAILED”.
– For the class average, add lab & exam marks and convert to 100%. If the class
average is >= 60.0 it displays “PASSED”. If it is < 60.0, it prints “FAILED”.
Exercise
• Write a program which accepts a list L from users and returns the
most frequent one or more items in L. There may only be one
most frequent item in L, or there may be more than one most
frequent item. For example;
– what is the most frequent item in the list ‘( a b c a a d e a g)).
(a) # because a occurs 4 times in the list, more often than
any other item
– ( most_frequent ‘( a b c a b d e a g b) )
(a b) # because a and b both occur 3 times in the list,
more often than any other item
• Write a Python program that will read in a string and give you the
character frequency count (14 E’s, 12 T’s, 8 A’s, etc.)
Project
• Write python program that will read a text file (with at
least 10 lines) and perform the following tasks:
 Identify words in the text (Note: remove special characters
(like semicolon, comma, full stop, etc.) since they are not
part of meaningful words)
 Create a function that compute word frequency in the text
file and displays words in decreasing order of their
frequency.
 Create a function that compute character frequency in the
text file and displays the first five most frequently
occurring characters.
 Finally output statistical information such as total lines,
total words and total characters in the text file.
Useful Resources
Books:
David M Beazley, Python Essential Reference, (3rd ed.), Sams
publishing, 2006
Mark Lutz & David Ascher, Learning Python, O'Reilly Press, 1999
Mark Lutz, Programming Python, O'Reilly Press, 2006
Wesley J. Chun, Core Python Programming (2nd ed.), Prentice Hall,
2006
Websites:
http://docs.python.org – online Python Library Reference
http://laurent.pointal.org/python/pqrc - Python Quick Reference
http://rgruet.free.fr - long version of Python Quick Reference
http://mail.python.org - extensive Python forum
“Dive into Python” : http://diveintopython.org/
The Python Quick Reference; http://rgruet.free.fr/PQR2.3.html

You might also like