diff options
author | Prabhu Ramachandran | 2017-02-21 01:36:12 +0530 |
---|---|---|
committer | Prabhu Ramachandran | 2017-02-21 01:36:12 +0530 |
commit | 10058532c29188637409eed7643626eff53bdc7c (patch) | |
tree | 5daf5760b75650526fe7ecad845305a251cc6816 /basic_python | |
parent | b234e1bef428cf79bd0c50a37df8331a2890656b (diff) | |
download | python-workshops-10058532c29188637409eed7643626eff53bdc7c.tar.gz python-workshops-10058532c29188637409eed7643626eff53bdc7c.tar.bz2 python-workshops-10058532c29188637409eed7643626eff53bdc7c.zip |
Add exceptions and practice exercises.
Update makefile.
Diffstat (limited to 'basic_python')
-rw-r--r-- | basic_python/Makefile | 8 | ||||
-rw-r--r-- | basic_python/exceptions.tex | 289 | ||||
-rw-r--r-- | basic_python/practice_files_exc.tex | 206 |
3 files changed, 502 insertions, 1 deletions
diff --git a/basic_python/Makefile b/basic_python/Makefile index 1cdc572..6310d3a 100644 --- a/basic_python/Makefile +++ b/basic_python/Makefile @@ -9,7 +9,13 @@ SLIDES= basics.pdf \ control_flow.pdf \ practice_control_flow.pdf \ core_data_structures.pdf \ - practice_ds.pdf + practice_ds.pdf \ + functions.pdf \ + practice_functions.pdf \ + modules.pdf \ + files.pdf \ + exceptions.pdf \ + practice_files_exc.pdf all: $(SLIDES) diff --git a/basic_python/exceptions.tex b/basic_python/exceptions.tex new file mode 100644 index 0000000..766dc98 --- /dev/null +++ b/basic_python/exceptions.tex @@ -0,0 +1,289 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%Tutorial slides on Python. +% +% Author: FOSSEE +% Copyright (c) 2017, FOSSEE, IIT Bombay +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} +\input{macros.tex} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Exceptions]{Python language: exceptions} + +\author[FOSSEE Team] {The FOSSEE Group} + +\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {Mumbai, India} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% DOCUMENT STARTS +\begin{document} + +\begin{frame} + \titlepage +\end{frame} + +\begin{frame}{Motivation} + \begin{itemize} + \item How do you signal errors to a user? + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Exceptions} + \begin{itemize} + \item Python's way of notifying you of errors + \item Several standard exceptions: \texttt{SyntaxError}, \texttt{IOError} + etc. + \item Users can also \texttt{raise} errors + \item Users can create their own exceptions + \item Exceptions can be ``caught'' via \texttt{try/except} blocks + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exceptions: examples} + \begin{lstlisting} +In []: while True print('Hello world') + \end{lstlisting} +\pause + \begin{lstlisting} +File "<stdin>", line 1, in ? + while True print('Hello world') + ^ +SyntaxError: invalid syntax +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exceptions: examples} + \begin{lstlisting} +In []: print(spam) +\end{lstlisting} +\pause +\begin{lstlisting} +Traceback (most recent call last): + File "<stdin>", line 1, in <module> +NameError: name 'spam' is not defined +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exceptions: examples} + \begin{lstlisting} +In []: 1 / 0 +\end{lstlisting} +\pause +\begin{lstlisting} +Traceback (most recent call last): + File "<stdin>", line 1, in <module> +ZeroDivisionError: integer division +or modulo by zero +\end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Exceptions: examples} +\begin{lstlisting} +In []: '2' + 2 +\end{lstlisting} +\pause +\begin{lstlisting} +Traceback (most recent call last): + File "<stdin>", line 1, in ? +TypeError: cannot concatenate 'str' and 'int' objects +\end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Processing user input} + \begin{lstlisting} +prompt = 'Enter a number(Q to quit): ' +a = input(prompt) + +num = int(a) if a != 'Q' else 0 + \end{lstlisting} + \emphbar{What if the user enters some other alphabet?} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Handling Exceptions} + Python provides a \typ{try} and \typ{except} clause. + \begin{lstlisting} +prompt = 'Enter a number(Q to quit): ' +a = input(prompt) +try: + num = int(a) + print(num) +except: + if a == 'Q': + print("Exiting ...") + else: + print("Wrong input ...") + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Handling Exceptions a little better} + Use specific exceptions; avoid blanket except clauses + \begin{lstlisting} +prompt = 'Enter a number(Q to quit): ' +a = input(prompt) +try: + num = int(a) + print(num) +except ValueError: + if a == 'Q': + print("Exiting ...") + else: + print("Wrong input ...") + \end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Exceptions: examples} + \small +\begin{lstlisting} +prompt = "Enter a number: " +while True: + try: + x = int(input(prompt)) + break + except ValueError: + print("Invalid input, try again...") + +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Catching multiple exceptions} +\begin{lstlisting} +data = input() +try: + x = int(data.split(',')[1]) + break +except IndexError: + print('Input at least 2 values.') +except ValueError: + print("Invalid input, try again...") + +\end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Catching multiple exceptions} +\begin{lstlisting} +data = input() +try: + x = int(data.split(',')[1]) + break +except (ValueError, IndexError): + print("Invalid input ...") + +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{try, except, else}} +\begin{lstlisting} +data = input() +try: + x = int(data.split(',')[1]) + break +except (ValueError, IndexError): + print("Invalid input ...") +else: + print('All is well!') + \end{lstlisting} + +\end{frame} + + +\begin{frame} + \frametitle{Some comments} + \begin{itemize} + \item In practice NEVER use blanket except clauses + \item Always catch specific exceptions + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Exceptions: raising your exceptions} +\small +\begin{lstlisting} +>>> raise ValueError("your error message") +Traceback (most recent call last): + File "<stdin>", line 2, in ? +ValueError: your error message +\end{lstlisting} +\end{frame} + + + +\begin{frame}[fragile] + \frametitle{Exceptions: try/finally} + \small +\begin{lstlisting} +while True: + try: + x = int(input(prompt)) + break + except ValueError: + print("Invalid number, try again...") + finally: + print "All good!" + + \end{lstlisting} + \normalsize + Always runs the finally clause! +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Exceptions: try/finally} + \begin{lstlisting} +def f(x): + try: + y = int(x) + return y + except ValueError: + print(x) + finally: + print('finally') + +>>> f(1) +>>> f('a') +\end{lstlisting} +Always runs the finally clause! +\end{frame} + + +\begin{frame} + \frametitle{Summary} + \begin{itemize} + \item Catching exceptions with \typ{try/except} + \item Catching multiple exceptions + \item Cleanup with \typ{finally} + \item Raising your own exceptions + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{What next?} + \begin{itemize} + \item Only covered the very basics + \item More advanced topics remain + \item Read the official Python tutorial: + \url{docs.python.org/tutorial/} + \end{itemize} +\end{frame} + +\end{document} diff --git a/basic_python/practice_files_exc.tex b/basic_python/practice_files_exc.tex new file mode 100644 index 0000000..4a7cdfc --- /dev/null +++ b/basic_python/practice_files_exc.tex @@ -0,0 +1,206 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Tutorial slides on Python. +% +% Author: FOSSEE +% Copyright (c) 2017, FOSSEE, IIT Bombay +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} + +\input{macros.tex} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Files/exceptions]{Practice exercises: files and exceptions} + +\author[FOSSEE Team] {The FOSSEE Group} + +\institute[FOSSEE -- IITB] {Department of Aerospace Engineering\\IIT Bombay} +\date[] {Mumbai, India} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% DOCUMENT STARTS +\begin{document} + +\begin{frame} + \titlepage +\end{frame} + + +\begin{frame}[plain] + \frametitle{Exercise: reading from a file} + \begin{enumerate} + \item Define a function called \typ{largest} which takes a single argument + \item The argument passed will be an opened file object + \item Read the data in the file + \item Assume that the data is separated by spaces and are all numbers + \item Find the maximum value in the file + \item Do not use \typ{loadtxt}! + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + def largest(f): + data = [] + for line in f: + for field in line.split(): + data.append(float(field)) + return max(data) + +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Another solution} +\begin{lstlisting} +def largest(f): + res = -1e20 + for line in f: + for field in line.split(): + res = max(res, float(field)) + return res + +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain] + \frametitle{Exercise: reading/writing files} + \begin{enumerate} + \item Read the \typ{pendulum.txt} file + \item Print the second column alone to another file called \typ{col2.txt} + \item Remember to add a newline + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + f = open('pendulum.txt') + out = open('col2.txt', 'w') + for line in f: + fields = line.split() + out.write(fields[1] + '\n') + f.close() + out.close() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Another solution} +\begin{lstlisting} + f = open('pendulum.txt') + out = open('col2.txt', 'w') + for line in f: + fields = line.split() + print(fields[1], file=out) + f.close() + out.close() +\end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Exercise: simple exceptions} + \begin{enumerate} + \item Write a function called \typ{my\_sum} + \item The function is passed a single string with terms separated by spaces + \item The string contains both names and integer values in arbitrary order + \item Find the sum of all the numbers in the string + \end{enumerate} + For example: + \begin{lstlisting} +>>> my_sum('1 fox, 2 dogs and 3 jackals') +6 +>>> my_sum('3 blind mice and 1 man') +4 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Possible solution} +\begin{lstlisting} + def my_sum(s): + total = 0 + for word in s.split(): + try: + total += int(word) + except ValueError: + pass + return total + \end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Exercise: catching exceptions} + \small + \begin{enumerate} + \item Write a function called \typ{safe\_run(f, x)} + \item \typ{f} is a function and \typ{x} is a value + \item \typ{f} can raise either \typ{ValueError} or \typ{TypeError} + \item Your function should return \typ{'OK'} if no exception is raised + \item Return \typ{'ValueError'} if \typ{ValueError} is raised + \item Return \typ{'TypeError'} if \typ{TypeError} is raised + \end{enumerate} + For example: + \begin{lstlisting} + >>> safe_run(float, 'A') + 'ValueError' + >>> def f(x): return x + 2 + >>> safe_run(f, '2') + 'TypeError' + >>> safe_run(float, '2') + 'OK' + \end{lstlisting} + +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Possible solution} +\begin{lstlisting} + def safe_run(f, x): + try: + f(x) + except ValueError: + return 'ValueError' + except TypeError: + return 'TypeError' + else: + return 'OK' + + \end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Exercise: raising exceptions} + \begin{enumerate} + \item Write a function \typ{func} which takes a single integer argument + \item If \typ{x} is not a positive integer raise a \typ{ValueError} + \item If \typ{x} is not an integer type raise a \typ{TypeError} + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] + \frametitle{Possible solution} + \small +\begin{lstlisting} + def func(x): + if type(x) != int: + raise TypeError('Expected int') + elif x < 0: + raise ValueError('Got negative int') + +\end{lstlisting} +\end{frame} + +\begin{frame} + \centering + \Huge + + Thank you! +\end{frame} +\end{document} + +\end{document} |