Thursday, June 6, 2024

Python hands-on self learning

Classroom training may not be sufficient to learn Python. You have to get your hands dirty. Here are some assignments that you could do, to learn Python the self-help way.

Exercise 1. In a Python script, accept command line arguments. Display all the arguments and also the number of arguments.


Expected output:

$ ex_01.py here there
arguments:
here
there
Number of arguments: 2
$

Exercise 2. Accept a filename as command line argument. Display the contents of that file.

Expected output:

$ cat > ringfile.txt
Three Rings for the Elven-kings under the sky,
Seven for the Dwarf-lords in their halls of stone,
Nine for Mortal Men doomed to die,
One for the Dark Lord on his dark throne
In the Land of Mordor where the Shadows lie.
One Ring to rule them all, One Ring to find them,
One Ring to bring them all and in the darkness bind them
In the Land of Mordor where the Shadows lie.
(Ctrl+D)$
$
$ ex_02.py ringfile.txt
Three Rings for the Elven-kings under the sky,
Seven for the Dwarf-lords in their halls of stone,
Nine for Mortal Men doomed to die,
One for the Dark Lord on his dark throne
In the Land of Mordor where the Shadows lie.
One Ring to rule them all, One Ring to find them,
One Ring to bring them all and in the darkness bind them
In the Land of Mordor where the Shadows lie.

$

This is similar to displaying the contents of a file using cat command.


Exercise 3. Accept a filename as command line argument. Display the contents of that file in the opposite order that they appear in the file.

Expected output:

$ ex_03.py ringfile.txt
In the Land of Mordor where the Shadows lie.
One Ring to bring them all and in the darkness bind them
One Ring to rule them all, One Ring to find them,
In the Land of Mordor where the Shadows lie.
One for the Dark Lord on his dark throne
Nine for Mortal Men doomed to die,
Seven for the Dwarf-lords in their halls of stone,
Three Rings for the Elven-kings under the sky,

$


Exercise 4. Accept a string as first argument and a filename as second argument. Display all lines of that file which contain the given string.

Expected output:

$ ex_04.py them ringfile.txt
One Ring to rule them all, One Ring to find them,
One Ring to bring them all and in the darkness bind them

$


Exercise 5. Accept a username as command line argument. Display if that user is currently logged in or not. Run who or w command and use its output to determine if the given user is logged in or not.

Expected output:

$ ex_05.py yogesh
yogesh is not logged in
$
$ ex_05.py root
root is logged in
$
$ ex_05.py roo
roo is not logged in

$


Exercise 6. Accept command line arguments. Consider all command line arguments as user names and for all the given user names, display if they are logged in or not.

Expected output:

$ ex_06.py yogesh pts roo root
yogesh is not logged in
pts is not logged in
roo is not logged in
root is logged in

$


Exercise 7. Display today's date in the format: 22-Aug-2008

Exercise 8. Display yesterday's date in the format: Thu Aug 21 16:58:10 2008

Exercise 8.1. Display tomorrow's date in the format: 21-Aug-2008


Exercise 9. Declare a list as follows:

nums = [5, 10, 15, 23, 20, 24, 30, 33, 40, 13]

Sort this list numerically in ascending order.

Exercise 9.1. Sort this list numerically in descending order.


Exercise 10. Declare a list as follows:

nums = [5, 10, 20, 23, 15, 23, 20, 5, 24, 30, 33, 40, 3, 13]

Find the duplicate elements from this list


Exercise 11. Declare a list as follows:

nums = [5, 10, 20, 23, 15, 23, 20, 5, 24, 30, 33, 40, 3, 13]

Find unique elements from this list


Exercise 12. Accept a string as command line argument. Declare a dictionary as follows:

food={'apple':'red', 'banana':'yellow', 'tomato':'red', 'spinach':'green', 'lemon':'yellow',}

Check whether the given string is present as a key in this dictionary.

Expected output:

$ ex_38.py apple
We've got apple
$
$ ex_38.py orange
We've got no orange

$


Exercise 13. Declare a dictionary as follows:

dict={d:12, b:20, g:2, a:6, e:1, h:13, c:8, f:5}

Display keys and values from this dictionary sorted by keys.

Expected output:

$ ex_13.py
key = a value = 6
key = b value = 20
key = c value = 8
key = d value = 12
key = e value = 1
key = f value = 5
key = g value = 2
key = h value = 13

$


Exercise 14. Declare a dictionary as follows:

dict={d:12, b:20, g:2, a:6, e:1, h:13, c:8, f:5}

Display keys and values from this dictionary numerically sorted by values.

Expected output:

$ ex_14.py
key = e value = 1
key = g value = 2
key = f value = 5
key = a value = 6
key = c value = 8
key = d value = 12
key = h value = 13
key = b value = 20

$


Exercise 15. Declare two dictionaries as follows:

food={'apple':'red', 'rice':'white', 'banana':'yellow', 'tomato':'red', 'spinach':'green'}

