I719 Fundamentals of Python/lecture3v3
= Lecture 3 =
Input, Handling Errors, Unit Testing
Input from console
You can prompt the user for input using a function called input
.
on python2, this is called raw_input
input
is a function that stops execution until the user hits 'enter', and the value they enter is the output of the the input
function.
Task 1
Write a program that takes two numbers from the user and prints the numbers added together.
""" Addition calculator Write a script that takes in two numbers, and adds them together. """ number_1 = int(input('Write a number: ')) number_2 = int(input('Write a number: ')) print(number_1 + number_2)
try
and except
try
creates a block that can run code that may raise an error. If an error is raised, the code in except
will run. If an error is NOT raised, then the code in else
will run
number_1 = input('Write a number: ')
number_2 = input('Write a number: ')
try:
number_1 = int(number_1)
number_2 = int(number_2)
except ValueError:
print('You must enter valid integers')
else:
print(number_1 + number_2)
Exceptions
class NotIntegerError(Exception):
pass
number_1 = input('Write a number: ')
number_2 = input('Write a number: ')
if not number_1.isdigit():
raise NotIntegerError('{0} is not a number'.format(number_1))
if not number_2.isdigit():
raise NotIntegerError('{0} is not a number'.format(number_2))
number_1 = int(number_1)
number_2 = int(number_2)
print(number_1 + number_2)
Unit testing
See https://wiki.itcollege.ee/index.php/I719_Fundamentals_of_Python/testing
Arguments from commandline
The standard library has sys which give us access to the command line arguments executed.
import sys
if '-h' in sys.argv or '--help' in sys.argv:
print('Sorry I can\'t help you :(')
But argparse from the standard library is much easier if we want to use the commandline arguments.
Opening a file, printing every line
The file path is passed into the script in the command line. run this script using python3 my_script.py --help
and a help message will show. run this script with python3 my_script path/to/my/file.txt
to read file.txt
line by line.
NOTE: you must run this from the commandline, not from your IDE
Task 2
Count the occurence of words in the file.
example output
{'banana': 1, 'carrot': 9, 'pumpkin': 2, 'cabbage': 7}
example solution
import argparse
parser = argparse.ArgumentParser(description='Count unique words in a file')
parser.add_argument('path')
args = parser.parse_args()
my_file = open(args.path, 'r')
result = {}
for line in my_file:
clean_line = line.strip()
result[clean_line] = result.get(clean_line, 0) + 1
my_file.close()
print(result)