You are on page 1of 6

Python examples

1. count_words.py – Given a list of strings, return the count of the number of strings where the string
length is 2 or more

Example: count_words.py

def count_strings(words):
count = 0
for word in words:
if len(word) >= 2 :
count = count + 1
# you can also use count+=1
return count

l_words = ['aba', 'xyz', 'aa', 'x', 'bbb']


print "List:", l_words

cnt = count_strings(l_words)
print "Found", cnt, "strings with length higher than 2"

Running example:
$ ./count_words.py
List: ['aba', 'xyz', 'aa', 'x', 'bbb']
Found 4 strings with length higher than 2

Exercise: Modify the script to count and print the elements of the list that have the same first and
last chars.
E.g. The exercise will print

$ ./count_words_solution.py
List: ['aba', 'xyz', 'aa', 'x', 'bbb']
aba
aa
bbb
Found 3 strings with length higher than 2

2. sum.py – Script for calculating the sum of 2 numbers given as parameters:

Example: add.py 3 5

#!/usr/bin/python

import sys

if (len(sys.argv) < 2 or len(sys.argv) > 3):


print "Usage:\n You should use the following syntax: add value1 value2"
sys.exit("Not enough paraments!!!")
else:
#the arguments that the script uses: add value1 value2
# sys.argv[0] represents program name
# the parameters need to be converted to int, as they are considered string
value1 = int(sys.argv[1])
value2 = int(sys.argv[2])

#the procedure returns the sum of 2 numbers given as parameters


def sum (a,b):
print "Add value1=",value1," with value2=",value2
result = a + b
return result

#calling the procedure


sum_value=sum(value1,value2)

print "Sum is:",sum_value

Exercise: Modify the script to calculate the sum of all numbers given as parameters (not just for 2
numbers)

3. mix_words.py - Given strings a and b, return a single string with a and b separated by a space '<a>
<b>', except swap the first 2 chars of each string.
Assume a and b are length 2 or more.

Example: mix_words.py

def mix_words(a, b):


# concat first two characters from b with characters from 2 to end from a
a_swapped = b[:2] + a[2:]
b_swapped = a[:2] + b[2:]
# create string using swapped a, b and space
return a_swapped + ' ' + b_swapped

val1 = "test"
val2 = "mix"
print 'Words to mix up:',val1,’,’,val2

# call mix_words procedure


mixed_string = mix_words(val1,val2)

print 'Mixed word:', mixed_string

Running example:
$ python mix_words.py
Words to mix up: test , mix
Mixed word: mist tex

Exercise: Modify mix_words procedure to receive a dictionary as parameter. Mix up each key and
value pair of the dictionary as above( <key> <value>, swap first two chars ). Return a list that contain
all values. Print the list on the screen.
E.g The exercise will print
$ python mix_up_solution.py
Dictionary to mix up: {'mix': 'test', 'one': 'First'}
Returned list: ['tex mist', 'Fie onrst']
4. get_employee_name.py – Given a file as a parameter, extract the Name and Surname of each
employee. Write the resulted name and surname on another file.

Each line of the file has the following format:


Name: <name> Surname: <surname> Address: <address> Phone: <phone_number>

E.g. Name: Test Surname: Ana Address: Bucharest Phone: 0040122122

Example: ./get_employ_name.py employ_list.txt


#!/usr/bin/python
import sys
import re

# procedure that reads a file and returns the text


def read_file (filename):
# open file for reading
fid = open(filename,'r')
# read the entire text in variable text
text = fid.read()
# close file after reading
fid.close()

return text

# procedure that returns a tuple containing the name and surnames


# Each file line has format:
# Name: <name> Surname: <surname> Address: <address> Phone: <phone_number>
# Returns a tuple of this type: [(<name>,<surname>)]
def parse_text (txt):
tuples = re.findall(r'Name:\s*(\S+)\s+Surname:\s*(\S+)', txt)
return tuples

# procedure that writes in a file the Name and Surname


# File format:
# Name: <name> Surname: <surname>
def write_file (tuples):
fout = open("filtered_employ_list.txt","w")

for name_surname in tuples:


# unpack the tuple into 2 vars
(name,surname) = name_surname
# generate the string in the correct format
str_to_write = "Name: " + name + " Surname:" + surname + "\n"
# write the string in the file
fout.write(str_to_write)
fout.close()

def main():
if len(sys.argv) != 2:
print 'usage: ./get_employee_name.py file-to-read'
sys.exit(1)

file_text = read_file(sys.argv[1])
print file_text
filtered_text = parse_text(file_text)
print filtered_text
write_file(filtered_text)

if __name__ == '__main__':
main()

Exercise:
1) Modify read_file procedure to read the file line by line
2) Create read_file_list procedure that reads the file line by line and returns a list
3) Create parse_list procedure that parses the list returned by read_file_list
It will return Name, Surname and Phone only for employees that have “Address” field set to
“Bucharest”
E.g. Tuple format: [(<name>,<surname>,<phone>)]
4) Modify write_file procedure to print on the first line the number of employees with “Address” as
“Bucharest” and then the Name, Surname and Phone
E.g. The output file will have the following format:
Number of employees living in Bucharest:<number>
Name: <name> <surname> Phone: <phone_number>

5. employee_class.py - Script that creates Employee class and two methods

Example: ./employee_class.py

class Employee:
'Common base class for all employees'
# class variable that counts number of employees
empCount = 0

def __init__(self, name, salary):


# object attributes
self.name = name
self.salary = salary
# increase the employee count
Employee.empCount += 1

# method that displays the total number of employees


def displayCount(self):
print "Total Employee %d" % Employee.empCount

# displays information about an Employee


def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

#"This would create first object of Employee class"


emp1 = Employee("Emp1", 2000)
#"This would create second object of Employee class"
emp2 = Employee("Emp2", 5000)

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

Running example:
$ python employee_class.py
Name : Emp1 , Salary: 2000
Name : Emp2 , Salary: 5000
Total Employee 2

Exercise:
1) Create a class that will inherit Employee class – Manager class.
The class will have mCount variable the will count the number of Manager objects
The class constructor will have 3 arguments: name, salary and departments
2) In Manager class create displayEmployee method that displays the name
3) In Manager class create displayManager method that prints the departments he is assigned to
4) Create 2 Manager objects. Call displayEmployee for both manager objects.
5) Print the value of empCount from Employee and Manager

6. Script for creating a client/server application


server.py
#!/usr/bin/python # This is server.py file

import socket # Import socket module

s = socket.socket() # Create a socket object


host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port

s.listen(5) # Now wait for client connection.


while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection

client.py
#!/usr/bin/python # This is client.py file

import socket # Import socket module

s = socket.socket() # Create a socket object


host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done

Running the client and server:


# Following would start a server in background.
$ python server.py &

# Once server is started run client as follows:


$ python client.py

Exercise: Modify the script to send a message from client to the server and print it on the screen with
appropriate label
>> [client] Hi server!
>> [server] Welcome user!

You might also like