fruits={'plum':'red', 'banana':'yellow', 'blueberry':'blue', 'mulberry':'black', 'apple':'red', 'pear':'green'}

Find common keys in these dictionaries.

Expected output:

$ ex_15.py
apple
banana

$


Exercise 16. Declare two dictionaries as follows:

food={'apple':'red', 'rice':'white', 'banana':'yellow', 'tomato':'red', 'spinach':'green'}

fruits={'plum':'red', 'banana':'yellow', 'blueberry':'blue', 'mulberry':'black', 'apple':'red', 'pear':'green'}

Find keys that are present in dictionary %food and not present in dictionary %fruits.

Expected output:

$ ex_16.py
rice
tomato
spinach

$


Exercise 17. Write a program to read file /etc/passwd and prepare a dictionary as follows:

(a) keys of the dictionary would be the user names

(b) corresponding value would be the home directory of that user

Also, display contents of this dictionary.


Exercise 18. Write a program to read file /etc/passwd and prepare a dictionary as follows:

(a) keys of the dictionary would be the user names

(b) corresponding value would be another dictionary as follows:

i. key = uid value = user id of that user

ii. key = homedir value = home directory of that user

iii. key = shell value = default shell of that user

Also, display contents of this dictionary.


Exercise 19. Write a program to find and print the longest word in a text file.

Expected output:

$ python find_longest_word.py ringfile.txt
Elven-kings
Dwarf-lords

$


Exercise 20. Write a function that simulates the roll of a dice. That is, it generates a random number between 1 and 6.


Exercise 21. Accept a filename as command line argument. Display the word that occurs most in it. Also display the number of occurrences of that word.

Expected output:

$ python ex_21.py ringfile.txt
highest occurance: the (9)

$


Exercise 22. Accept a directory path as command line argument. In the given directory, find the file having oldest modification time. Display the file name along with how many days ago it was modified.

Expected output:

$ ex_22.py /foo/
/foo/ does not exist
$
$ ex_22.py /etc/passwd
/etc/passwd is not a directory
$
$ ex_22.py /etc/
motd was modified 167 days ago

$


Exercise 23. Write a python program to validate a PAN codes.

Get PAN codes to be validated on the command line. There could be more than one PAN codes provided.

$ ./pan_code_validator.py BETPK1234M

$ ./pan_code_validator.py CRLCT3456G H2YPJ5678L

Q. What is a PAN number?

A. Please see https://en.wikipedia.org/wiki/Permanent_account_number

No bonus points if you could write a solution within five minutes. A comprehensive solution is better than a fast and clumsy one.


Exercise 24. Accept a filename as command line argument. Assuming that the file passed is a .json file, read its contents and display them.

Before reading the file, make sure that:

(a) it exists

(c) it is readable

(c) it is a simple file (not a directory or a device file)

(d) if the file is not a well formatted .json, display an appropriate error and exit.


Exercise 25. Write a python program to connect to a remote host using the SSH protocol, run ls command, and show the output.


Exercise 26. Write a python program to create and delete directories repeatedly, starting from a given directory path. Obviously, the program should create directories before they are be deleted. This program would be useful for checking certain features of filesystem, and also NFS and CIFS shared drives.

Arguments to this program should be as listed below.

1. directory path - starting point for creating / deleting directories

2. (optional) duration - run for how much duration, in seconds. Default : 300 seconds (5 minutes)

3. (optional) dontstop - run continuously till you stop the script by sending a signal using ctrl + c. This option should override duration.

4. (optional) dirprefix - string to be used while naming directories

Sub-directories in each directory should be named as dir1, dir2, dir3 and so on. If an optional argument dirprefix is mentioned, the string supplied along with it should be used while naming sub-directories.

Obviously, this program should not delete a directory that does not exist. Also, a thread / process should not create a directory which is already created / being created by another thread / process.


Exercise 27. Write a python program to convert English text to Morse code and vice versa. Or better yet, write two separate python programs, one to convert English text to its equivalent Morse code, and another to convert Morse code to its equivalent English text.

Get names of two files on command line, one for input and one for output, as shown below.

$ ./english_to_morse.py --infile notes.txt --outfile notes_in_morse_code.txt

$ ./morse_to_english.py --infile notes_in_morse_code.txt --outfile notes.txt

Read the English text / Morse code from the input file and write the converted Morse code / English text to the output file.

Q. What is Morse code?

A. See http://en.wikipedia.org/wiki/Morse_Code

Q. Which ASCII characters are considered valid for converting to Morse code?

A. Let's refer to http://en.wikipedia.org/wiki/Morse_Code#Letters.2C_numbers.2C_punctuation

Q. Do you know a web site that does this conversion?

A. There are many. Here's one - http://www.onlineconversion.com/morse_code.htm

Q. What would be the criteria to evaluate my solution?

A. No bonus points if you could write a solution within 10 minutes. A comprehensive solution is better than a fast and clumsy one.

You'll surely get bonus points if you could use some python package rather than writing all of the code yourself from scratch.