From 2c5145f262e82996c9c2424159e5eb5dde47fae7 Mon Sep 17 00:00:00 2001 From: Prabhu Ramachandran Date: Tue, 15 May 2018 19:17:01 +0530 Subject: Reorganize files so order is obvious. --- basic_python/01_basics.tex | 698 +++++++++++++++++++++++++++++ basic_python/02_practice_basics.tex | 318 ++++++++++++++ basic_python/03_control_flow.tex | 402 +++++++++++++++++ basic_python/04_practice_control_flow.tex | 399 +++++++++++++++++ basic_python/05_core_data_structures.tex | 704 ++++++++++++++++++++++++++++++ basic_python/06_practice_ds.tex | 411 +++++++++++++++++ basic_python/07_functions.tex | 435 ++++++++++++++++++ basic_python/08_practice_functions.tex | 357 +++++++++++++++ basic_python/09_modules.tex | 278 ++++++++++++ basic_python/10_files.tex | 294 +++++++++++++ basic_python/11_exceptions.tex | 292 +++++++++++++ basic_python/12_practice_files_exc.tex | 217 +++++++++ basic_python/Makefile | 26 +- basic_python/basics.tex | 698 ----------------------------- basic_python/control_flow.tex | 402 ----------------- basic_python/core_data_structures.tex | 704 ------------------------------ basic_python/exceptions.tex | 292 ------------- basic_python/files.tex | 294 ------------- basic_python/functions.tex | 435 ------------------ basic_python/modules.tex | 278 ------------ basic_python/practice_basics.tex | 318 -------------- basic_python/practice_control_flow.tex | 399 ----------------- basic_python/practice_ds.tex | 411 ----------------- basic_python/practice_files_exc.tex | 217 --------- basic_python/practice_functions.tex | 357 --------------- 25 files changed, 4818 insertions(+), 4818 deletions(-) create mode 100644 basic_python/01_basics.tex create mode 100644 basic_python/02_practice_basics.tex create mode 100644 basic_python/03_control_flow.tex create mode 100644 basic_python/04_practice_control_flow.tex create mode 100644 basic_python/05_core_data_structures.tex create mode 100644 basic_python/06_practice_ds.tex create mode 100644 basic_python/07_functions.tex create mode 100644 basic_python/08_practice_functions.tex create mode 100644 basic_python/09_modules.tex create mode 100644 basic_python/10_files.tex create mode 100644 basic_python/11_exceptions.tex create mode 100644 basic_python/12_practice_files_exc.tex delete mode 100644 basic_python/basics.tex delete mode 100644 basic_python/control_flow.tex delete mode 100644 basic_python/core_data_structures.tex delete mode 100644 basic_python/exceptions.tex delete mode 100644 basic_python/files.tex delete mode 100644 basic_python/functions.tex delete mode 100644 basic_python/modules.tex delete mode 100644 basic_python/practice_basics.tex delete mode 100644 basic_python/practice_control_flow.tex delete mode 100644 basic_python/practice_ds.tex delete mode 100644 basic_python/practice_files_exc.tex delete mode 100644 basic_python/practice_functions.tex (limited to 'basic_python') diff --git a/basic_python/01_basics.tex b/basic_python/01_basics.tex new file mode 100644 index 0000000..28aa214 --- /dev/null +++ b/basic_python/01_basics.tex @@ -0,0 +1,698 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%Tutorial slides on Python. +% +% Author: FOSSEE +% Copyright (c) 2009-2017, FOSSEE, IIT Bombay +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} + +\input{macros.tex} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Basic Python]{Python language: Basics} + +\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} + \frametitle{Outline} + \tableofcontents + % You might wish to add the option [pausesections] +\end{frame} + +\section{Data types} + +\begin{frame} + \frametitle{Primitive Data types} + \begin{itemize} + \item Numbers: float, int, complex + \item Strings + \item Booleans + \end{itemize} +\end{frame} + +\subsection{Numbers} +\begin{frame}[fragile] + \frametitle{Numbers} + \begin{itemize} + \item \kwrd{int}\\ whole number, no matter what the size! + \begin{lstlisting} +In []: a = 13 + +In []: b = 99999999999999999999 + \end{lstlisting} + \item \kwrd{float} + \begin{lstlisting} +In []: p = 3.141592 + \end{lstlisting} + \item \kwrd{complex} + \begin{lstlisting} +In []: c = 3+4j +In []: c = complex(3, 4) + \end{lstlisting} + \end{itemize} +\end{frame} + +\subsection{Booleans} +\begin{frame}[fragile] + \frametitle{Booleans} + \begin{lstlisting} +In []: t = True + +In []: F = not t + +In []: F or t +Out[]: True + +In []: F and t +Out[]: False + \end{lstlisting} +%% \inctime{5} +\end{frame} + +\begin{frame}[fragile] + \frametitle{( ) for precedence} + \begin{lstlisting} +In []: a = False +In []: b = True +In []: c = True + +In []: (a and b) or c +Out[]: True + +In []: a and (b or c) +Out[]: False + \end{lstlisting} +%% \inctime{5} +\end{frame} + +\subsection{Strings} + +\begin{frame}[fragile] +\frametitle{Strings} +Anything within ``quotes'' is a string! +\begin{lstlisting} +' This is a string ' +" This too! " +""" This one too! """ +''' And one more! ''' +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] +\frametitle{Strings} +Why so many? +\begin{lstlisting} +' "Do or do not. No try." said Yoda.' +" ' is a mighty lonely quote." +\end{lstlisting} +The triple quoted ones can span multiple lines! + +\begin{lstlisting} +""" The quick brown +fox jumped over + the lazy dingbat. +""" +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Strings} + \begin{lstlisting} +In []: w = "hello" + +In []: print(w[0], w[1], w[-1]) + +In []: len(w) +Out[]: 5 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Strings \ldots} + \emphbar{Strings are immutable} + \begin{lstlisting} +In []: w[0] = 'H' + \end{lstlisting} + \pause + \begin{lstlisting} +-------------------------------------------- +TypeError Traceback (most recent call last) + + in () + +TypeError: 'str' object does not + support item assignment + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Finding the type} +\begin{lstlisting} +In []: a = 1.0 +In []: type(a) +Out[]: float +In []: type(1) +Out[]: int + +In []: type(1+1j) +Out[]: complex + +In []: type('hello') +Out[]: str +\end{lstlisting} +\end{frame} + +\section{Operators} + +\begin{frame}[fragile] + \frametitle{Arithmetic operators} + \small + \begin{lstlisting} +In []: 1786 % 12 +Out[]: 10 + +In []: 45 % 2 +Out[]: 1 + +In []: 864675 % 10 +Out[]: 5 + +In []: 3124 * 126789 +Out[]: 396088836 + +In []: big = 1234567891234567890 ** 3 + +In []: verybig = big * big * big * big + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Arithmetic operators} + \begin{lstlisting} +In []: 17 / 2 +Out[]: 8.5 # 8 on Python 2.x + +In []: 17 / 2.0 +Out[]: 8.5 + +In []: 17.0 / 2 +Out[]: 8.5 + +In []: 17.0 / 8.5 +Out[]: 2.0 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Arithmetic operators: floor division} + \begin{lstlisting} +In []: 17 // 2 +Out[]: 8 + +In []: 17 // 2.0 +Out[]: 8.0 + +In []: 17.0 // 2.0 +Out[]: 8.0 + +In []: 17.0 // 8.6 +Out[]: 1.0 + \end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] +\frametitle{Arithmetic operators} + \begin{lstlisting} +In []: c = 3+4j + +In []: abs(c) +Out[]: 5.0 + +In []: c.imag +Out[]: 4.0 +In []: c.real +Out[]: 3.0 + +In []: c.conjugate() +(3-4j) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Arithmetic operators} + \begin{lstlisting} +In []: a = 7546 + +In []: a += 1 +In []: a +Out[]: 7547 + +In []: a -= 5 +In []: a + +In []: a *= 2 + +In []: a /= 5 + \end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{String operations} + \begin{lstlisting} +In []: s = 'Hello' + +In []: p = 'World' + +In []: s + p +Out[]: 'HelloWorld' + +In []: s * 4 +Out[]: 'HelloHelloHelloHello' + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{String operations \ldots} + \begin{lstlisting} +In []: s * s + \end{lstlisting} + \pause + \begin{lstlisting} +-------------------------------------------- +TypeError Traceback (most recent call last) + + in () + +TypeError: can`t multiply sequence by + non-int of type `str` + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{String methods} + \begin{lstlisting} +In []: a = 'Hello World' +In []: a.startswith('Hell') +Out[]: True + +In []: a.endswith('ld') +Out[]: True + +In []: a.upper() +Out[]: 'HELLO WORLD' + +In []: a.lower() +Out[]: 'hello world' + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{String methods} + \begin{lstlisting} +In []: a = ' Hello World ' +In []: b = a.strip() +In []: b +Out[]: 'Hello World' + +In []: b.index('ll') +Out[]: 2 +In []: b.replace('Hello', 'Goodbye') +Out[]: 'Goodbye World' +\end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] +\frametitle{Strings: \typ{split} \& \typ{join}} + \begin{lstlisting} +In []: chars = 'a b c' +In []: chars.split() +Out[]: ['a', 'b', 'c'] +In []: ' '.join(['a', 'b', 'c']) +Out[]: 'a b c' + \end{lstlisting} + \begin{lstlisting} +In []: alpha = ', '.join(['a', 'b', 'c']) +In []: alpha +Out[]: 'a, b, c' +In []: alpha.split(', ') +Out[]: ['a', 'b', 'c'] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] +\frametitle{String formatting} + \begin{lstlisting} +In []: x, y = 1, 1.234 + +In []: 'x is %s, y is %s' %(x, y) +Out[]: 'x is 1, y is 1.234' + \end{lstlisting} + \begin{itemize} + \item \emph{\%d}, \emph{\%f} etc. available + \end{itemize} + \emphbar{\url{http://docs.python.org/library/stdtypes.html}} +%% \inctime{10} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Relational and logical operators} + \begin{lstlisting} +In []: p, z, n = 1, 0, -1 +In []: p == n +Out[]: False + +In []: p >= n +Out[]: True + +In []: n < z < p +Out[]: True + +In []: p + n != z +Out[]: False + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{The \typ{assert} statement} + \begin{itemize} + \item You will see it in tests and your exam! + \end{itemize} + + \begin{small} +\begin{lstlisting} +In []: assert p != n +In []: assert p == n +------------------------------------------------------ +AssertionError Traceback (most recent call last) +----> 1 assert p == n + +AssertionError: +\end{lstlisting} + \end{small} + \begin{itemize} + \item No error if condition is True + \item Raises error if False + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{assert} examples} + \begin{small} +\begin{lstlisting} +In []: assert p == n, "Oops condition failed" +------------------------------------------------------ +AssertionError Traceback (most recent call last) +----> 1 assert p == n + +AssertionError: Oops condition failed +\end{lstlisting} + \end{small} + \begin{itemize} + \item Can supply an optional message + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] +\frametitle{String containership} + \begin{lstlisting} +In []: fruits = 'apple, banana, pear' +In []: 'apple' in fruits +Out[]: True + +In []: 'potato' in fruits +Out[]: False + +\end{lstlisting} + \begin{itemize} + \item Use tab complete to list other string methods + \item Use \typ{?} to find more information + \end{itemize} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{Built-ins} + \begin{lstlisting} +In []: int(17 / 2.0) +Out[]: 8 + +In []: float(17 // 2) +Out[]: 8.0 + +In []: str(17 / 2.0) +Out[]: '8.5' + +In []: round( 7.5 ) +Out[]: 8.0 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Odds and ends} + \begin{itemize} + \item Case sensitive + \item Dynamically typed $\Rightarrow$ need not specify a type + \begin{lstlisting} +In []: a = 1 +In []: a = 1.1 +In []: a = "Now I am a string!" + \end{lstlisting} + \item Comments: + \begin{lstlisting} +In []: a = 1 # In-line comments +In []: # A comment line. +In []: a = "# Not a comment!" + \end{lstlisting} + \end{itemize} +%% \inctime{15} +\end{frame} + +\begin{frame} + \frametitle{Exercise 1} + Given a 2 digit integer\ \typ{x}, find the digits of the number. + \vspace*{1em} + + \begin{itemize} + \item For example, let us say \typ{x = 38} + \item Find a way to get \typ{a = 3} and \typ{b = 8} using \typ{x}? + \end{itemize} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{Possible Solution} +\begin{lstlisting} +In []: a = x//10 +In []: b = x%10 +In []: a*10 + b == x +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Another Solution} +\begin{lstlisting} +In []: sx = str(x) +In []: a = int(sx[0]) +In []: b = int(sx[1]) +In []: a*10 + b == x +\end{lstlisting} +\end{frame} + + +\begin{frame} + \frametitle{Exercise 2} + Given an arbitrary integer, count the number of digits it has. +\end{frame} + +\begin{frame}[fragile] +\frametitle{Possible solution} +\begin{lstlisting} +In []: x = 12345678 +In []: len(str(x)) +\end{lstlisting} + + Sneaky solution! +\end{frame} + + + +\section{Simple IO} +\begin{frame}[fragile] + \frametitle{Simple IO: Console Input} + \small + \begin{itemize} + \item \typ{input()} waits for user input. + \begin{lstlisting} +In []: a = input() +5 + +In []: a +Out[]: '5' # Python 3.x! + +In []: a = input('Enter a value: ') +Enter a value: 5 + \end{lstlisting} + \item Prompt string is optional. + \item \typ{input} produces strings (Python 3.x) + \item \typ{int()} converts string to int. + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Simple IO: Python 2.x vs 3.x} + \begin{itemize} + \item \typ{print} is familiar to us + \item Changed from Python 2.x to 3.x + \item We use the Python 3 convention here + \vspace*{2em} + \item If on Python 2.x do this: + { + \small +\begin{lstlisting} +In []: from __future__ import print_function +\end{lstlisting} + } + \item Safe to use in Python 3.x also + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Simple IO: Console output} + \begin{itemize} + \item Put the following code snippet in a file \typ{hello1.py} + \end{itemize} +\begin{lstlisting} +from __future__ import print_function +print("Hello", "World") +print("Goodbye", "World") +\end{lstlisting} +Now run it like so: +\begin{lstlisting} +In []: %run hello1.py +Hello World +Goodbye World + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Simple IO: Console output \ldots} +Put the following code snippet in a file \typ{hello2.py} + \begin{lstlisting} +from __future__ import print_function +print("Hello", end=' ') +print("World") +\end{lstlisting} +Now run it like so: +\begin{lstlisting} +In []: %run hello2.py +Hello World + \end{lstlisting} + +\pause + +\begin{block}{Mini Exercise} + \begin{itemize} + \item Read docs for \typ{print} + \item Remember: use \typ{print?} \ + \end{itemize} +\end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{What did we learn?} + \begin{itemize} + \item Data types: int, float, complex, boolean, string + \item Use \typ{type} builtin function to find the type + \item Operators: +, -, *, /, \%, **, +=, -=, *=, /=, >, <, <=, >=, ==, !=, a < b < c + \item Simple IO: \kwrd{input} and \kwrd{print} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Homework} + \begin{itemize} + \item Explore the various string methods + \item Read the documentation for the string methods + \item Explore the different builtins seen so far also + \end{itemize} +\end{frame} + + +\end{document} + +%% Questions for Quiz %% +%% ------------------ %% + + +\begin{frame} +\frametitle{\incqno } + What is the largest integer value that can be represented natively by Python? +\end{frame} + +\begin{frame} +\frametitle{\incqno } + What is the result of 17.0 / 2? +\end{frame} + +\begin{frame} +\frametitle{\incqno } + Which of the following is not a type in Python? + \begin{enumerate} + \item int + \item float + \item char + \item string + \end{enumerate} +\end{frame} + +\begin{frame} +\frametitle{\incqno } +How do you create a complex number with real part 2 and imaginary part +0.5. +\end{frame} + +\begin{frame} +\frametitle{\incqno } + What is the difference between \kwrd{print} \emph{x} and \kwrd{print} \emph{x,} ? +\end{frame} + +\begin{frame} +\frametitle{\incqno } + What does '*' * 40 produce? +\end{frame} + +\begin{frame}[fragile] +\frametitle{\incqno } + What is the output of: + \begin{lstlisting} +In []: ', '.join(['a', 'b', 'c']) + \end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{\incqno} + \begin{lstlisting} +In []: 47 % 3 + \end{lstlisting} + What is the output? +\end{frame} diff --git a/basic_python/02_practice_basics.tex b/basic_python/02_practice_basics.tex new file mode 100644 index 0000000..37e535c --- /dev/null +++ b/basic_python/02_practice_basics.tex @@ -0,0 +1,318 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Tutorial slides on Python. +% +% Author: FOSSEE +% Copyright (c) 2009-2017, FOSSEE, IIT Bombay +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} + +\input{macros.tex} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Basic Python]{Practice exercises: Basics} + +\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}[fragile,plain] + \frametitle{Note: Python 2.x and 3.x} + + If you are using Python 2.x + \begin{itemize} + \item Use \typ{raw\_input} instead of \typ{input} + \item Use the following for \typ{print} + \end{itemize} + \begin{lstlisting} +from __future__ import print_function +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: print string} + \begin{enumerate} + \item Ask the user to enter a name + \begin{itemize} + \item use \typ{input()} (or \typ{raw\_input()} on 2.x) + \end{itemize} + \item Lets say the user entered: \\ \typ{abc}\\ then print \\ \typ{hello abc} + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Possible solution} +\begin{lstlisting} + name = input() # Or raw_input() + print("hello", name) +\end{lstlisting} + +\end{frame} + + +\begin{frame}[plain] + \frametitle{Exercise: input prompt} + \begin{enumerate} + \item Ask the user to enter a name but give them a prompt:\\ \typ{"Please + enter your name: "} \\ (note the trailing space) + \item Lets say the user entered: \\ \typ{abc}\\ then print \\ \typ{hello abc} + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Possible solution} +\begin{lstlisting} +name = input("Please enter your name: ") +print("hello", name) +\end{lstlisting} + +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: integers} + \begin{enumerate} + \item Ask the user for a single integer (no prompt string) + \item Print the square of this number + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Possible solution} +\begin{lstlisting} + x_str = input() + x = int(x_str) + print(x*x) +\end{lstlisting} + +\end{frame} + + +\begin{frame}[plain] + \frametitle{Exercise: digits of integer} + \begin{enumerate} + \item Ask the user for a single integer (use an empty prompt) + \item Square this integer + \item Print the number of digits the squared integer has + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Possible solution} +\begin{lstlisting} + x_str = input() + x = int(x_str) + y_str = str(x*x) + print(len(y_str)) +\end{lstlisting} + +\end{frame} + +\begin{frame}[fragile,plain] + \frametitle{Exercise: complex numbers} + \begin{enumerate} + \item Ask the user for a single complex number + \item If the number entered was \typ{1+2j}, print: + \begin{lstlisting} + 1 2 + \end{lstlisting} + \item Print the absolute value of this complex number + \item Print the conjugate of this complex number + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Possible solution} +\begin{lstlisting} + z_str = input() + z = complex(z_str) + print(z.real, z.imag) + print(abs(z)) + print(z.conjugate()) +\end{lstlisting} + +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: Booleans} + \begin{enumerate} + \item Ask the user to enter an integer (use an empty prompt) + \item Print \typ{True} if the number is odd, print \typ{False} otherwise + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Possible solution} +\begin{lstlisting} + x_str = input() + x = int(x_str) + print(x%2 == 1) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: Booleans} + \begin{enumerate} + \item Ask the user to enter an integer (use an empty prompt) + \item Print \typ{True} if the number is even, print \typ{False} otherwise + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Possible solution} +\begin{lstlisting} + x_str = input() + x = int(x_str) + print(x%2 == 0) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: string operations 1} + \begin{itemize} + \item Ask the user to enter a name (use an empty prompt) + \item Print the name entered but in upper case + \item For example, if the user enters 'abc', print 'ABC' + \end{itemize} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Possible solution} +\begin{lstlisting} + name = input() + print(name.upper()) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: string operations 2} + \begin{enumerate} + \item Ask the user to enter the name of a file (use an empty prompt) + \item Add an extension '.txt' to the name and print it + \item For example, if the user enters 'abc', print 'abc.txt' + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Possible solution} +\begin{lstlisting} + name = input() + print(name + '.txt') +\end{lstlisting} + +\end{frame} + + +\begin{frame}[fragile,plain] + \frametitle{Exercise: string slicing} + \begin{enumerate} + \item Ask the user to enter a string + \item Print the string without the first character + \item Print the string without the last character + \item Print the string in reverse + \item Finally print every alternate character of the string starting from + the first + \end{enumerate} + For example, if the user enters 'abcd', print the following: + \begin{lstlisting} + bcd + abc + dcba + ac + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Possible solution} +\begin{lstlisting} + name = input() + print(name[1:]) + print(name[:-1]) + print(name[::-1]) + print(name[::2]) +\end{lstlisting} + +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: string manipulations} + \begin{itemize} + \item Ask the user to enter a string + \item Count the number of vowels in the string + \item The code should be case-insensitive + \end{itemize} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Possible solution} +\begin{lstlisting} + x = input() + x = x.lower() + n = (x.count('a') + x.count('e') + + x.count('i') + x.count('o') + + x.count('u')) + print(n) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: string containership} + \begin{itemize} + \item Ask the user to enter a string + \item Check if the substrings 'abc' OR 'def' exist in the string + \item If it does, print True, else False + \end{itemize} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Possible solution} +\begin{lstlisting} + x = input().lower() + print('abc' in x or 'def' in x) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: digits of an integer} + Given a 2 digit integer\ \typ{x}, find the digits of the number. + \vspace*{1em} + + \begin{itemize} + \item For example, let us say \typ{x = 38} + \item Find a way to get \typ{a = 3} and \typ{b = 8} using \typ{x} + \item Print the digits, one in each line + \end{itemize} +\end{frame} + +\begin{frame}[fragile,plain] + \frametitle{Possible Solution} + \begin{lstlisting} +x = int(input()) +a = x//10 +b = x%10 +print(a) +print(b) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] + \frametitle{Another Solution} +\begin{lstlisting} + x = input() + print(x[0]) + print(x[1]) +\end{lstlisting} +\end{frame} + +\end{document} diff --git a/basic_python/03_control_flow.tex b/basic_python/03_control_flow.tex new file mode 100644 index 0000000..25d9cbc --- /dev/null +++ b/basic_python/03_control_flow.tex @@ -0,0 +1,402 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%Tutorial slides on Python. +% +% Author: FOSSEE +% Copyright (c) 2009-2017, FOSSEE, IIT Bombay +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} + +\input{macros.tex} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Control flow]{Python language: Control Flow} + +\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} + \frametitle{Outline} + \tableofcontents + % You might wish to add the option [pausesections] +\end{frame} + +\section{Control flow} + +\begin{frame} + \frametitle{Control flow constructs} + \begin{itemize} + \item \kwrd{if/elif/else}: branching + \item \kwrd{while}: looping + \item \kwrd{for}: iterating + \item \kwrd{break, continue}: modify loop + \item \kwrd{pass}: syntactic filler + \end{itemize} +\end{frame} + +\subsection{Basic Conditional flow} +\begin{frame}[fragile] + \frametitle{\typ{if...elif...else} example} +Type the following code in an editor \& save as \alert{ladder.py} +{ \small +\begin{lstlisting} +x = int(input("Enter an integer: ")) +if x < 0: + print('Be positive!') +elif x == 0: + print('Zero') +elif x == 1: + print('Single') +else: + print('More') +\end{lstlisting} +} + %% \inctime{10} +\pause +\begin{itemize} +\item Run in IPython: \typ{\%run ladder.py} +\item Run on terminal: \typ{python ladder.py} +\end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Ternary operator} + \begin{itemize} + \item \texttt{score\_str} is either \texttt{'AA'} or a string of one + of the numbers in the range 0 to 100. + \item We wish to convert the string to a number using \texttt{int} + \item Convert it to 0, when it is \texttt{'AA'} + \item \texttt{if-else} construct or the ternary operator + \end{itemize} + \begin{lstlisting} +In []: if score_str != 'AA': +.....: score = int(score_str) +.....: else: +.....: score = 0 + \end{lstlisting} +\end{frame} +\begin{frame}[fragile] + \frametitle{Ternary operator} + With the ternary operator you can do this: + \small + \begin{lstlisting} +In []: ss = score_str +In []: score = int(ss) if ss != 'AA' else 0 + \end{lstlisting} +\end{frame} + + +\section{Control flow} +\subsection{Basic Looping} + +\begin{frame} + \frametitle{\typ{while}: motivational problem} +\begin{block}{Example: Fibonacci series} + Sum of previous two elements defines the next: + \begin{center} + $0,\ \ 1,\ \ 1,\ \ 2,\ \ 3,\ \ 5,\ \ 8,\ \ 13,\ \ 21,\ \ ...$ + \end{center} +\end{block} +\end{frame} + +\begin{frame} + \frametitle{How do you solve this?} + \begin{itemize} + \item Task: Give computer, instructions to solve this + \vspace*{2em} + \item How would you solve it? + \item How would you tell someone to solve it? + \vspace*{1em} + \item Assume you are given the starting values, 0 and 1. + \end{itemize} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{while}: Fibonacci} +\begin{block}{Example: Fibonacci series} + Sum of previous two elements defines the next: + \begin{center} + $0,\ \ 1,\ \ 1,\ \ 2,\ \ 3,\ \ 5,\ \ 8,\ \ 13,\ \ 21,\ \ ...$ + \end{center} +\end{block} +\pause +\begin{enumerate} +\item Start with: \typ{a, b = 0, 1} + \pause +\item Next element: \typ{next = a + b} + \pause +\item Shift \typ{a, b} to next values + \begin{itemize} + \item \typ{a = b} + \item \typ{b = next} + \end{itemize} + \pause +\item Repeat steps 2, 3 when \typ{b < 30} +\end{enumerate} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{\typ{while}} + \begin{lstlisting} +In []: a, b = 0, 1 +In []: while b < 30: + ...: print(b, end=' ') + ...: next = a + b + ...: a = b + ...: b = next + ...: + ...: +\end{lstlisting} + \begin{itemize} + \item Do this manually to check logic + \item Note: Indentation determines scope + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{while}} + We can eliminate the temporary \typ{next}: + \begin{lstlisting} +In []: a, b = 0, 1 +In []: while b < 30: + ...: print(b, end=' ') + ...: a, b = b, a + b + ...: + ...: +1 1 2 3 5 8 13 21 +\end{lstlisting} + Simple! +\end{frame} + + +\begin{frame}[fragile] + \frametitle{\typ{for} \ldots \typ{range()}} +Example: print squares of first \typ{5} numbers + \begin{lstlisting} +In []: for i in range(5): + ....: print(i, i * i) + ....: + ....: +0 0 +1 1 +2 4 +3 9 +4 16 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] +\frametitle{\typ{range()}} +\kwrd{range([start,] stop[, step])}\\ +\begin{itemize} + \item \typ{range()} returns a sequence of integers + \item The \typ{start} and the \typ{step} arguments are optional + \item \typ{stop} is not included in the sequence +\end{itemize} +\vspace*{.5in} +\begin{block}{Documentation convention} + \begin{itemize} + \item \alert{Anything within \typ{[]} is optional} + \item Nothing to do with Python + \end{itemize} +\end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{for} \ldots \typ{range()}} +Example: print squares of odd numbers from 3 to 9 + \begin{lstlisting} +In []: for i in range(3, 10, 2): + ....: print(i, i * i) + ....: + ....: +3 9 +5 25 +7 49 +9 81 +\end{lstlisting} +%% \inctime{5} +\end{frame} + +\begin{frame} + \frametitle{Exercise with \typ{for}} + +Convert the Fibonnaci sequence example to use a \typ{for} loop with range. + +\end{frame} + +\begin{frame}[fragile] + \frametitle{Solution} +\begin{lstlisting} +a, b = 0, 1 +for i in range(10): + print(b, end=' ') + a, b = b, a + b +\end{lstlisting} + \vspace*{2em} +Note that the \typ{while} loop is a more natural fit here +\end{frame} + +\begin{frame} + \frametitle{\typ{break}, \typ{continue}, and\ \typ{pass}} + \begin{itemize} + \item Use \typ{break} to break out of loop + \item Use \typ{continue} to skip an iteration + \item Use \typ{pass} as syntactic filler + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{break} example} + Find first number in Fibonnaci sequence < 100 divisible by 4: +\begin{lstlisting} +a, b = 0, 1 +while b < 500: + if b % 4 == 0: + print(b) + break + a, b = b, a + b + +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{continue}} + \begin{itemize} + \item Skips execution of rest of the loop on current iteration + \item Jumps to the end of this iteration + \item Squares of all odd numbers below 10, not multiples of 3 + \end{itemize} + \begin{lstlisting} + In []: for n in range(1, 10, 2): + .....: if n%3 == 0: + .....: continue + .....: print(n*n) + \end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{\typ{pass} example} +Try this: +\begin{lstlisting} +for i in range(5): + if i % 2 == 0: + pass + else: + print(i, 'is Odd') +\end{lstlisting} +\begin{itemize} +\item \typ{pass}: does nothing +\item Keep Python syntactically happy +\end{itemize} +Another example: +\begin{lstlisting} +while True: + pass +\end{lstlisting} +\end{frame} + + + +\section{Exercises} + +\begin{frame}{Problem 1.1: \emph{Armstrong} numbers} + Write a program that displays all three digit numbers that are equal to the sum of the cubes of their digits. That is, print numbers $abc$ that have the property $abc = a^3 + b^3 + c^3$\\ +For example, $153 = 1^3 + 5^3 + 3^3$\\ +\vspace*{0.2in} + +\begin{block}{Hints} + \begin{itemize} + \item Break problem into easier pieces + \item How would you solve the problem? + \item Can you explain to someone else how to solve it? + \end{itemize} +\end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Some hints} + \begin{itemize} + \item What are the possible three digit numbers? + \item Can you split 153 into its respective digits, $a=1, b=5, c=3$? + \item With $a, b, c$ can you test if it is an Armstrong number? + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Solution: part 1} +\begin{lstlisting} +x = 153 +a = x//100 +b = (x%100)//10 +c = x%10 + +(a**3 + b**3 + c**3) == x +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Solution: part 2} +\begin{lstlisting} +x = 100 +while x < 1000: + print(x) + x += 1 # x = x + 1 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Solution} +\begin{lstlisting} +x = 100 +while x < 1000: + a = x//100 + b = (x%100)//10 + c = x%10 + if (a**3 + b**3 + c**3) == x: + print(x) + x += 1 +\end{lstlisting} +\end{frame} + + +\begin{frame}{Problem 1.2: Collatz sequence} +\begin{enumerate} + \item Start with an arbitrary (positive) integer. + \item If the number is even, divide by 2; if the number is odd, multiply by 3 and add 1. + \item Repeat the procedure with the new number. + \item It appears that for all starting values there is a cycle of 4, 2, 1 at which the procedure loops. +\end{enumerate} + Write a program that accepts the starting value and prints out the Collatz sequence. +%% \inctime{5} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{What did we learn?} + \begin{itemize} + \item Conditionals: \kwrd{if elif else} + \item Looping: \kwrd{while} \& \kwrd{for} + \item \typ{range} + \item \kwrd{break, continue, pass} + \item Solving simple problems + \end{itemize} +\end{frame} + +\end{document} diff --git a/basic_python/04_practice_control_flow.tex b/basic_python/04_practice_control_flow.tex new file mode 100644 index 0000000..4fa966b --- /dev/null +++ b/basic_python/04_practice_control_flow.tex @@ -0,0 +1,399 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Tutorial slides on Python. +% +% Author: FOSSEE +% Copyright (c) 2009-2017, FOSSEE, IIT Bombay +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} + +\input{macros.tex} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Basic Python]{Practice exercises: Control flow} + +\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}[fragile,plain] + \frametitle{Note: Python 2.x and 3.x} + + If you are using Python 2.x + \begin{itemize} + \item Use \typ{raw\_input} instead of \typ{input} + \item Use the following for \typ{print} + \end{itemize} + \begin{lstlisting} +from __future__ import print_function +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: simple \typ{if}} + \begin{enumerate} + \item Ask the user to enter an integer + \item If the number is positive, print "Positive" + \item If the number is negative, say -10 print:\\ "Negative of 10" + \item If the number is zero, print "Zero" + \item Finally, print "Done" + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + x = int(input()) + if x < 0: + print("Negative of", abs(x)) + elif x > 0: + print("Positive") + else: + print("Zero") + print("Done") +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: simple \typ{if} 2} + \begin{enumerate} + \item Ask the user to enter two integers, one on each line say \typ{x} and \typ{y} + \item If \typ{x} is larger than \typ{y} print, "first", store the value of \typ{x} in a + variable \typ{highest} + \item If \typ{y} is larger than \typ{x} print, "second", store the value of \typ{y} in a + variable \typ{highest} + \item If they are equal, print "same", store either as the \typ{highest} + \item Finally, print the square of the \typ{highest} + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + x = int(input()) + y = int(input()) + if x > y: + print("first") + highest = x + elif y > x: + print("second") + highest = y + else: + print("same") + highest = x + print(highest*highest) +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain] + \frametitle{Simple \typ{while} loop 1} + \begin{enumerate} + \item Use a while loop to print the numbers from 1 to 10 + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + x = 1 + while x < 11: + print(x) + x += 1 +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Simple \typ{while} loop 2} + \begin{enumerate} + \item Use a while loop to print the odd numbers from 1 to 10 + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + x = 1 + while x < 11: + print(x) + x += 2 +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Simple \typ{while} loop 2} + \begin{enumerate} + \item Use a while loop to generate the numbers from 1 to 10 + \item If a number divisible by 3 is found, print *** + \item If a number divisible by 5 is found, print ***** + \item Otherwise just print the number + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + x = 1 + while x < 11: + if x%3 == 0: + print('***') + elif x%5 == 0: + print('*****') + else: + print(x) + x += 1 +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Simple \typ{while} loop 3} + \begin{enumerate} + \item Use a while loop to generate the numbers from 10 to 1 + \item For each number, print that many * characters + \item That is, if the number is 1 print *, if the number is 3, print *** etc. + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + x = 10 + while x > 0: + print('*'*x) + x -= 1 +\end{lstlisting} +\end{frame} + +\begin{frame}[plain,fragile] + \frametitle{Simple \typ{while} loop 4} + \begin{enumerate} + \item Ask the user for an integer, \typ{n} (>=2) + \item Use a while loop to print \typ{n} numbers uniformly spaced between 0 and 1 + \item Include both 0 and 1 + \end{enumerate} + For example if the user entered 3, print + \begin{lstlisting} + 0.0 + 0.5 + 1.0 + \end{lstlisting} + +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + n = int(input()) + dx = 1.0/(n-1) + x = 0.0 + while x < (1.0-dx/2): + print(x) + x += dx + print(1.0) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain,fragile] + \frametitle{Simple \typ{for} loop 1} + \begin{enumerate} + \item Ask the user for an integer + \item Use a for loop to generate the multiplication table for the number (up + to 10) + \end{enumerate} + If the user entered 5, print the following + \begin{lstlisting} + 5 x 1 = 5 + 5 x 2 = 10 + 5 x 3 = 15 + ... + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + n = int(input()) + for i in range(1, 11): + print(n, 'x', i, '=', n*i) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain,fragile] + \frametitle{\typ{for} loop Fibonacci} + \begin{enumerate} + \item Ask the user for an integer, \typ{n} (>=1) + \item Print the first \typ{n} numbers of the Fibonacci sequence + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + n = int(input()) + a, b = 0, 1 + print(a) + for i in range(n-1): + print(b) + a, b = b, a+b +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain,fragile] + \frametitle{\typ{for} loop over list 1} + \begin{enumerate} + \item Ask the user for an integer, \typ{n} + \item Use the range to create numbers from 1 to \typ{n} + \item Print each value in this in a separate line + \end{enumerate} + For example let us say user enters \typ{3}, print + \begin{lstlisting} + 1 + 2 + 3 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + n = int(input()) + for x in range(1, n+1): + print(x) +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain,fragile] + \frametitle{\typ{for} loop over array} + \begin{enumerate} + \item Ask the user for an integer, \typ{n} + \item Use numpy's \typ{linspace} to create n points from 1 to 2 + \item Print each value in this in a separate line + \end{enumerate} + For example let us say user enters \typ{3}, print + \begin{lstlisting} + 1.0 + 1.5 + 2.0 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + from numpy import linspace + n = int(input()) + data = linspace(1, 2, n) + for x in data: + print(x) +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain,fragile] + \frametitle{\typ{for} loop over list 2} + \begin{enumerate} + \item Ask the user for an list of fruits separated by a comma + \item Print each fruit in a separate line + \end{enumerate} + For example let us say user enters \typ{apple, pear}, print + \begin{lstlisting} + apple + pear + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + fruits = input() + fruits = fruits.split(',') + for fruit in fruits: + print(fruit) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain,fragile] + \frametitle{\typ{for} loop over string} + \begin{enumerate} + \item Ask the user for a string + \item Print each character of the string using a for loop + \end{enumerate} + For example let us say user enters \typ{box}, print + \begin{lstlisting} + b + o + x + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + s = input() + for char in s: + print(char) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain,fragile] + \frametitle{Nested \typ{for} loops} + \begin{enumerate} + \item Let us say the user supplies an integer, \typ{n} (empty prompt) + \item Print an n x n matrix where each entry is the sum of the row + column + \end{enumerate} + For example let us say user enters \typ{3}, print + \begin{lstlisting} + 0 1 2 + 1 2 3 + 2 3 4 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + n = int(input()) + for i in range(n): + for j in range(n): + print(i+j, end=' ') + print() +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain,fragile] + \frametitle{Exercise: Fibonacci divisible by 4} + \begin{enumerate} + \item Find the first number in the Fibonacci sequence divisible by 4 but > 8 + and less than 500. + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} +a, b = 0, 1 +while b < 500: + if b % 4 == 0 and b > 8: + print(b) + break + a, b = b, a+b +\end{lstlisting} +\end{frame} + + +\end{document} diff --git a/basic_python/05_core_data_structures.tex b/basic_python/05_core_data_structures.tex new file mode 100644 index 0000000..7bfbb38 --- /dev/null +++ b/basic_python/05_core_data_structures.tex @@ -0,0 +1,704 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%Tutorial slides on Python. +% +% Author: FOSSEE +% Copyright (c) 2009-2017, FOSSEE, IIT Bombay +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} +\input{macros.tex} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Data structures]{Python language: Core data structures} + +\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} + \frametitle{Outline} + \tableofcontents + % You might wish to add the option [pausesections] +\end{frame} + +\section{Data structures} +\subsection{Lists} +\begin{frame}[fragile] + \frametitle{Lists} +\begin{block}{We already know that} + \begin{lstlisting} +num = [1, 2, 3, 4] + \end{lstlisting} +is a list +\end{block} +\pause +\begin{itemize} +\item Lists can contain different types +\item including nested lists +\end{itemize} +\begin{lstlisting} +x = ['apple', 1, 'banana', 2.5, + 'shirt', [1,2,3]] +len(x) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Lists: methods} + \begin{lstlisting} +In []: num = [9, 8, 2, 3, 7] + +In []: num + [4, 5, 6] +Out[]: [9, 8, 2, 3, 7, 4, 5, 6] + +In []: num.append([4, 5, 6]) + +In []: num +Out[]: [9, 8, 2, 3, 7, [4, 5, 6]] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Lists: methods} + \begin{lstlisting} +In []: num = [9, 8, 2, 3, 7] + +In []: num.extend([4, 5, 6]) +In []: num +Out[]: [9, 8, 2, 3, 7, 4, 5, 6] + +In []: num.reverse() +In []: num +Out[]: [6, 5, 4, 7, 3, 2, 8, 9] + +In []: num.remove(6) +In []: num + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Lists: methods} + \begin{lstlisting} +In []: num = [9, 8, 2, 3, 1, 2, 3, 4] +In []: num.count(2) +Out[]: 2 + +In []: num.index(2) +Out[]: 2 + +In []: num.pop() +4 +In []: num +[9, 8, 2, 3, 1, 2, 3] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Removing elements} +\begin{itemize} + \item Elements can be removed based on their index OR + \item based on the value of the element + \end{itemize} + \begin{lstlisting} + In []: del num[1] + + In []: num.remove(3) + \end{lstlisting} + \begin{itemize} + \item \alert{When removing by value, first element is removed} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Sorting} + \begin{lstlisting} + In []: a = [5, 1, 6, 7, 7, 10] + In []: a.sort() + In []: a + \end{lstlisting} + \begin{itemize} + \item \typ{sort} method sorts the list in-place + \item Use \typ{sorted} if you require a new list + \item Pass \typ{reverse=True} to reverse the ordering + \end{itemize} + \begin{lstlisting} + In []: a = [5, 1, 6, 7, 7, 10] + In []: sorted(a, reverse=True) + In []: a + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] +\frametitle{List containership} +\emphbar{Recall \typ{num} is \typ{[9, 8, 2, 3, 7]}} +\begin{lstlisting} +In []: 4 in num +Out[]: False + +In []: b = 8 +In []: b in num +Out[]: True + +In []: b not in num +Out[]: False +\end{lstlisting} +\end{frame} + +\subsection{Tuples} +\begin{frame}[fragile] +\frametitle{Tuples: Immutable sequence} +\begin{lstlisting} +In []: x = 1, 2, 3 +In []: x +(1, 2, 3) + +In []: t = (1, 2, 3, 4, 5, 6, 7, 8) +In []: t[0] + t[3] + t[-1] +Out[]: 13 + +In []: t[4] = 7 +\end{lstlisting} +\pause +\begin{block}{Note:} +\begin{itemize} + \item Tuples are immutable - cannot be changed +\end{itemize} +\end{block} + +\end{frame} + +\begin{frame}[fragile] + \frametitle{Tuple packing and expansion} + Try these: +\begin{lstlisting} +In []: a, b = 1, 2 + +In []: a, b, c = 1, 2, 3 + +In []: a, b = 1, 2, 3 + +In []: a, = [1] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Swapping values} + \vspace*{-1em} + \begin{lstlisting} + In[]: a, b = 5, 7 + + In[]: temp = a + In[]: a = b + In[]: b = temp + \end{lstlisting} + \begin{itemize} + \item Here's the Pythonic way of doing it + \end{itemize} + \begin{lstlisting} + In[]: a, b = b, a + \end{lstlisting} + \begin{itemize} + \item The variables can be of different data-types + \end{itemize} + \begin{lstlisting} + In[]: a = 2.5 + In[]: b = "hello" + In[]: a, b = b, a +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{tuple, list} functions} + Try these: +\begin{lstlisting} +In []: x = 1,2,3 + +In []: list(x) +Out[]: [1, 2, 3] + +In []: tuple(list(x)) +Out[]: (1, 2, 3) + +In []: tuple('hello') +\end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Slicing} + \begin{itemize} + \item Slicing works the same way for all sequence types + \item Indices also work the same way + \item Lists, tuples, and strings + \item \alert{\typ{sequence[initial:final:step]}} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Slicing \& Striding examples} + \begin{lstlisting} +In[]: primes = [2, 3, 5, 7, 11, 13, 17] +In[]: primes[2:6] +In[]: primes[:4] + +In[]: num = list(range(14)) +In[]: num[1:10:2] +In[]: num[:10] +In[]: num[10:] +In[]: num[::2] +In[]: num[::-1] + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Problem - Day of the Week?} + \begin{itemize} + \item Strings have methods to manipulate them + \end{itemize} + \begin{block}{Problem} + Given a list, \texttt{week}, containing names of the days of the + week and a string \texttt{s}, check if the string is a day of the + week. We should be able to check for any of the forms like, + \emph{sat, Sat, SAT} + \end{block} + \begin{itemize} + \item Get the first 3 characters of the string + \item Convert it all to lower case + \item Check for existence in the list, \texttt{week} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Solution - Day of the Week?} + \small +\begin{lstlisting} +week = 'mon tue wed thu fri sat sun'.split() +s = 'Sunday' +s.lower()[:3] in week +\end{lstlisting} + OR +\begin{lstlisting} +s[:3].lower() in week +\end{lstlisting} +\end{frame} + +\subsection{Dictionaries} + +\begin{frame}[fragile] + \frametitle{Dictionaries: Introduction} + \begin{itemize} + \item Lists index using integers; recall that :\\ + \vspace*{1em} + If \typ{p = [2, 3, 5, 7]}\\ + \typ{p[1]} is equal to \typ{3} + \vspace*{2em} + \item Dictionaries index not just with integers! + \item Following examples are for string indices + \item Will also work for integers, floats, tuples, and others + \item \alert{No ordering of keys!} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Dictionaries \ldots} +\begin{lstlisting} +In []: mtdict = {} +In []: d = {'png' : 'image file', + 'txt' : 'text file', + 'py' : 'python code', + 'java': 'bad code', + 'cpp': 'complex code'} + +In []: d['txt'] +Out[]: 'text file' + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Dictionaries \ldots} + \begin{lstlisting} +In []: 'py' in d +Out[]: True + +In []: 'jpg' in d +Out[]: False + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Dictionaries \ldots} + \begin{small} + \begin{lstlisting} +In []: list(d.keys()) +Out[]: ['cpp', 'py', 'txt', 'java', 'png'] + +In []: list(d.values()) +Out[]: ['complex code', 'python code', + 'text file', 'bad code', + 'image file'] + \end{lstlisting} + \end{small} +%% \inctime{10} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Inserting elements} + \emphbar{\alert{\typ{d[key] = value}}} + \begin{lstlisting} +In []: d['bin'] = 'binary file' +In []: d +Out[]: +{'bin': 'binary file', + 'cpp': 'complex code', + 'java': 'bad code', + 'png': 'image file', + 'py': 'python code', + 'txt': 'text file'} + \end{lstlisting} + \emphbar{\alert{Duplicate keys are overwritten!}} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Adding \& Removing Elements} + \begin{itemize} + \item Adding a new key-value pair + \end{itemize} + \begin{lstlisting} + In[]: d['c++'] = 'C++ code' + In[]: d + \end{lstlisting} + \begin{itemize} + \item Deleting a key-value pair + \end{itemize} + \begin{lstlisting} + In[]: del d['java'] + In[]: d + \end{lstlisting} + \begin{itemize} + \item Assigning to existing key, modifies the value + \end{itemize} + \begin{lstlisting} + In[]: d['cpp'] = 'C++ source code' + In[]: d + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Dictionaries: methods} +\begin{lstlisting} +In []: d.keys() +In []: d.values() +In []: d.get('bin') +Out[]: 'binary file' +In []: d.get('junk') # No error! + +In []: d.update({'bin': 'Binary file', +.....: 'exe': 'executable'}) +In []: d.clear() +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Dictionaries: containership} + \begin{lstlisting} +In []: 'bin' in d +Out[]: True + +In []: 'hs' in d +Out[]: False + \end{lstlisting} + \begin{block}{Note} + \begin{itemize} + \item We can check for the containership of keys only + \item Not values + \end{itemize} + \end{block} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Dictionaries: iteration} + \begin{lstlisting} +In []: for v in d: +.....: print(v) +.....: + +In []: for v in d.values(): +.....: print(v) +.....: + +In []: for k, v in d.items(): +.....: print(k, v) +.....: + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{dict} built-in} +Like \typ{list, tuple} can also create dicts like so: +\begin{lstlisting} +In []: d = dict(png='image file', +.....: txt='text file', +.....: py='python code') +\end{lstlisting} +\begin{itemize} +\item Check more of the dictionary methods yourself +\end{itemize} +\end{frame} + +\begin{frame} {Problem 2.1} + + You are given date strings of the form ``29 Jul, 2009'', or ``4 January + 2008''. In other words a number, a string and another number, with a comma + sometimes separating the items. + + Write a program that takes such a string as input and prints a tuple (yyyy, + mm, dd) where all three elements are ints. +\end{frame} + +\begin{frame}[fragile] + \frametitle{Some hints} + \begin{itemize} + \item Simplify the problem + \item Try to explain how someone can do it + \vspace*{2em} + + \item Replace ',' with space + \item \typ{string.split()} method is your friend + \item Need a mapping from month (string) to a number: use a dict + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Partial solution} +\begin{lstlisting} +month2mm = {'jan': 1, 'feb': 2, #... + } +date = input('Enter a date string: ') +date = date.replace(',', ' ') +day, month, year = date.split() +dd, yyyy = int(day), int(year) +mon = month[:3].lower() +mm = month2mm[mon] +print((yyyy, mm, dd)) +\end{lstlisting} +\end{frame} + +\subsection{Sets} +\begin{frame}[fragile] + \frametitle{Sets} + \begin{itemize} + \item Conceptually identical to the sets in mathematics + \item Simplest container, mutable + \item No ordering, no duplicates + \item usual suspects: union, intersection, subset \ldots + \item >, >=, <, <=, in, \ldots + \end{itemize} + \begin{lstlisting} + In[]: a_list = [1, 2, 1, 4, 5, 6, 2] + In[]: a = set(a_list) + In[]: a + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] + \frametitle{Operations on Sets} + \begin{lstlisting} + In []: f10 = set([1, 2, 3, 5, 8]) + In []: p10 = set([2, 3, 5, 7]) + \end{lstlisting} + \begin{itemize} + \item Mathematical operations can be performed on sets + \end{itemize} + \begin{itemize} + \item Union + \begin{lstlisting} + In []: f10 | p10 + \end{lstlisting} + \item Intersection + \begin{lstlisting} + In []: f10 & p10 + \end{lstlisting} + \item Difference + \begin{lstlisting} + In []: f10 - p10 + \end{lstlisting} + \item Symmetric Difference +\begin{lstlisting} + In []: f10 ^ p10 + \end{lstlisting} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Sub-sets} + \begin{itemize} + \item Proper Subset + \begin{lstlisting} + In[]: b = set([1, 2]) + In[]: b < f10 + \end{lstlisting} + \item Subsets + \begin{lstlisting} + In[]: f10 <= f10 + \end{lstlisting} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Elements of sets} + \begin{itemize} + \item Containership + \begin{lstlisting} + In[]: 1 in f10 + In[]: 4 in f10 + \end{lstlisting} + \item Iterating over elements + \begin{lstlisting} + In[]: for i in f10: + ....: print(i) + ....: + \end{lstlisting} + \item Subsets + \begin{lstlisting} + In[]: f10 <= f10 + \end{lstlisting} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Problem 2.2} + Given a dictionary of the names of students and their marks, + + \begin{enumerate} + \item identify how many duplicate marks are there? + \item and what are these duplicate marks? + \end{enumerate} + +\end{frame} + +\begin{frame} + \frametitle{Hints} + \begin{itemize} + \item Use a set to find the unique marks: first part + \item Second part can be done in a few different ways + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Possible solution} +\begin{lstlisting} +students = {'x': 60, 'y': 60, 'z': 55} +all_marks = list(students.values()) +unique = set(all_marks) +n_dups = len(all_marks) - len(unique) +print(n_dups, 'duplicates') + +# Part 2 +for i in unique: + all_marks.remove(i) +print('Duplicates are', set(all_marks)) +\end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{What did we learn?} + \begin{itemize} + \item Core Python data structures: + \begin{itemize} + \item Lists + \item Tuples + \item Dictionaries + \item Sets + \end{itemize} + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Homework} + + \begin{itemize} + \item Explore all the methods of the various data structures you have seen + so far. + \item Read the documentation for each of these methods. + \item Solve all problems discussed + \end{itemize} +\end{frame} + +\end{document} + +%% Questions for Quiz %% +%% ------------------ %% + +\begin{frame} + \frametitle{\incqno} + How do you find the presence of an element \emph{x} in the list \emph{a}? +\end{frame} + + +\begin{frame}[fragile] + \frametitle{\incqno} + \begin{lstlisting} +In []: set([1, 2, 8, 2, 13, 8, 9]) + \end{lstlisting} + What is the output? +\end{frame} + +\begin{frame}[fragile] + \frametitle{\incqno} + \begin{lstlisting} +In []: a = {'a': 1, 'b': 2} +In []: a['a'] = 10 +In []: print(a) + \end{lstlisting} + What is the output? +\end{frame} + +\begin{frame}[fragile] + \frametitle{\incqno} + \begin{lstlisting} +In []: for i in range(3, 10, 2): + ...: print(i) + \end{lstlisting} + What is the output? +\end{frame} + +\begin{frame}[fragile] + \frametitle{\incqno} + \begin{lstlisting} +In []: a = [1, 2, 3] +In []: a.extend([5, 6]) + \end{lstlisting} + What is the value of a? +\end{frame} + +\begin{frame}[fragile] + \frametitle{\incqno} + \begin{lstlisting} +In []: a = (1, 2, 3) +In []: a[1] = 10 + \end{lstlisting} + What is the result? +\end{frame} + +\begin{frame}[fragile] + \frametitle{\incqno} + \begin{lstlisting} +def func(x, y=10): + print x+1, y+10 + +func(1) + + \end{lstlisting} + What is the output? +\end{frame} diff --git a/basic_python/06_practice_ds.tex b/basic_python/06_practice_ds.tex new file mode 100644 index 0000000..50ebf7e --- /dev/null +++ b/basic_python/06_practice_ds.tex @@ -0,0 +1,411 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Tutorial slides on Python. +% +% Author: FOSSEE +% Copyright (c) 2017, FOSSEE, IIT Bombay +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} + +\input{macros.tex} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Basic Python]{Practice exercises: data structures} + +\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}[fragile,plain] + \frametitle{Note: Python 2.x and 3.x} + + If you are using Python 2.x + \begin{itemize} + \item Use \typ{raw\_input} instead of \typ{input} + \item Use the following for \typ{print} + \end{itemize} + \begin{lstlisting} +from __future__ import print_function +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: simple list creation} + \begin{enumerate} + \item Ask the user to enter an integer, \typ{n} + \item Create a list of integers from 0 to \typ{n-1} + \item Print this list + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + n = int(input()) + x = list(range(n)) + print(x) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: more list creation} + \begin{enumerate} + \item Ask the user to enter an integer, \typ{n} + \item Store the square of all the odd numbers less than \typ{n} in a list + \item Print this list + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + n = int(input()) + result = [] + for i in range(1, n, 2): + result.append(i*i) + print(result) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: tuple creation} + \begin{enumerate} + \item Ask the user to enter an integer, \typ{n} + \item Store the square of all the odd numbers less than \typ{n} + \item Print a tuple of this list + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + n = int(input()) + result = [] + for i in range(1, n, 2): + result.append(i*i) + print(tuple(result)) +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain,fragile] + \frametitle{Hint: string to list/tuple} + Here is an easy way to convert a string to a list of characters. + + Try this: + \begin{lstlisting} + In []: x = 'hello' + In []: print(list(x)) + In []: print(tuple(x)) + \end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: list of Fibonacci} + \begin{enumerate} + \item Ask the user to enter an integer, \typ{n} ($\geq 1$) + \item Store the first \typ{n} numbers of the Fibonnaci series in a list + \item Print this list + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + n = int(input()) + a, b = 0, 1 + result = [0] + for i in range(n-1): + result.append(b) + a, b = b, a+b + print(result) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain,fragile] + \frametitle{Exercise: square a list of integers} + \begin{enumerate} + \item Ask the user to enter a list of integers separated by spaces + \item Convert this into a list of integers but square each element + \item Print this list + \end{enumerate} + For example, if the user enters \typ{1 2 3 4}, print: + \begin{lstlisting} + [1, 4, 9, 16] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + text = input() + result = [] + for item in text.split(): + x = int(item) + result.append(x*x) + print(result) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain,fragile] + \frametitle{Exercise: list of tuples} + \begin{enumerate} + \item Ask the user to enter a list of integers separated by spaces + \item Convert this into a list of integers but square each element + \item Store the integer and its square in a tuple, put this into a list + \item Print this list + \end{enumerate} + For example, if the user enters \typ{1 2 3 4}, print: + \begin{lstlisting} + [(1, 1), (2, 4), (3, 9), (4, 16)] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + text = input() + result = [] + for item in text.split(): + x = int(item) + result.append((x, x*x)) + print(result) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain,fragile] + \frametitle{Hint: iterating over a list of tuples} + Consider the following code: + \begin{small} + \begin{lstlisting} +In []: data = [(1, 1), (2, 4), (3, 9), (4, 16)] +\end{lstlisting} +\end{small} +We can iterate over this as follows: +\begin{small} +\begin{lstlisting} +In []: for x, y in data: +.....: print(x, y) +\end{lstlisting} +\end{small} +\end{frame} + + +\begin{frame}[plain,fragile] + \frametitle{Exercise: list methods} + \begin{enumerate} + \item Ask the user to enter a string + \item Convert this into a list of characters + \item Sort this list in ascending order + \item Now eliminate any repeated values in this list + \item Print this list + \end{enumerate} + For example, if the user enters \typ{hello}, print: + \begin{lstlisting} + ['e', 'h', 'l', 'o'] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + text = input() + chars = list(text) + chars.sort() + result = [] + for c in chars: + if c not in result: + result.append(c) + print(result) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Another solution} +\begin{lstlisting} + text = input() + chars = set(text) + chars = list(chars) + chars.sort() + print(chars) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Another solution} +\begin{lstlisting} + chars = set(input()) + print(sorted(chars)) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain,fragile] + \frametitle{Exercise: simple dictionaries} + \begin{enumerate} + \item Ask the user for a list of integers separated by spaces + \item For each integer, store the string version as the key and the square of + the integer value as the value in a dictionary. + \item Print the resulting dictionary + \end{enumerate} +For example if the user enters "1 3 5", print: +\begin{lstlisting} +{'1': 1, '3': 9, '5': 25} +\end{lstlisting} +Hint: simply print the resulting dictionary +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} +text = input() +d = {} +for item in text.split(): + x = int(item) + d[item] = x*x +print(d) +\end{lstlisting} +\end{frame} + + +\begin{frame}[fragile,plain,fragile] + \frametitle{Exercise: mapping using dicts} + \begin{enumerate} + \item Create a mapping from 3 character month name to month number + \item Hint: for example \typ{\{'jan': 1, 'dec': 12\}} + \item Ask the user for a 3 character month code lower/upper mixed + \item Print the month number corresponding to the month the user entered. + \end{enumerate} +For example if the user enters "Jul", print: +\begin{lstlisting} +7 +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} +months = ('jan feb mar apr may jun jul ' + + 'aug sep oct nov dec').split() +month2mm = {} +for i in range(len(months)): + month2mm[months[i]] = i + 1 + +text = input() +mon = text[:3].lower() +print(month2mm[mon]) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Aside: using \typ{enumerate} example} +\begin{lstlisting} +for i, char in enumerate('hello'): + print(i, char) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Aside: using \typ{enumerate}} +\begin{lstlisting} +months = ('jan feb mar apr may jun jul ' + + 'aug sep oct nov dec').split() +month2mm = {} +for i, month in enumerate(months): + month2mm[month] = i + 1 + +# Is easier/nicer than this: + +for i in range(len(months)): + month2mm[months[i]] = i + 1 +\end{lstlisting} + +\end{frame} + + + +\begin{frame}[plain,fragile] + \frametitle{Exercise: dictionaries} + \begin{enumerate} + \item Ask the user to enter a string + \item Convert this to lower case + \item Count the number of occurrences of each character in the string + \item Hint: use a dict + \item Print the result in sorted order of the characters + \end{enumerate} + For example, if the user enters \typ{helloo}, print: + \begin{lstlisting} + e 1 + h 1 + l 2 + o 2 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + text = input().lower() + result = {} + for char in text: + if char in result: + result[char] += 1 + else: + result[char] = 1 + + for char in sorted(result): + print(char, result[char]) +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain] + {Problem: datestring to date tuple} + + You are given date strings of the form ``29 Jul, 2009'', or ``4 January + 2008''. In other words a number, a string and another number, with a comma + sometimes separating the items. + + Write a program that takes such a string as input and prints a tuple (yyyy, + mm, dd) where all three elements are ints. +\end{frame} + +\begin{frame}[fragile] + \frametitle{Solution} + \small + \begin{lstlisting} +months = ('jan feb mar apr may jun jul ' + + 'aug sep oct nov dec').split() +month2mm = {} +for i, month in enumerate(months): + month2mm[month] = i + 1 + +date = input() +date = date.replace(',', ' ') +day, month, year = date.split() + +dd, yyyy = int(day), int(year) +mon = month[:3].lower() +mm = month2mm[mon] +print((yyyy, mm, dd)) +\end{lstlisting} +\end{frame} + +\begin{frame} + \centering + \Huge + + That's all folks! +\end{frame} +\end{document} diff --git a/basic_python/07_functions.tex b/basic_python/07_functions.tex new file mode 100644 index 0000000..7213fea --- /dev/null +++ b/basic_python/07_functions.tex @@ -0,0 +1,435 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%Tutorial slides on Python. +% +% Author: FOSSEE +% Copyright (c) 2017, FOSSEE, IIT Bombay +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} +\input{macros.tex} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Functions]{Python language: Functions} + +\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} + +\section{Functions} + +\begin{frame}[fragile] + \frametitle{Functions for abstraction} + \begin{itemize} + \item Reduce duplication of code + \item Fewer lines of code: lesser scope for bugs + \item Re-usability of code + \item Use functions written by others, without exactly knowing how + they do, what they are doing + \item \alert{Enter Functions!} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Defining functions} + \begin{itemize} + \item Consider the function \texttt{f(x) = x\textasciicircum{}2} + \item In Python: + \end{itemize} + \begin{lstlisting} + In []: def f(x): + .....: return x*x + .....: + In []: f(1) + In []: f(1+2j) + \end{lstlisting} + \begin{itemize} + \item \typ{def} is a keyword + \item \typ{f} is the name of the function + \item \typ{x} the parameter of the function + \item \typ{return} is a keyword + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Defining functions \ldots} + \begin{lstlisting} + In []: def greet(): + .....: print("Hello World!") + .....: + + In []: greet() + \end{lstlisting} + \begin{itemize} + \item \texttt{greet} is a function that takes no arguments + \item It returns nothing explicitly + \item Implicitly, Python returns \typ{None} + \item \typ{None} is also a built-in, immutable data type + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Defining functions \ldots} + \begin{lstlisting} + In []: def avg(a, b): + .....: return (a + b)/2 + .....: + + In []: avg(12, 10) +\end{lstlisting} +\begin{itemize} +\item \typ{avg} takes two arguments +\item Returns one value +\end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Doc-strings} + \begin{itemize} + \item It's highly recommended that all functions have documentation + \item We write a doc-string along with the function definition + \end{itemize} + \begin{lstlisting} +def avg(a, b): + """Returns the average of two + given numbers.""" + return (a + b)/2 + +In[]: avg? +In[]: greet? + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Returning multiple values} + \begin{itemize} + \item Return area and perimeter of circle, given radius + \item Function needs to return two values + \end{itemize} + \begin{lstlisting} +def circle(r): + """Returns area and perimeter of + circle given radius r""" + pi = 3.14 + area = pi * r * r + perimeter = 2 * pi * r + return area, perimeter + +In []: circle(4) +In []: a, p = circle(6) + \end{lstlisting} +\end{frame} + + +\subsection{Default \& Keyword Arguments} + +\begin{frame}[fragile] + \frametitle{Default arguments} + \begin{lstlisting} +In []: round(2.484) +In []: round(2.484, 2) + +In []: s.split() # split on spaces +In []: s.split(';') # split on ';' + +In []: range(10) +In []: range(1, 10) +In []: range(1, 10, 2) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Default arguments \ldots} + \begin{lstlisting} +In []: def welcome(greet, name="World"): +.....: print(greet, name) +.....: + +In []: welcome("Hi", "Guido") +In []: welcome("Hello") + \end{lstlisting} +\end{frame} +\begin{frame}[fragile] + \frametitle{Default arguments \ldots} + \begin{itemize} + \item Arguments with default values, should be placed at the end + \item The following definition is \alert{WRONG} + \end{itemize} + \begin{lstlisting} +In []: def welcome(name="World", greet): +.....: print(greet, name) +.....: + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] + \frametitle{Keyword Arguments} + \begin{lstlisting} +In []: def welcome(greet, name="World"): +.....: print(greet, name) +.....: + +In []: welcome("Hello", "James") + +In []: welcome("Hi", name="Guido") + +In []: welcome(name="Guido",greet="Hey") + +In []: welcome(name="Guido", "Hey") +\end{lstlisting} +Cannot have non-keyword args after kwargs +\end{frame} + +\begin{frame}[fragile] + \frametitle{Built-in functions} + \begin{itemize} + \item Variety of built-in functions are available + \item \typ{abs, any, all, len, max, min} + \item \typ{pow, range, sum, type} + \item Refer here: + \url{http://docs.python.org/library/functions.html} + \end{itemize} +\end{frame} + +\subsection{Variable Scope} + +\begin{frame}[fragile] + \frametitle{Arguments are local} + \begin{lstlisting} + In []: def change(q): + .....: q = 10 + .....: print(q) + .....: + + In []: change(1) + In []: print(q) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Variables inside function are local} + \begin{lstlisting} + In []: n = 5 + In []: def change(): + .....: n = 10 + .....: print(n) + .....: + In []: change() + In []: print(n) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{If not defined, look in parent scope} + \begin{lstlisting} + In []: n = 5 + In []: def scope(): + .....: print(n) + .....: + In []: scope() +\end{lstlisting} +\begin{itemize} +\item Note that \typ{n} was not defined in \typ{scope} +\item It looked for the variable in previous scope +\item See: \url{pythontutor.com} +\end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{global}} + \begin{itemize} + \item Use the \texttt{global} statement to assign to global variables + \end{itemize} + \begin{lstlisting} + In[]: def change(): + ....: global n + ....: n = 10 + ....: print(n) + ....: + In[]: change() + In[]: print(n) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Mutable variables} + \begin{itemize} + \item Behavior is different when assigning to a list element/slice + \item Python looks up for the name, from innermost scope outwards, + until the name is found + \end{itemize} + \begin{lstlisting} +In []: name = ['Mr.', 'Steve','Gosling'] +In []: def change_name(): +.....: name[0] = 'Dr.' +.....: +In []: change_name() +In []: print(name) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Passing Arguments \ldots} + \begin{lstlisting} +In []: n = 5 +In []: def change(n): +.....: n = 10 +.....: print(n, "inside change") +.....: +In []: change(n) +In []: print(n) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Passing Arguments \ldots} +\begin{lstlisting} +In []: name = ['Mr.', 'Steve','Gosling'] +In []: def change_name(x): +.....: x[0] = 'Dr.' +.....: print(x, 'in change') +.....: +In []: change_name(name) +In []: print(name) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Passing Arguments \ldots} +\begin{lstlisting} +In []: name = ['Mr.', 'Steve','Gosling'] +In []: def change_name(x): +.....: x = [1,2,3] +.....: print(x, 'in change') +.....: +In []: change_name(name) +In []: print(name) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Passing Arguments \ldots} +\begin{lstlisting} +In []: name = ['Mr.', 'Steve','Gosling'] +In []: def change_name(x): +.....: x[:] = [1,2,3] +.....: print(x, 'in change') +.....: +In []: change_name(name) +In []: print(name) + \end{lstlisting} +\end{frame} + + +\subsection{Examples} + +\begin{frame}[fragile] + \frametitle{Functions: example} + \begin{lstlisting} +def signum( r ): + """returns 0 if r is zero + -1 if r is negative + +1 if r is positive""" + if r < 0: + return -1 + elif r > 0: + return 1 + else: + return 0 + \end{lstlisting} + \emphbar{Note docstrings} +\end{frame} + +\begin{frame}[fragile] + \frametitle {What does this function do?} + \begin{lstlisting} +def what(n): + if n < 0: n = -n + while n > 0: + if n % 2 == 1: + return False + n /= 10 + return True + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{What does this function do?} +\begin{lstlisting} +def what(n): + i = 1 + while i * i < n: + i += 1 + return i * i == n, i + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle {What does this function do?} + \begin{lstlisting} +def what(x, n): + if n < 0: + n = -n + x = 1.0 / x + + z = 1.0 + while n > 0: + if n % 2 == 1: + z *= x + x *= x + n //= 2 + return z + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Nested functions} + \begin{lstlisting} + def f(x): + def g(x): + return x+1 + return g(x)**2 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Nested functions: returning functions} + \begin{lstlisting} + def f(): + def g(x): + return x+1 + return g + + In []: func = f() + In []: func(1) + In []: f()(1) # Also valid! + \end{lstlisting} +\end{frame} + + +\begin{frame} + \frametitle{Summary} + \begin{itemize} + \item Defining functions + \item Taking either 0, or more arguments + \item Returning \typ{None} implicitly or any number of values + \item Default and keyword arguments + \item Variable scope, \typ{global} + \item Mutable and immutable arguments + \item Nested functions + \end{itemize} +\end{frame} + +\end{document} diff --git a/basic_python/08_practice_functions.tex b/basic_python/08_practice_functions.tex new file mode 100644 index 0000000..d71168c --- /dev/null +++ b/basic_python/08_practice_functions.tex @@ -0,0 +1,357 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Tutorial slides on Python. +% +% Author: FOSSEE +% Copyright (c) 2017, FOSSEE, IIT Bombay +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} + +\input{macros.tex} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Basic Python]{Practice exercises: functions} + +\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}[fragile,plain] + \frametitle{Note: Python 2.x and 3.x} + + If you are using Python 2.x + \begin{itemize} + \item Use \typ{raw\_input} instead of \typ{input} + \item Use the following for \typ{print} + \end{itemize} + \begin{lstlisting} +from __future__ import print_function +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: function without arguments} + \begin{enumerate} + \item Define a function called \typ{prompt} + \item The function should ask the user to enter their name (no prompt) + \item The function should not take any arguments + \item The function should not return anything + \item The function should print \typ{Hello } + \end{enumerate} + For example if the user enters \typ{Sam}, print: + Hello Sam +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + def prompt(): + name = input() + print('Hello', name) +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: function with one argument} + \begin{enumerate} + \item Define a function called \typ{prompt} + \item The function should take a single string argument + \item \textbf{Do not ask the user for input, i.e. do not use input} + \item The function should not return anything + \item The function should print \typ{Hello } + \end{enumerate} + For example if the function is passed \typ{'Sam'}, print: + Hello Sam +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + def prompt(name): + print('Hello', name) +\end{lstlisting} +\end{frame} + + +\begin{frame}[plain,fragile] + \frametitle{Exercise: function with \typ{return}} + \begin{enumerate} + \item Define a function called \typ{prompt} + \item The function should take a single string argument + \item The function should return a string with \typ{'Hello'} + \item \textbf{Do not use input} + \item \textbf{Do not print anything} + \end{enumerate} + For example if the function is passed \typ{'Sam'}, return: + \begin{lstlisting} + 'Hello Sam' + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + def prompt(name): + return 'Hello ' + name +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: function with two args} + \begin{enumerate} + \item Define a function called \typ{add} + \item The function should take two arguments + \item The function should return the sum of the two arguments + \item \textbf{Do not use input} + \item \textbf{Do not print anything} + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + def add(a, b): + return a + b +\end{lstlisting} +\end{frame} + +\begin{frame}[plain] + \frametitle{Exercise: function returning boolean} + \begin{enumerate} + \item Define a function called \typ{is\_even} + \item The function should take a single integer argument + \item The function should return \typ{True} if the number is even and \typ{False} otherwise + \item \textbf{Do not use input} + \item \textbf{Do not print anything} + \end{enumerate} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Naive Solution} +\begin{lstlisting} + def is_even(x): + if x%2 == 0: + return True + else: + return False +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Elegant Solution} +\begin{lstlisting} + def is_even(x): + return x%2 == 0 +\end{lstlisting} +\end{frame} + +\begin{frame}[plain,fragile] + \frametitle{Exercise: function returning two values} + \begin{enumerate} + \item Define a function called \typ{even\_square} + \item The function should take a single argument + \item The function should return if the number is even and the square of the number + \item \textbf{Do not use input} + \item \textbf{Do not print anything} + \end{enumerate} + For example: + \begin{lstlisting} + In []: even_square(2) + Out[]: (True, 4) + In []: even_square(3) + Out[]: (False, 9) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] + \frametitle{Solution} + \begin{lstlisting} + def even_square(x): + return x%2 == 0, x*x + \end{lstlisting} +\end{frame} + + +\begin{frame}[plain,fragile] + \frametitle{Exercise: default arguments} + \begin{enumerate} + \item Define a function called \typ{greet} + \item The function should take one positional argument, \typ{name} + \item The function should take one optional argument, \typ{message} + \item If \typ{message} is not given, it should default to \typ{'Hello'} + \item It should return the string with the greeting + \end{enumerate} + For example: + \begin{lstlisting} + In []: greet('Sam') + Out[]: 'Hello Sam' + In []: greet('Sam', 'Hi') + Out[]: 'Hi Sam' + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] + \frametitle{Solution} + \begin{lstlisting} + def greet(name, message='Hello'): + return message + ' ' + name + \end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Exercise: functions and lists} + \begin{enumerate} + \item Define a function called \typ{to\_lower} + \item The function should take a single list of strings + \item The function should return the list of strings but all in lowercase + \item \textbf{Do not use input} + \item \textbf{Do not print anything} + \end{enumerate} + For example: + \begin{lstlisting} +In []: to_lower(['I', 'am', 'Batman']) +Out[]: ['i', 'am', 'batman'] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + def to_lower(data): + result = [] + for x in data: + result.append(x.lower()) + return result +\end{lstlisting} +\end{frame} + +\begin{frame}[plain,fragile] + \frametitle{Exercise: list of Fibonacci} + \begin{enumerate} + \item Define a function called \typ{fib} taking one argument \typ{n} + \item Where, \typ{n>0} is an integer but defaults to 8 + \item Return the first \typ{n} terms of the Fibonacci sequence + \end{enumerate} + For example: + \begin{lstlisting} + In []: fib(4) + Out[]: [0, 1, 1, 2] + In []: fib() + Out[]: [0, 1, 1, 2, 3, 5, 8, 13] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + def fib(n=8): + a, b = 0, 1 + result = [0] + for i in range(n-1): + result.append(b) + a, b = b, a+b + return result +\end{lstlisting} +\end{frame} + +\begin{frame}[plain,fragile] + \frametitle{Exercise: returning a function} + \begin{enumerate} + \item Define a function called \typ{power2()} which takes no argument + \item It should return a function which takes a single argument \typ{x} but + returns $2^x$ + \end{enumerate} + For example: + \begin{lstlisting} + In []: f = power2() + In []: f(2) + Out[]: 4 + In []: power2()(4) + Out[]: 16 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] +\frametitle{Solution} +\begin{lstlisting} + def power2(): + def f(x): + return 2**x + return f +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile,plain] + \frametitle{Another solution} + \begin{lstlisting} + def power(n=2): + def f(x): + return n**x + return f + \end{lstlisting} + \begin{itemize} + \item This is called a closure. + \item Note that \typ{f} ``stores'' the value of \typ{n} + \end{itemize} + \pause + \begin{lstlisting} + In []: p2 = power(2) + In []: p3 = power(3) + In []: p2(2) + Out[]: 4 + In []: p3(2) + Out[]: 9 + \end{lstlisting} +\end{frame} + +\begin{frame}[plain,fragile] + \frametitle{Exercise: function as an argument} + \begin{enumerate} + \item Define a function called \typ{apply(f, data)} + \item Where \typ{f} is a function taking a single value + \item Where \typ{data} is a list + \item It should return a list where the function is applied to each element + of \typ{data} + \end{enumerate} + For example: + \begin{lstlisting} + In []: def double(x): + .....: return 2*x + .....: + In []: apply(double, [1, 2, 3]) + Out[]: [2, 4, 6] + \end{lstlisting} +\end{frame} + +\begin{frame}[plain, fragile] + \frametitle{Solution} + \begin{lstlisting} + def apply(f, data): + result = [] + for x in data: + result.append(f(x)) + return result + \end{lstlisting} +\end{frame} + +\begin{frame} + \centering + \Huge + + That's all folks! +\end{frame} +\end{document} + +\end{document} diff --git a/basic_python/09_modules.tex b/basic_python/09_modules.tex new file mode 100644 index 0000000..57f720d --- /dev/null +++ b/basic_python/09_modules.tex @@ -0,0 +1,278 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%Tutorial slides on Python. +% +% Author: FOSSEE +% Copyright (c) 2017, FOSSEE, IIT Bombay +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} +\input{macros.tex} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Modules]{Python language: modules} + +\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} + +\section{Python modules} + +\begin{frame} + \frametitle{Modules} + \begin{itemize} + \item Organize your code + \item Collect similar functionality + \item Functions, classes, constants, etc. + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Modules} + \begin{itemize} + \item Define variables, functions and classes in a file with a + \texttt{.py} extension + \item This file becomes a module! + \item File name should be valid variable name + \end{itemize} +\end{frame} + +\begin{frame} + \frametitle{Modules \ldots} + \begin{itemize} + \item The \typ{import} keyword ``loads'' a module + \item One can also use: + \mbox{\typ{from module import name1, name2}}\\ + where \typ{name1} etc. are names in the module, \typ{module} + \item \typ{from module import *} \ --- imports everything from module, + \alert{use only in interactive mode} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Note on module file names} + \begin{itemize} + \item Should start with a letter or underscore + \item Can use \typ{\_} (underscore) and numbers + \item No \typ{.} allowed + \item No spaces or special characters + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Test} + \begin{itemize} + \item \typ{1\_script.py} + \item \typ{script\_1.py} + \item \typ{one11.py} + \item \typ{\_one11.py} + \item \typ{one script.py} + \item \typ{one,script;xxx.py} + \item \typ{one.two.py} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: example} + \begin{lstlisting} +# --- fib.py --- +some_var = 1 +def fib(n): + """Print Fibonacci series up to n. + """ + a, b = 0, 1 + while b < n: + print(b, end=' ') + a, b = b, a+b +# EOF + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: example} + \begin{lstlisting} +>>> import fib +>>> fib.fib(10) +1 1 2 3 5 8 +>>> fib.some_var +1 + \end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Python path} + \begin{itemize} + \item In IPython type the following + \end{itemize} + \begin{lstlisting} + import sys + sys.path + \end{lstlisting} + \begin{itemize} + \item List of locations where python searches for a module + \item \texttt{import sys} -- searches for file \texttt{sys.py} or + dir \texttt{sys} in all these locations + \item Modules can be in any one of the locations + \item Current working directory is one of the locations + \item Can also set \texttt{PYTHONPATH} env var + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Running a module} + \begin{itemize} + \item Let us say we want to run some code in \typ{fib.py} so we get: + \end{itemize} + \begin{lstlisting} + $ python fib.py + 1 1 2 3 5 8 + \end{lstlisting} %$ + +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: Running a module} + \begin{lstlisting} +# --- fib.py --- +some_var = 1 +def fib(n): + """Print Fibonacci series up to n. + """ + a, b = 0, 1 + while b < n: + print(b, end=' ') + a, b = b, a+b + +fib(10) +# EOF + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: example} + \begin{lstlisting} +>>> import fib +1 1 2 3 5 8 +\end{lstlisting} + +\begin{itemize} +\item So the code is called even when we import the module +\item We do not want this! +\end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Using \texttt{\_\_name\_\_}} + \begin{lstlisting} + import fib + \end{lstlisting} + \begin{itemize} + \item The import is successful + \item But \typ{fib(10)}, gets run + \pause + \item Add it to the following \texttt{if} block + \end{itemize} + \begin{lstlisting} + if __name__ == "__main__": + fib(10) + \end{lstlisting} + \begin{itemize} + \item Now the script runs properly + \item As well as the import works; the code is not executed + \item \texttt{\_\_name\_\_} is local to every module and is equal + to \texttt{'\_\_main\_\_'} only when the file is run as a script. + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Modules: using \typ{\_\_name\_\_}} + \vspace*{-1ex} + \begin{lstlisting} +# --- fib.py --- +def fib(n): + """Print Fibonacci series up to n. + """ + a, b = 0, 1 + while b < n: + print(b, end=' ') + a, b = b, a+b + +print(__name__) +if __name__ == '__main__': + fib(10) +# EOF + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Modules: using \typ{\_\_name\_\_}} + \begin{lstlisting} + >>> import fib + \end{lstlisting} + Try this: + \begin{lstlisting} + $ python fib.py + \end{lstlisting} %$ +\end{frame} + +\begin{frame}[fragile] + \frametitle{Stand-alone scripts} +Consider a file \texttt{f.py}: +\footnotesize +\begin{lstlisting} +#!/usr/bin/env python +"""Module level documentation.""" +# First line tells the shell that it should use Python +# to interpret the code in the file. +def f(): + print "f" + +# Check if we are running standalone or as module. +# When imported, __name__ will not be '__main__' +if __name__ == '__main__': + # This is not executed when f.py is imported. + f() +\end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Standard library} + \begin{itemize} + \item Operating system interface: \typ{os}, \typ{os.path} + \item System, Command line arguments: \typ{sys} + \item Regular expressions: \typ{re} + \item Math: \typ{math}, \typ{random} + \item Internet access: \typ{urllib}, \typ{smtplib} + \item Data compression: \typ{zlib}, \typ{gzip}, \typ{bz2}, + \typ{zipfile}, and \typ{tarfile} + \item Unit testing: \typ{doctest} and \typ{unittest} + \item And a whole lot more! + \item Check out the Python Library reference: + \url{http://docs.python.org/lib/lib.html} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Summary} + \begin{itemize} + \item Creating modules + \item Importing modules + \item Running modules as scripts + \item \texttt{\_\_name\_\_} + \end{itemize} +\end{frame} + +\end{document} diff --git a/basic_python/10_files.tex b/basic_python/10_files.tex new file mode 100644 index 0000000..14ee6f6 --- /dev/null +++ b/basic_python/10_files.tex @@ -0,0 +1,294 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%Tutorial slides on Python. +% +% Author: FOSSEE +% Copyright (c) 2017, FOSSEE, IIT Bombay +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +\documentclass[14pt,compress]{beamer} +\input{macros.tex} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Title page +\title[Files]{Python language: reading/writing files} + +\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} + +\section{Reading files} + +\begin{frame}[fragile] + \frametitle{Opening files} + Recall: + \begin{lstlisting} +% pwd # present working directory +% cd /home/fossee # go to directory + \end{lstlisting} + {\small The file is in our present working directory} + \begin{lstlisting} + In []: f = open('pendulum.txt') + In []: f + \end{lstlisting} + \begin{itemize} + \item \texttt{f} is a file object + \item Shows the mode in which the file is open (read mode) + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Reading the whole file} + \begin{lstlisting} + In []: pend = f.read() + In []: print(pend) + \end{lstlisting} + \begin{itemize} + \item We have read the whole file into the variable \texttt{pend} + \end{itemize} + \begin{lstlisting} + In []: type(pend) + In []: pend_list = pend.splitlines() + In []: pend_list + \end{lstlisting} + \begin{itemize} + \item \texttt{pend} is a string variable + \item We can split it at the newline characters into a list of + strings + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Closing the file} + \begin{itemize} + \item Close the file, when done; Also, if you want to read again + \end{itemize} + \begin{lstlisting} + In []: f.close() + In []: f + \end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Reading line-by-line} + \begin{lstlisting} +In []: for line in open('pendulum.txt'): +.....: print(line) + \end{lstlisting} + \begin{itemize} + \item The file object is an ``iterable'' + \item We iterate over it and print each line + \item Instead of printing, collect lines in a list + \end{itemize} + \begin{lstlisting} +In []: line_list = [ ] +In []: for line in open('pendulum.txt'): +.....: line_list.append(line) + \end{lstlisting} +\end{frame} + +\section{Writing files} + +\begin{frame}[fragile] + \frametitle{Writing files} + \begin{lstlisting} +In []: f = open('new_file.txt', 'w') +In []: f.write('Hello world!\n') +In []: f.close() +\end{lstlisting} +\begin{itemize} +\item Note the mode \typ{'w'} +\item Will clobber existing file! +\item \typ{write} will not add new lines +\item Always remember to call \typ{close} +\end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Using print to write files} + \begin{small} + On Python 2.x + \begin{lstlisting} +In []: from __future__ import print_function +\end{lstlisting} +\hrule +\end{small} + + \begin{lstlisting} +In []: f = open('new_file.txt', 'w') +In []: print('Hello world!', file=f) +In []: f.close() +\end{lstlisting} +\begin{itemize} +\item Just pass the \typ{file} keyword arg +\item \typ{print} works normally, so adds new lines +\end{itemize} +\end{frame} + + +\section{Exercise: parsing data from file} + +\begin{frame}[fragile,plain] + \frametitle{File parsing -- Problem} + \begin{lstlisting} +A;010002;AMY A;058;037;42;35;40;212;P;; + \end{lstlisting} + \begin{itemize} + \item File with records like the one above is given + \item Each record has fields separated by \verb+;+ + \item region code; roll number; name; + \item marks --- $1^{st}$ L; $2^{nd}$ L; math; science; social; total + \item pass/fail indicated by P/F; W if withheld and else empty + \end{itemize} + + \begin{itemize} + \item We wish to calculate mean of math marks in region B + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Tokenization} + \begin{lstlisting} +In []: line = "parse this string" +In []: line.split() + \end{lstlisting} + \begin{itemize} + \item Original string is split on white-space + \item Returns a list of strings + \item It can be given an argument to split on that argument + \end{itemize} + \begin{lstlisting} +r = "A;01;JOSE R;083;042;47;AA;72;244;;;" +r.split(';') + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Tokenization \ldots} + \begin{itemize} + \item Since we split on commas, fields may have extra spaces at ends + \item We can strip out the spaces at the ends + \end{itemize} + \begin{lstlisting} + In []: word = " B " + In []: word.strip() + \end{lstlisting} + \begin{itemize} + \item \texttt{strip} is returning a new string + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{str} to \texttt{float}} + \begin{itemize} + \item After tokenizing, the marks we have are strings + \item We need numbers to perform math operations + \end{itemize} + \begin{lstlisting} + In []: mark_str = "1.25" + In []: mark = float(mark_str) + In []: type(mark_str) + In []: type(mark) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile, plain] + \frametitle{File parsing -- Solution} + \begin{lstlisting} +math_B = [] # empty list to store marks +for line in open("sslc1.txt"): + fields = line.split(";") + reg_code = fields[0] + reg_code = reg_code.strip() + + math_mark_str = fields[5] + math_mark = float(math_mark_str) + + if reg_code == "B": + math_B.append(math_mark) + +math_B_mean = sum(math_B) / len(math_B) +print(math_B_mean) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile, plain] + \frametitle{File parsing -- Solution} + An Error! + \small + \begin{lstlisting} +ValueError: could not convert string to float: AA + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile, plain] + \frametitle{File parsing -- debugging} + \begin{lstlisting} +math_B = [] # empty list to store marks +for line in open("sslc1.txt"): + fields = line.split(";") + reg_code = fields[0] + reg_code = reg_code.strip() + print(fields) # <-- Added + math_mark_str = fields[5] + math_mark = float(math_mark_str) + # ... + \end{lstlisting} +\end{frame} + + +\begin{frame}[fragile, plain] + \frametitle{File parsing -- debugging} + \small + \begin{lstlisting} +math_B = [] # empty list to store marks +for i, line in enumerate(open("sslc1.txt")): + fields = line.split(";") + reg_code = fields[0] + reg_code = reg_code.strip() + print(i, fields) # <-- Added + math_mark_str = fields[5] + math_mark = float(math_mark_str) + # ... + \end{lstlisting} +\end{frame} + + +\begin{frame}[fragile, plain] + \frametitle{File parsing -- Solution} + \begin{lstlisting} +math_B = [] # empty list to store marks +for line in open("sslc1.txt"): + fields = line.split(";") + reg_code = fields[0].strip() + m = fields[5] + mark = float(m) if m != 'AA' else 0 + if reg_code == "B": + math_B.append(mark) + +math_B_mean = sum(math_B) / len(math_B) +print(math_B_mean) + \end{lstlisting} +\end{frame} + +\begin{frame} + \frametitle{Summary} + \begin{itemize} + \item Reading files + \item Writing files + \item Simple file parsing + \end{itemize} +\end{frame} + +\end{document} diff --git a/basic_python/11_exceptions.tex b/basic_python/11_exceptions.tex new file mode 100644 index 0000000..8b9eb46 --- /dev/null +++ b/basic_python/11_exceptions.tex @@ -0,0 +1,292 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%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 "", 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 "", line 1, in +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 "", line 1, in +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 "", 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} + \small +\begin{lstlisting} +while True: + try: + data = input() + 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]) +except (ValueError, IndexError): + print("Invalid input ...") + +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\typ{try, except, else}} + \small +\begin{lstlisting} +while True: + try: + data = input() + x = int(data.split(',')[1]) + except (ValueError, IndexError): + print("Invalid input ...") + else: + print('All is well!') + break + \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 "", 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/12_practice_files_exc.tex b/basic_python/12_practice_files_exc.tex new file mode 100644 index 0000000..1eda602 --- /dev/null +++ b/basic_python/12_practice_files_exc.tex @@ -0,0 +1,217 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% 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 \typ{x} + \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} + \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} + + +\begin{frame} + \centering + \Huge + + Thank you! +\end{frame} +\end{document} + +\end{document} diff --git a/basic_python/Makefile b/basic_python/Makefile index 6310d3a..c7853b1 100644 --- a/basic_python/Makefile +++ b/basic_python/Makefile @@ -4,23 +4,23 @@ pdflatex $*.tex pdflatex $*.tex -SLIDES= basics.pdf \ - practice_basics.pdf \ - control_flow.pdf \ - practice_control_flow.pdf \ - core_data_structures.pdf \ - practice_ds.pdf \ - functions.pdf \ - practice_functions.pdf \ - modules.pdf \ - files.pdf \ - exceptions.pdf \ - practice_files_exc.pdf +SLIDES= 01_basics.pdf \ + 02_practice_basics.pdf \ + 03_control_flow.pdf \ + 04_practice_control_flow.pdf \ + 05_core_data_structures.pdf \ + 06_practice_ds.pdf \ + 07_functions.pdf \ + 08_practice_functions.pdf \ + 09_modules.pdf \ + 10_files.pdf \ + 11_exceptions.pdf \ + 12_practice_files_exc.pdf all: $(SLIDES) cleanall: - rm -f *.dvi *.log *.bak *.aux *.bbl *.blg *.idx *.ps *.eps *.pdf *.toc *.out *~ *.vrb *.nav *.snm + rm -f *.dvi *.log *.bak *.aux *.bbl *.blg *.idx *.ps *.eps *.pdf *.toc *.out *~ *.vrb *.nav *.snm *.synctex.gz clean: rm -f *.log *.bak *.aux *.bbl *.blg *.idx *.toc *.out *~ *.vrb *.nav *.snm *.synctex.gz diff --git a/basic_python/basics.tex b/basic_python/basics.tex deleted file mode 100644 index 28aa214..0000000 --- a/basic_python/basics.tex +++ /dev/null @@ -1,698 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009-2017, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} - -\input{macros.tex} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Basic Python]{Python language: Basics} - -\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} - \frametitle{Outline} - \tableofcontents - % You might wish to add the option [pausesections] -\end{frame} - -\section{Data types} - -\begin{frame} - \frametitle{Primitive Data types} - \begin{itemize} - \item Numbers: float, int, complex - \item Strings - \item Booleans - \end{itemize} -\end{frame} - -\subsection{Numbers} -\begin{frame}[fragile] - \frametitle{Numbers} - \begin{itemize} - \item \kwrd{int}\\ whole number, no matter what the size! - \begin{lstlisting} -In []: a = 13 - -In []: b = 99999999999999999999 - \end{lstlisting} - \item \kwrd{float} - \begin{lstlisting} -In []: p = 3.141592 - \end{lstlisting} - \item \kwrd{complex} - \begin{lstlisting} -In []: c = 3+4j -In []: c = complex(3, 4) - \end{lstlisting} - \end{itemize} -\end{frame} - -\subsection{Booleans} -\begin{frame}[fragile] - \frametitle{Booleans} - \begin{lstlisting} -In []: t = True - -In []: F = not t - -In []: F or t -Out[]: True - -In []: F and t -Out[]: False - \end{lstlisting} -%% \inctime{5} -\end{frame} - -\begin{frame}[fragile] - \frametitle{( ) for precedence} - \begin{lstlisting} -In []: a = False -In []: b = True -In []: c = True - -In []: (a and b) or c -Out[]: True - -In []: a and (b or c) -Out[]: False - \end{lstlisting} -%% \inctime{5} -\end{frame} - -\subsection{Strings} - -\begin{frame}[fragile] -\frametitle{Strings} -Anything within ``quotes'' is a string! -\begin{lstlisting} -' This is a string ' -" This too! " -""" This one too! """ -''' And one more! ''' -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] -\frametitle{Strings} -Why so many? -\begin{lstlisting} -' "Do or do not. No try." said Yoda.' -" ' is a mighty lonely quote." -\end{lstlisting} -The triple quoted ones can span multiple lines! - -\begin{lstlisting} -""" The quick brown -fox jumped over - the lazy dingbat. -""" -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Strings} - \begin{lstlisting} -In []: w = "hello" - -In []: print(w[0], w[1], w[-1]) - -In []: len(w) -Out[]: 5 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Strings \ldots} - \emphbar{Strings are immutable} - \begin{lstlisting} -In []: w[0] = 'H' - \end{lstlisting} - \pause - \begin{lstlisting} --------------------------------------------- -TypeError Traceback (most recent call last) - - in () - -TypeError: 'str' object does not - support item assignment - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Finding the type} -\begin{lstlisting} -In []: a = 1.0 -In []: type(a) -Out[]: float -In []: type(1) -Out[]: int - -In []: type(1+1j) -Out[]: complex - -In []: type('hello') -Out[]: str -\end{lstlisting} -\end{frame} - -\section{Operators} - -\begin{frame}[fragile] - \frametitle{Arithmetic operators} - \small - \begin{lstlisting} -In []: 1786 % 12 -Out[]: 10 - -In []: 45 % 2 -Out[]: 1 - -In []: 864675 % 10 -Out[]: 5 - -In []: 3124 * 126789 -Out[]: 396088836 - -In []: big = 1234567891234567890 ** 3 - -In []: verybig = big * big * big * big - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Arithmetic operators} - \begin{lstlisting} -In []: 17 / 2 -Out[]: 8.5 # 8 on Python 2.x - -In []: 17 / 2.0 -Out[]: 8.5 - -In []: 17.0 / 2 -Out[]: 8.5 - -In []: 17.0 / 8.5 -Out[]: 2.0 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Arithmetic operators: floor division} - \begin{lstlisting} -In []: 17 // 2 -Out[]: 8 - -In []: 17 // 2.0 -Out[]: 8.0 - -In []: 17.0 // 2.0 -Out[]: 8.0 - -In []: 17.0 // 8.6 -Out[]: 1.0 - \end{lstlisting} -\end{frame} - - -\begin{frame}[fragile] -\frametitle{Arithmetic operators} - \begin{lstlisting} -In []: c = 3+4j - -In []: abs(c) -Out[]: 5.0 - -In []: c.imag -Out[]: 4.0 -In []: c.real -Out[]: 3.0 - -In []: c.conjugate() -(3-4j) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Arithmetic operators} - \begin{lstlisting} -In []: a = 7546 - -In []: a += 1 -In []: a -Out[]: 7547 - -In []: a -= 5 -In []: a - -In []: a *= 2 - -In []: a /= 5 - \end{lstlisting} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{String operations} - \begin{lstlisting} -In []: s = 'Hello' - -In []: p = 'World' - -In []: s + p -Out[]: 'HelloWorld' - -In []: s * 4 -Out[]: 'HelloHelloHelloHello' - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{String operations \ldots} - \begin{lstlisting} -In []: s * s - \end{lstlisting} - \pause - \begin{lstlisting} --------------------------------------------- -TypeError Traceback (most recent call last) - - in () - -TypeError: can`t multiply sequence by - non-int of type `str` - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{String methods} - \begin{lstlisting} -In []: a = 'Hello World' -In []: a.startswith('Hell') -Out[]: True - -In []: a.endswith('ld') -Out[]: True - -In []: a.upper() -Out[]: 'HELLO WORLD' - -In []: a.lower() -Out[]: 'hello world' - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{String methods} - \begin{lstlisting} -In []: a = ' Hello World ' -In []: b = a.strip() -In []: b -Out[]: 'Hello World' - -In []: b.index('ll') -Out[]: 2 -In []: b.replace('Hello', 'Goodbye') -Out[]: 'Goodbye World' -\end{lstlisting} -\end{frame} - - -\begin{frame}[fragile] -\frametitle{Strings: \typ{split} \& \typ{join}} - \begin{lstlisting} -In []: chars = 'a b c' -In []: chars.split() -Out[]: ['a', 'b', 'c'] -In []: ' '.join(['a', 'b', 'c']) -Out[]: 'a b c' - \end{lstlisting} - \begin{lstlisting} -In []: alpha = ', '.join(['a', 'b', 'c']) -In []: alpha -Out[]: 'a, b, c' -In []: alpha.split(', ') -Out[]: ['a', 'b', 'c'] - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] -\frametitle{String formatting} - \begin{lstlisting} -In []: x, y = 1, 1.234 - -In []: 'x is %s, y is %s' %(x, y) -Out[]: 'x is 1, y is 1.234' - \end{lstlisting} - \begin{itemize} - \item \emph{\%d}, \emph{\%f} etc. available - \end{itemize} - \emphbar{\url{http://docs.python.org/library/stdtypes.html}} -%% \inctime{10} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Relational and logical operators} - \begin{lstlisting} -In []: p, z, n = 1, 0, -1 -In []: p == n -Out[]: False - -In []: p >= n -Out[]: True - -In []: n < z < p -Out[]: True - -In []: p + n != z -Out[]: False - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{The \typ{assert} statement} - \begin{itemize} - \item You will see it in tests and your exam! - \end{itemize} - - \begin{small} -\begin{lstlisting} -In []: assert p != n -In []: assert p == n ------------------------------------------------------- -AssertionError Traceback (most recent call last) -----> 1 assert p == n - -AssertionError: -\end{lstlisting} - \end{small} - \begin{itemize} - \item No error if condition is True - \item Raises error if False - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{assert} examples} - \begin{small} -\begin{lstlisting} -In []: assert p == n, "Oops condition failed" ------------------------------------------------------- -AssertionError Traceback (most recent call last) -----> 1 assert p == n - -AssertionError: Oops condition failed -\end{lstlisting} - \end{small} - \begin{itemize} - \item Can supply an optional message - \end{itemize} -\end{frame} - - -\begin{frame}[fragile] -\frametitle{String containership} - \begin{lstlisting} -In []: fruits = 'apple, banana, pear' -In []: 'apple' in fruits -Out[]: True - -In []: 'potato' in fruits -Out[]: False - -\end{lstlisting} - \begin{itemize} - \item Use tab complete to list other string methods - \item Use \typ{?} to find more information - \end{itemize} - -\end{frame} - -\begin{frame}[fragile] - \frametitle{Built-ins} - \begin{lstlisting} -In []: int(17 / 2.0) -Out[]: 8 - -In []: float(17 // 2) -Out[]: 8.0 - -In []: str(17 / 2.0) -Out[]: '8.5' - -In []: round( 7.5 ) -Out[]: 8.0 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Odds and ends} - \begin{itemize} - \item Case sensitive - \item Dynamically typed $\Rightarrow$ need not specify a type - \begin{lstlisting} -In []: a = 1 -In []: a = 1.1 -In []: a = "Now I am a string!" - \end{lstlisting} - \item Comments: - \begin{lstlisting} -In []: a = 1 # In-line comments -In []: # A comment line. -In []: a = "# Not a comment!" - \end{lstlisting} - \end{itemize} -%% \inctime{15} -\end{frame} - -\begin{frame} - \frametitle{Exercise 1} - Given a 2 digit integer\ \typ{x}, find the digits of the number. - \vspace*{1em} - - \begin{itemize} - \item For example, let us say \typ{x = 38} - \item Find a way to get \typ{a = 3} and \typ{b = 8} using \typ{x}? - \end{itemize} - -\end{frame} - -\begin{frame}[fragile] - \frametitle{Possible Solution} -\begin{lstlisting} -In []: a = x//10 -In []: b = x%10 -In []: a*10 + b == x -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Another Solution} -\begin{lstlisting} -In []: sx = str(x) -In []: a = int(sx[0]) -In []: b = int(sx[1]) -In []: a*10 + b == x -\end{lstlisting} -\end{frame} - - -\begin{frame} - \frametitle{Exercise 2} - Given an arbitrary integer, count the number of digits it has. -\end{frame} - -\begin{frame}[fragile] -\frametitle{Possible solution} -\begin{lstlisting} -In []: x = 12345678 -In []: len(str(x)) -\end{lstlisting} - - Sneaky solution! -\end{frame} - - - -\section{Simple IO} -\begin{frame}[fragile] - \frametitle{Simple IO: Console Input} - \small - \begin{itemize} - \item \typ{input()} waits for user input. - \begin{lstlisting} -In []: a = input() -5 - -In []: a -Out[]: '5' # Python 3.x! - -In []: a = input('Enter a value: ') -Enter a value: 5 - \end{lstlisting} - \item Prompt string is optional. - \item \typ{input} produces strings (Python 3.x) - \item \typ{int()} converts string to int. - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Simple IO: Python 2.x vs 3.x} - \begin{itemize} - \item \typ{print} is familiar to us - \item Changed from Python 2.x to 3.x - \item We use the Python 3 convention here - \vspace*{2em} - \item If on Python 2.x do this: - { - \small -\begin{lstlisting} -In []: from __future__ import print_function -\end{lstlisting} - } - \item Safe to use in Python 3.x also - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Simple IO: Console output} - \begin{itemize} - \item Put the following code snippet in a file \typ{hello1.py} - \end{itemize} -\begin{lstlisting} -from __future__ import print_function -print("Hello", "World") -print("Goodbye", "World") -\end{lstlisting} -Now run it like so: -\begin{lstlisting} -In []: %run hello1.py -Hello World -Goodbye World - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Simple IO: Console output \ldots} -Put the following code snippet in a file \typ{hello2.py} - \begin{lstlisting} -from __future__ import print_function -print("Hello", end=' ') -print("World") -\end{lstlisting} -Now run it like so: -\begin{lstlisting} -In []: %run hello2.py -Hello World - \end{lstlisting} - -\pause - -\begin{block}{Mini Exercise} - \begin{itemize} - \item Read docs for \typ{print} - \item Remember: use \typ{print?} \ - \end{itemize} -\end{block} -\end{frame} - -\begin{frame}[fragile] - \frametitle{What did we learn?} - \begin{itemize} - \item Data types: int, float, complex, boolean, string - \item Use \typ{type} builtin function to find the type - \item Operators: +, -, *, /, \%, **, +=, -=, *=, /=, >, <, <=, >=, ==, !=, a < b < c - \item Simple IO: \kwrd{input} and \kwrd{print} - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Homework} - \begin{itemize} - \item Explore the various string methods - \item Read the documentation for the string methods - \item Explore the different builtins seen so far also - \end{itemize} -\end{frame} - - -\end{document} - -%% Questions for Quiz %% -%% ------------------ %% - - -\begin{frame} -\frametitle{\incqno } - What is the largest integer value that can be represented natively by Python? -\end{frame} - -\begin{frame} -\frametitle{\incqno } - What is the result of 17.0 / 2? -\end{frame} - -\begin{frame} -\frametitle{\incqno } - Which of the following is not a type in Python? - \begin{enumerate} - \item int - \item float - \item char - \item string - \end{enumerate} -\end{frame} - -\begin{frame} -\frametitle{\incqno } -How do you create a complex number with real part 2 and imaginary part -0.5. -\end{frame} - -\begin{frame} -\frametitle{\incqno } - What is the difference between \kwrd{print} \emph{x} and \kwrd{print} \emph{x,} ? -\end{frame} - -\begin{frame} -\frametitle{\incqno } - What does '*' * 40 produce? -\end{frame} - -\begin{frame}[fragile] -\frametitle{\incqno } - What is the output of: - \begin{lstlisting} -In []: ', '.join(['a', 'b', 'c']) - \end{lstlisting} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{\incqno} - \begin{lstlisting} -In []: 47 % 3 - \end{lstlisting} - What is the output? -\end{frame} diff --git a/basic_python/control_flow.tex b/basic_python/control_flow.tex deleted file mode 100644 index 25d9cbc..0000000 --- a/basic_python/control_flow.tex +++ /dev/null @@ -1,402 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009-2017, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} - -\input{macros.tex} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Control flow]{Python language: Control Flow} - -\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} - \frametitle{Outline} - \tableofcontents - % You might wish to add the option [pausesections] -\end{frame} - -\section{Control flow} - -\begin{frame} - \frametitle{Control flow constructs} - \begin{itemize} - \item \kwrd{if/elif/else}: branching - \item \kwrd{while}: looping - \item \kwrd{for}: iterating - \item \kwrd{break, continue}: modify loop - \item \kwrd{pass}: syntactic filler - \end{itemize} -\end{frame} - -\subsection{Basic Conditional flow} -\begin{frame}[fragile] - \frametitle{\typ{if...elif...else} example} -Type the following code in an editor \& save as \alert{ladder.py} -{ \small -\begin{lstlisting} -x = int(input("Enter an integer: ")) -if x < 0: - print('Be positive!') -elif x == 0: - print('Zero') -elif x == 1: - print('Single') -else: - print('More') -\end{lstlisting} -} - %% \inctime{10} -\pause -\begin{itemize} -\item Run in IPython: \typ{\%run ladder.py} -\item Run on terminal: \typ{python ladder.py} -\end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Ternary operator} - \begin{itemize} - \item \texttt{score\_str} is either \texttt{'AA'} or a string of one - of the numbers in the range 0 to 100. - \item We wish to convert the string to a number using \texttt{int} - \item Convert it to 0, when it is \texttt{'AA'} - \item \texttt{if-else} construct or the ternary operator - \end{itemize} - \begin{lstlisting} -In []: if score_str != 'AA': -.....: score = int(score_str) -.....: else: -.....: score = 0 - \end{lstlisting} -\end{frame} -\begin{frame}[fragile] - \frametitle{Ternary operator} - With the ternary operator you can do this: - \small - \begin{lstlisting} -In []: ss = score_str -In []: score = int(ss) if ss != 'AA' else 0 - \end{lstlisting} -\end{frame} - - -\section{Control flow} -\subsection{Basic Looping} - -\begin{frame} - \frametitle{\typ{while}: motivational problem} -\begin{block}{Example: Fibonacci series} - Sum of previous two elements defines the next: - \begin{center} - $0,\ \ 1,\ \ 1,\ \ 2,\ \ 3,\ \ 5,\ \ 8,\ \ 13,\ \ 21,\ \ ...$ - \end{center} -\end{block} -\end{frame} - -\begin{frame} - \frametitle{How do you solve this?} - \begin{itemize} - \item Task: Give computer, instructions to solve this - \vspace*{2em} - \item How would you solve it? - \item How would you tell someone to solve it? - \vspace*{1em} - \item Assume you are given the starting values, 0 and 1. - \end{itemize} - -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{while}: Fibonacci} -\begin{block}{Example: Fibonacci series} - Sum of previous two elements defines the next: - \begin{center} - $0,\ \ 1,\ \ 1,\ \ 2,\ \ 3,\ \ 5,\ \ 8,\ \ 13,\ \ 21,\ \ ...$ - \end{center} -\end{block} -\pause -\begin{enumerate} -\item Start with: \typ{a, b = 0, 1} - \pause -\item Next element: \typ{next = a + b} - \pause -\item Shift \typ{a, b} to next values - \begin{itemize} - \item \typ{a = b} - \item \typ{b = next} - \end{itemize} - \pause -\item Repeat steps 2, 3 when \typ{b < 30} -\end{enumerate} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{\typ{while}} - \begin{lstlisting} -In []: a, b = 0, 1 -In []: while b < 30: - ...: print(b, end=' ') - ...: next = a + b - ...: a = b - ...: b = next - ...: - ...: -\end{lstlisting} - \begin{itemize} - \item Do this manually to check logic - \item Note: Indentation determines scope - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{while}} - We can eliminate the temporary \typ{next}: - \begin{lstlisting} -In []: a, b = 0, 1 -In []: while b < 30: - ...: print(b, end=' ') - ...: a, b = b, a + b - ...: - ...: -1 1 2 3 5 8 13 21 -\end{lstlisting} - Simple! -\end{frame} - - -\begin{frame}[fragile] - \frametitle{\typ{for} \ldots \typ{range()}} -Example: print squares of first \typ{5} numbers - \begin{lstlisting} -In []: for i in range(5): - ....: print(i, i * i) - ....: - ....: -0 0 -1 1 -2 4 -3 9 -4 16 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] -\frametitle{\typ{range()}} -\kwrd{range([start,] stop[, step])}\\ -\begin{itemize} - \item \typ{range()} returns a sequence of integers - \item The \typ{start} and the \typ{step} arguments are optional - \item \typ{stop} is not included in the sequence -\end{itemize} -\vspace*{.5in} -\begin{block}{Documentation convention} - \begin{itemize} - \item \alert{Anything within \typ{[]} is optional} - \item Nothing to do with Python - \end{itemize} -\end{block} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{for} \ldots \typ{range()}} -Example: print squares of odd numbers from 3 to 9 - \begin{lstlisting} -In []: for i in range(3, 10, 2): - ....: print(i, i * i) - ....: - ....: -3 9 -5 25 -7 49 -9 81 -\end{lstlisting} -%% \inctime{5} -\end{frame} - -\begin{frame} - \frametitle{Exercise with \typ{for}} - -Convert the Fibonnaci sequence example to use a \typ{for} loop with range. - -\end{frame} - -\begin{frame}[fragile] - \frametitle{Solution} -\begin{lstlisting} -a, b = 0, 1 -for i in range(10): - print(b, end=' ') - a, b = b, a + b -\end{lstlisting} - \vspace*{2em} -Note that the \typ{while} loop is a more natural fit here -\end{frame} - -\begin{frame} - \frametitle{\typ{break}, \typ{continue}, and\ \typ{pass}} - \begin{itemize} - \item Use \typ{break} to break out of loop - \item Use \typ{continue} to skip an iteration - \item Use \typ{pass} as syntactic filler - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{break} example} - Find first number in Fibonnaci sequence < 100 divisible by 4: -\begin{lstlisting} -a, b = 0, 1 -while b < 500: - if b % 4 == 0: - print(b) - break - a, b = b, a + b - -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\texttt{continue}} - \begin{itemize} - \item Skips execution of rest of the loop on current iteration - \item Jumps to the end of this iteration - \item Squares of all odd numbers below 10, not multiples of 3 - \end{itemize} - \begin{lstlisting} - In []: for n in range(1, 10, 2): - .....: if n%3 == 0: - .....: continue - .....: print(n*n) - \end{lstlisting} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{\typ{pass} example} -Try this: -\begin{lstlisting} -for i in range(5): - if i % 2 == 0: - pass - else: - print(i, 'is Odd') -\end{lstlisting} -\begin{itemize} -\item \typ{pass}: does nothing -\item Keep Python syntactically happy -\end{itemize} -Another example: -\begin{lstlisting} -while True: - pass -\end{lstlisting} -\end{frame} - - - -\section{Exercises} - -\begin{frame}{Problem 1.1: \emph{Armstrong} numbers} - Write a program that displays all three digit numbers that are equal to the sum of the cubes of their digits. That is, print numbers $abc$ that have the property $abc = a^3 + b^3 + c^3$\\ -For example, $153 = 1^3 + 5^3 + 3^3$\\ -\vspace*{0.2in} - -\begin{block}{Hints} - \begin{itemize} - \item Break problem into easier pieces - \item How would you solve the problem? - \item Can you explain to someone else how to solve it? - \end{itemize} -\end{block} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Some hints} - \begin{itemize} - \item What are the possible three digit numbers? - \item Can you split 153 into its respective digits, $a=1, b=5, c=3$? - \item With $a, b, c$ can you test if it is an Armstrong number? - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Solution: part 1} -\begin{lstlisting} -x = 153 -a = x//100 -b = (x%100)//10 -c = x%10 - -(a**3 + b**3 + c**3) == x -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Solution: part 2} -\begin{lstlisting} -x = 100 -while x < 1000: - print(x) - x += 1 # x = x + 1 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Solution} -\begin{lstlisting} -x = 100 -while x < 1000: - a = x//100 - b = (x%100)//10 - c = x%10 - if (a**3 + b**3 + c**3) == x: - print(x) - x += 1 -\end{lstlisting} -\end{frame} - - -\begin{frame}{Problem 1.2: Collatz sequence} -\begin{enumerate} - \item Start with an arbitrary (positive) integer. - \item If the number is even, divide by 2; if the number is odd, multiply by 3 and add 1. - \item Repeat the procedure with the new number. - \item It appears that for all starting values there is a cycle of 4, 2, 1 at which the procedure loops. -\end{enumerate} - Write a program that accepts the starting value and prints out the Collatz sequence. -%% \inctime{5} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{What did we learn?} - \begin{itemize} - \item Conditionals: \kwrd{if elif else} - \item Looping: \kwrd{while} \& \kwrd{for} - \item \typ{range} - \item \kwrd{break, continue, pass} - \item Solving simple problems - \end{itemize} -\end{frame} - -\end{document} diff --git a/basic_python/core_data_structures.tex b/basic_python/core_data_structures.tex deleted file mode 100644 index 7bfbb38..0000000 --- a/basic_python/core_data_structures.tex +++ /dev/null @@ -1,704 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009-2017, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -\input{macros.tex} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Data structures]{Python language: Core data structures} - -\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} - \frametitle{Outline} - \tableofcontents - % You might wish to add the option [pausesections] -\end{frame} - -\section{Data structures} -\subsection{Lists} -\begin{frame}[fragile] - \frametitle{Lists} -\begin{block}{We already know that} - \begin{lstlisting} -num = [1, 2, 3, 4] - \end{lstlisting} -is a list -\end{block} -\pause -\begin{itemize} -\item Lists can contain different types -\item including nested lists -\end{itemize} -\begin{lstlisting} -x = ['apple', 1, 'banana', 2.5, - 'shirt', [1,2,3]] -len(x) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Lists: methods} - \begin{lstlisting} -In []: num = [9, 8, 2, 3, 7] - -In []: num + [4, 5, 6] -Out[]: [9, 8, 2, 3, 7, 4, 5, 6] - -In []: num.append([4, 5, 6]) - -In []: num -Out[]: [9, 8, 2, 3, 7, [4, 5, 6]] - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Lists: methods} - \begin{lstlisting} -In []: num = [9, 8, 2, 3, 7] - -In []: num.extend([4, 5, 6]) -In []: num -Out[]: [9, 8, 2, 3, 7, 4, 5, 6] - -In []: num.reverse() -In []: num -Out[]: [6, 5, 4, 7, 3, 2, 8, 9] - -In []: num.remove(6) -In []: num - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Lists: methods} - \begin{lstlisting} -In []: num = [9, 8, 2, 3, 1, 2, 3, 4] -In []: num.count(2) -Out[]: 2 - -In []: num.index(2) -Out[]: 2 - -In []: num.pop() -4 -In []: num -[9, 8, 2, 3, 1, 2, 3] - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Removing elements} -\begin{itemize} - \item Elements can be removed based on their index OR - \item based on the value of the element - \end{itemize} - \begin{lstlisting} - In []: del num[1] - - In []: num.remove(3) - \end{lstlisting} - \begin{itemize} - \item \alert{When removing by value, first element is removed} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Sorting} - \begin{lstlisting} - In []: a = [5, 1, 6, 7, 7, 10] - In []: a.sort() - In []: a - \end{lstlisting} - \begin{itemize} - \item \typ{sort} method sorts the list in-place - \item Use \typ{sorted} if you require a new list - \item Pass \typ{reverse=True} to reverse the ordering - \end{itemize} - \begin{lstlisting} - In []: a = [5, 1, 6, 7, 7, 10] - In []: sorted(a, reverse=True) - In []: a - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] -\frametitle{List containership} -\emphbar{Recall \typ{num} is \typ{[9, 8, 2, 3, 7]}} -\begin{lstlisting} -In []: 4 in num -Out[]: False - -In []: b = 8 -In []: b in num -Out[]: True - -In []: b not in num -Out[]: False -\end{lstlisting} -\end{frame} - -\subsection{Tuples} -\begin{frame}[fragile] -\frametitle{Tuples: Immutable sequence} -\begin{lstlisting} -In []: x = 1, 2, 3 -In []: x -(1, 2, 3) - -In []: t = (1, 2, 3, 4, 5, 6, 7, 8) -In []: t[0] + t[3] + t[-1] -Out[]: 13 - -In []: t[4] = 7 -\end{lstlisting} -\pause -\begin{block}{Note:} -\begin{itemize} - \item Tuples are immutable - cannot be changed -\end{itemize} -\end{block} - -\end{frame} - -\begin{frame}[fragile] - \frametitle{Tuple packing and expansion} - Try these: -\begin{lstlisting} -In []: a, b = 1, 2 - -In []: a, b, c = 1, 2, 3 - -In []: a, b = 1, 2, 3 - -In []: a, = [1] -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Swapping values} - \vspace*{-1em} - \begin{lstlisting} - In[]: a, b = 5, 7 - - In[]: temp = a - In[]: a = b - In[]: b = temp - \end{lstlisting} - \begin{itemize} - \item Here's the Pythonic way of doing it - \end{itemize} - \begin{lstlisting} - In[]: a, b = b, a - \end{lstlisting} - \begin{itemize} - \item The variables can be of different data-types - \end{itemize} - \begin{lstlisting} - In[]: a = 2.5 - In[]: b = "hello" - In[]: a, b = b, a -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{tuple, list} functions} - Try these: -\begin{lstlisting} -In []: x = 1,2,3 - -In []: list(x) -Out[]: [1, 2, 3] - -In []: tuple(list(x)) -Out[]: (1, 2, 3) - -In []: tuple('hello') -\end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Slicing} - \begin{itemize} - \item Slicing works the same way for all sequence types - \item Indices also work the same way - \item Lists, tuples, and strings - \item \alert{\typ{sequence[initial:final:step]}} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Slicing \& Striding examples} - \begin{lstlisting} -In[]: primes = [2, 3, 5, 7, 11, 13, 17] -In[]: primes[2:6] -In[]: primes[:4] - -In[]: num = list(range(14)) -In[]: num[1:10:2] -In[]: num[:10] -In[]: num[10:] -In[]: num[::2] -In[]: num[::-1] - \end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Problem - Day of the Week?} - \begin{itemize} - \item Strings have methods to manipulate them - \end{itemize} - \begin{block}{Problem} - Given a list, \texttt{week}, containing names of the days of the - week and a string \texttt{s}, check if the string is a day of the - week. We should be able to check for any of the forms like, - \emph{sat, Sat, SAT} - \end{block} - \begin{itemize} - \item Get the first 3 characters of the string - \item Convert it all to lower case - \item Check for existence in the list, \texttt{week} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Solution - Day of the Week?} - \small -\begin{lstlisting} -week = 'mon tue wed thu fri sat sun'.split() -s = 'Sunday' -s.lower()[:3] in week -\end{lstlisting} - OR -\begin{lstlisting} -s[:3].lower() in week -\end{lstlisting} -\end{frame} - -\subsection{Dictionaries} - -\begin{frame}[fragile] - \frametitle{Dictionaries: Introduction} - \begin{itemize} - \item Lists index using integers; recall that :\\ - \vspace*{1em} - If \typ{p = [2, 3, 5, 7]}\\ - \typ{p[1]} is equal to \typ{3} - \vspace*{2em} - \item Dictionaries index not just with integers! - \item Following examples are for string indices - \item Will also work for integers, floats, tuples, and others - \item \alert{No ordering of keys!} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Dictionaries \ldots} -\begin{lstlisting} -In []: mtdict = {} -In []: d = {'png' : 'image file', - 'txt' : 'text file', - 'py' : 'python code', - 'java': 'bad code', - 'cpp': 'complex code'} - -In []: d['txt'] -Out[]: 'text file' - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Dictionaries \ldots} - \begin{lstlisting} -In []: 'py' in d -Out[]: True - -In []: 'jpg' in d -Out[]: False - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Dictionaries \ldots} - \begin{small} - \begin{lstlisting} -In []: list(d.keys()) -Out[]: ['cpp', 'py', 'txt', 'java', 'png'] - -In []: list(d.values()) -Out[]: ['complex code', 'python code', - 'text file', 'bad code', - 'image file'] - \end{lstlisting} - \end{small} -%% \inctime{10} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Inserting elements} - \emphbar{\alert{\typ{d[key] = value}}} - \begin{lstlisting} -In []: d['bin'] = 'binary file' -In []: d -Out[]: -{'bin': 'binary file', - 'cpp': 'complex code', - 'java': 'bad code', - 'png': 'image file', - 'py': 'python code', - 'txt': 'text file'} - \end{lstlisting} - \emphbar{\alert{Duplicate keys are overwritten!}} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Adding \& Removing Elements} - \begin{itemize} - \item Adding a new key-value pair - \end{itemize} - \begin{lstlisting} - In[]: d['c++'] = 'C++ code' - In[]: d - \end{lstlisting} - \begin{itemize} - \item Deleting a key-value pair - \end{itemize} - \begin{lstlisting} - In[]: del d['java'] - In[]: d - \end{lstlisting} - \begin{itemize} - \item Assigning to existing key, modifies the value - \end{itemize} - \begin{lstlisting} - In[]: d['cpp'] = 'C++ source code' - In[]: d - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Dictionaries: methods} -\begin{lstlisting} -In []: d.keys() -In []: d.values() -In []: d.get('bin') -Out[]: 'binary file' -In []: d.get('junk') # No error! - -In []: d.update({'bin': 'Binary file', -.....: 'exe': 'executable'}) -In []: d.clear() -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Dictionaries: containership} - \begin{lstlisting} -In []: 'bin' in d -Out[]: True - -In []: 'hs' in d -Out[]: False - \end{lstlisting} - \begin{block}{Note} - \begin{itemize} - \item We can check for the containership of keys only - \item Not values - \end{itemize} - \end{block} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Dictionaries: iteration} - \begin{lstlisting} -In []: for v in d: -.....: print(v) -.....: - -In []: for v in d.values(): -.....: print(v) -.....: - -In []: for k, v in d.items(): -.....: print(k, v) -.....: - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{dict} built-in} -Like \typ{list, tuple} can also create dicts like so: -\begin{lstlisting} -In []: d = dict(png='image file', -.....: txt='text file', -.....: py='python code') -\end{lstlisting} -\begin{itemize} -\item Check more of the dictionary methods yourself -\end{itemize} -\end{frame} - -\begin{frame} {Problem 2.1} - - You are given date strings of the form ``29 Jul, 2009'', or ``4 January - 2008''. In other words a number, a string and another number, with a comma - sometimes separating the items. - - Write a program that takes such a string as input and prints a tuple (yyyy, - mm, dd) where all three elements are ints. -\end{frame} - -\begin{frame}[fragile] - \frametitle{Some hints} - \begin{itemize} - \item Simplify the problem - \item Try to explain how someone can do it - \vspace*{2em} - - \item Replace ',' with space - \item \typ{string.split()} method is your friend - \item Need a mapping from month (string) to a number: use a dict - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Partial solution} -\begin{lstlisting} -month2mm = {'jan': 1, 'feb': 2, #... - } -date = input('Enter a date string: ') -date = date.replace(',', ' ') -day, month, year = date.split() -dd, yyyy = int(day), int(year) -mon = month[:3].lower() -mm = month2mm[mon] -print((yyyy, mm, dd)) -\end{lstlisting} -\end{frame} - -\subsection{Sets} -\begin{frame}[fragile] - \frametitle{Sets} - \begin{itemize} - \item Conceptually identical to the sets in mathematics - \item Simplest container, mutable - \item No ordering, no duplicates - \item usual suspects: union, intersection, subset \ldots - \item >, >=, <, <=, in, \ldots - \end{itemize} - \begin{lstlisting} - In[]: a_list = [1, 2, 1, 4, 5, 6, 2] - In[]: a = set(a_list) - In[]: a - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] - \frametitle{Operations on Sets} - \begin{lstlisting} - In []: f10 = set([1, 2, 3, 5, 8]) - In []: p10 = set([2, 3, 5, 7]) - \end{lstlisting} - \begin{itemize} - \item Mathematical operations can be performed on sets - \end{itemize} - \begin{itemize} - \item Union - \begin{lstlisting} - In []: f10 | p10 - \end{lstlisting} - \item Intersection - \begin{lstlisting} - In []: f10 & p10 - \end{lstlisting} - \item Difference - \begin{lstlisting} - In []: f10 - p10 - \end{lstlisting} - \item Symmetric Difference -\begin{lstlisting} - In []: f10 ^ p10 - \end{lstlisting} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Sub-sets} - \begin{itemize} - \item Proper Subset - \begin{lstlisting} - In[]: b = set([1, 2]) - In[]: b < f10 - \end{lstlisting} - \item Subsets - \begin{lstlisting} - In[]: f10 <= f10 - \end{lstlisting} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Elements of sets} - \begin{itemize} - \item Containership - \begin{lstlisting} - In[]: 1 in f10 - In[]: 4 in f10 - \end{lstlisting} - \item Iterating over elements - \begin{lstlisting} - In[]: for i in f10: - ....: print(i) - ....: - \end{lstlisting} - \item Subsets - \begin{lstlisting} - In[]: f10 <= f10 - \end{lstlisting} - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Problem 2.2} - Given a dictionary of the names of students and their marks, - - \begin{enumerate} - \item identify how many duplicate marks are there? - \item and what are these duplicate marks? - \end{enumerate} - -\end{frame} - -\begin{frame} - \frametitle{Hints} - \begin{itemize} - \item Use a set to find the unique marks: first part - \item Second part can be done in a few different ways - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Possible solution} -\begin{lstlisting} -students = {'x': 60, 'y': 60, 'z': 55} -all_marks = list(students.values()) -unique = set(all_marks) -n_dups = len(all_marks) - len(unique) -print(n_dups, 'duplicates') - -# Part 2 -for i in unique: - all_marks.remove(i) -print('Duplicates are', set(all_marks)) -\end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{What did we learn?} - \begin{itemize} - \item Core Python data structures: - \begin{itemize} - \item Lists - \item Tuples - \item Dictionaries - \item Sets - \end{itemize} - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Homework} - - \begin{itemize} - \item Explore all the methods of the various data structures you have seen - so far. - \item Read the documentation for each of these methods. - \item Solve all problems discussed - \end{itemize} -\end{frame} - -\end{document} - -%% Questions for Quiz %% -%% ------------------ %% - -\begin{frame} - \frametitle{\incqno} - How do you find the presence of an element \emph{x} in the list \emph{a}? -\end{frame} - - -\begin{frame}[fragile] - \frametitle{\incqno} - \begin{lstlisting} -In []: set([1, 2, 8, 2, 13, 8, 9]) - \end{lstlisting} - What is the output? -\end{frame} - -\begin{frame}[fragile] - \frametitle{\incqno} - \begin{lstlisting} -In []: a = {'a': 1, 'b': 2} -In []: a['a'] = 10 -In []: print(a) - \end{lstlisting} - What is the output? -\end{frame} - -\begin{frame}[fragile] - \frametitle{\incqno} - \begin{lstlisting} -In []: for i in range(3, 10, 2): - ...: print(i) - \end{lstlisting} - What is the output? -\end{frame} - -\begin{frame}[fragile] - \frametitle{\incqno} - \begin{lstlisting} -In []: a = [1, 2, 3] -In []: a.extend([5, 6]) - \end{lstlisting} - What is the value of a? -\end{frame} - -\begin{frame}[fragile] - \frametitle{\incqno} - \begin{lstlisting} -In []: a = (1, 2, 3) -In []: a[1] = 10 - \end{lstlisting} - What is the result? -\end{frame} - -\begin{frame}[fragile] - \frametitle{\incqno} - \begin{lstlisting} -def func(x, y=10): - print x+1, y+10 - -func(1) - - \end{lstlisting} - What is the output? -\end{frame} diff --git a/basic_python/exceptions.tex b/basic_python/exceptions.tex deleted file mode 100644 index 8b9eb46..0000000 --- a/basic_python/exceptions.tex +++ /dev/null @@ -1,292 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%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 "", 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 "", line 1, in -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 "", line 1, in -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 "", 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} - \small -\begin{lstlisting} -while True: - try: - data = input() - 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]) -except (ValueError, IndexError): - print("Invalid input ...") - -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\typ{try, except, else}} - \small -\begin{lstlisting} -while True: - try: - data = input() - x = int(data.split(',')[1]) - except (ValueError, IndexError): - print("Invalid input ...") - else: - print('All is well!') - break - \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 "", 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/files.tex b/basic_python/files.tex deleted file mode 100644 index 14ee6f6..0000000 --- a/basic_python/files.tex +++ /dev/null @@ -1,294 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2017, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -\input{macros.tex} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Files]{Python language: reading/writing files} - -\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} - -\section{Reading files} - -\begin{frame}[fragile] - \frametitle{Opening files} - Recall: - \begin{lstlisting} -% pwd # present working directory -% cd /home/fossee # go to directory - \end{lstlisting} - {\small The file is in our present working directory} - \begin{lstlisting} - In []: f = open('pendulum.txt') - In []: f - \end{lstlisting} - \begin{itemize} - \item \texttt{f} is a file object - \item Shows the mode in which the file is open (read mode) - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Reading the whole file} - \begin{lstlisting} - In []: pend = f.read() - In []: print(pend) - \end{lstlisting} - \begin{itemize} - \item We have read the whole file into the variable \texttt{pend} - \end{itemize} - \begin{lstlisting} - In []: type(pend) - In []: pend_list = pend.splitlines() - In []: pend_list - \end{lstlisting} - \begin{itemize} - \item \texttt{pend} is a string variable - \item We can split it at the newline characters into a list of - strings - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Closing the file} - \begin{itemize} - \item Close the file, when done; Also, if you want to read again - \end{itemize} - \begin{lstlisting} - In []: f.close() - In []: f - \end{lstlisting} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Reading line-by-line} - \begin{lstlisting} -In []: for line in open('pendulum.txt'): -.....: print(line) - \end{lstlisting} - \begin{itemize} - \item The file object is an ``iterable'' - \item We iterate over it and print each line - \item Instead of printing, collect lines in a list - \end{itemize} - \begin{lstlisting} -In []: line_list = [ ] -In []: for line in open('pendulum.txt'): -.....: line_list.append(line) - \end{lstlisting} -\end{frame} - -\section{Writing files} - -\begin{frame}[fragile] - \frametitle{Writing files} - \begin{lstlisting} -In []: f = open('new_file.txt', 'w') -In []: f.write('Hello world!\n') -In []: f.close() -\end{lstlisting} -\begin{itemize} -\item Note the mode \typ{'w'} -\item Will clobber existing file! -\item \typ{write} will not add new lines -\item Always remember to call \typ{close} -\end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Using print to write files} - \begin{small} - On Python 2.x - \begin{lstlisting} -In []: from __future__ import print_function -\end{lstlisting} -\hrule -\end{small} - - \begin{lstlisting} -In []: f = open('new_file.txt', 'w') -In []: print('Hello world!', file=f) -In []: f.close() -\end{lstlisting} -\begin{itemize} -\item Just pass the \typ{file} keyword arg -\item \typ{print} works normally, so adds new lines -\end{itemize} -\end{frame} - - -\section{Exercise: parsing data from file} - -\begin{frame}[fragile,plain] - \frametitle{File parsing -- Problem} - \begin{lstlisting} -A;010002;AMY A;058;037;42;35;40;212;P;; - \end{lstlisting} - \begin{itemize} - \item File with records like the one above is given - \item Each record has fields separated by \verb+;+ - \item region code; roll number; name; - \item marks --- $1^{st}$ L; $2^{nd}$ L; math; science; social; total - \item pass/fail indicated by P/F; W if withheld and else empty - \end{itemize} - - \begin{itemize} - \item We wish to calculate mean of math marks in region B - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Tokenization} - \begin{lstlisting} -In []: line = "parse this string" -In []: line.split() - \end{lstlisting} - \begin{itemize} - \item Original string is split on white-space - \item Returns a list of strings - \item It can be given an argument to split on that argument - \end{itemize} - \begin{lstlisting} -r = "A;01;JOSE R;083;042;47;AA;72;244;;;" -r.split(';') - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Tokenization \ldots} - \begin{itemize} - \item Since we split on commas, fields may have extra spaces at ends - \item We can strip out the spaces at the ends - \end{itemize} - \begin{lstlisting} - In []: word = " B " - In []: word.strip() - \end{lstlisting} - \begin{itemize} - \item \texttt{strip} is returning a new string - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\texttt{str} to \texttt{float}} - \begin{itemize} - \item After tokenizing, the marks we have are strings - \item We need numbers to perform math operations - \end{itemize} - \begin{lstlisting} - In []: mark_str = "1.25" - In []: mark = float(mark_str) - In []: type(mark_str) - In []: type(mark) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile, plain] - \frametitle{File parsing -- Solution} - \begin{lstlisting} -math_B = [] # empty list to store marks -for line in open("sslc1.txt"): - fields = line.split(";") - reg_code = fields[0] - reg_code = reg_code.strip() - - math_mark_str = fields[5] - math_mark = float(math_mark_str) - - if reg_code == "B": - math_B.append(math_mark) - -math_B_mean = sum(math_B) / len(math_B) -print(math_B_mean) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile, plain] - \frametitle{File parsing -- Solution} - An Error! - \small - \begin{lstlisting} -ValueError: could not convert string to float: AA - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile, plain] - \frametitle{File parsing -- debugging} - \begin{lstlisting} -math_B = [] # empty list to store marks -for line in open("sslc1.txt"): - fields = line.split(";") - reg_code = fields[0] - reg_code = reg_code.strip() - print(fields) # <-- Added - math_mark_str = fields[5] - math_mark = float(math_mark_str) - # ... - \end{lstlisting} -\end{frame} - - -\begin{frame}[fragile, plain] - \frametitle{File parsing -- debugging} - \small - \begin{lstlisting} -math_B = [] # empty list to store marks -for i, line in enumerate(open("sslc1.txt")): - fields = line.split(";") - reg_code = fields[0] - reg_code = reg_code.strip() - print(i, fields) # <-- Added - math_mark_str = fields[5] - math_mark = float(math_mark_str) - # ... - \end{lstlisting} -\end{frame} - - -\begin{frame}[fragile, plain] - \frametitle{File parsing -- Solution} - \begin{lstlisting} -math_B = [] # empty list to store marks -for line in open("sslc1.txt"): - fields = line.split(";") - reg_code = fields[0].strip() - m = fields[5] - mark = float(m) if m != 'AA' else 0 - if reg_code == "B": - math_B.append(mark) - -math_B_mean = sum(math_B) / len(math_B) -print(math_B_mean) - \end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Summary} - \begin{itemize} - \item Reading files - \item Writing files - \item Simple file parsing - \end{itemize} -\end{frame} - -\end{document} diff --git a/basic_python/functions.tex b/basic_python/functions.tex deleted file mode 100644 index 7213fea..0000000 --- a/basic_python/functions.tex +++ /dev/null @@ -1,435 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2017, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -\input{macros.tex} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Functions]{Python language: Functions} - -\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} - -\section{Functions} - -\begin{frame}[fragile] - \frametitle{Functions for abstraction} - \begin{itemize} - \item Reduce duplication of code - \item Fewer lines of code: lesser scope for bugs - \item Re-usability of code - \item Use functions written by others, without exactly knowing how - they do, what they are doing - \item \alert{Enter Functions!} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Defining functions} - \begin{itemize} - \item Consider the function \texttt{f(x) = x\textasciicircum{}2} - \item In Python: - \end{itemize} - \begin{lstlisting} - In []: def f(x): - .....: return x*x - .....: - In []: f(1) - In []: f(1+2j) - \end{lstlisting} - \begin{itemize} - \item \typ{def} is a keyword - \item \typ{f} is the name of the function - \item \typ{x} the parameter of the function - \item \typ{return} is a keyword - \end{itemize} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Defining functions \ldots} - \begin{lstlisting} - In []: def greet(): - .....: print("Hello World!") - .....: - - In []: greet() - \end{lstlisting} - \begin{itemize} - \item \texttt{greet} is a function that takes no arguments - \item It returns nothing explicitly - \item Implicitly, Python returns \typ{None} - \item \typ{None} is also a built-in, immutable data type - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Defining functions \ldots} - \begin{lstlisting} - In []: def avg(a, b): - .....: return (a + b)/2 - .....: - - In []: avg(12, 10) -\end{lstlisting} -\begin{itemize} -\item \typ{avg} takes two arguments -\item Returns one value -\end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Doc-strings} - \begin{itemize} - \item It's highly recommended that all functions have documentation - \item We write a doc-string along with the function definition - \end{itemize} - \begin{lstlisting} -def avg(a, b): - """Returns the average of two - given numbers.""" - return (a + b)/2 - -In[]: avg? -In[]: greet? - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Returning multiple values} - \begin{itemize} - \item Return area and perimeter of circle, given radius - \item Function needs to return two values - \end{itemize} - \begin{lstlisting} -def circle(r): - """Returns area and perimeter of - circle given radius r""" - pi = 3.14 - area = pi * r * r - perimeter = 2 * pi * r - return area, perimeter - -In []: circle(4) -In []: a, p = circle(6) - \end{lstlisting} -\end{frame} - - -\subsection{Default \& Keyword Arguments} - -\begin{frame}[fragile] - \frametitle{Default arguments} - \begin{lstlisting} -In []: round(2.484) -In []: round(2.484, 2) - -In []: s.split() # split on spaces -In []: s.split(';') # split on ';' - -In []: range(10) -In []: range(1, 10) -In []: range(1, 10, 2) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Default arguments \ldots} - \begin{lstlisting} -In []: def welcome(greet, name="World"): -.....: print(greet, name) -.....: - -In []: welcome("Hi", "Guido") -In []: welcome("Hello") - \end{lstlisting} -\end{frame} -\begin{frame}[fragile] - \frametitle{Default arguments \ldots} - \begin{itemize} - \item Arguments with default values, should be placed at the end - \item The following definition is \alert{WRONG} - \end{itemize} - \begin{lstlisting} -In []: def welcome(name="World", greet): -.....: print(greet, name) -.....: - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] - \frametitle{Keyword Arguments} - \begin{lstlisting} -In []: def welcome(greet, name="World"): -.....: print(greet, name) -.....: - -In []: welcome("Hello", "James") - -In []: welcome("Hi", name="Guido") - -In []: welcome(name="Guido",greet="Hey") - -In []: welcome(name="Guido", "Hey") -\end{lstlisting} -Cannot have non-keyword args after kwargs -\end{frame} - -\begin{frame}[fragile] - \frametitle{Built-in functions} - \begin{itemize} - \item Variety of built-in functions are available - \item \typ{abs, any, all, len, max, min} - \item \typ{pow, range, sum, type} - \item Refer here: - \url{http://docs.python.org/library/functions.html} - \end{itemize} -\end{frame} - -\subsection{Variable Scope} - -\begin{frame}[fragile] - \frametitle{Arguments are local} - \begin{lstlisting} - In []: def change(q): - .....: q = 10 - .....: print(q) - .....: - - In []: change(1) - In []: print(q) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Variables inside function are local} - \begin{lstlisting} - In []: n = 5 - In []: def change(): - .....: n = 10 - .....: print(n) - .....: - In []: change() - In []: print(n) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{If not defined, look in parent scope} - \begin{lstlisting} - In []: n = 5 - In []: def scope(): - .....: print(n) - .....: - In []: scope() -\end{lstlisting} -\begin{itemize} -\item Note that \typ{n} was not defined in \typ{scope} -\item It looked for the variable in previous scope -\item See: \url{pythontutor.com} -\end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{\texttt{global}} - \begin{itemize} - \item Use the \texttt{global} statement to assign to global variables - \end{itemize} - \begin{lstlisting} - In[]: def change(): - ....: global n - ....: n = 10 - ....: print(n) - ....: - In[]: change() - In[]: print(n) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Mutable variables} - \begin{itemize} - \item Behavior is different when assigning to a list element/slice - \item Python looks up for the name, from innermost scope outwards, - until the name is found - \end{itemize} - \begin{lstlisting} -In []: name = ['Mr.', 'Steve','Gosling'] -In []: def change_name(): -.....: name[0] = 'Dr.' -.....: -In []: change_name() -In []: print(name) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Passing Arguments \ldots} - \begin{lstlisting} -In []: n = 5 -In []: def change(n): -.....: n = 10 -.....: print(n, "inside change") -.....: -In []: change(n) -In []: print(n) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Passing Arguments \ldots} -\begin{lstlisting} -In []: name = ['Mr.', 'Steve','Gosling'] -In []: def change_name(x): -.....: x[0] = 'Dr.' -.....: print(x, 'in change') -.....: -In []: change_name(name) -In []: print(name) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Passing Arguments \ldots} -\begin{lstlisting} -In []: name = ['Mr.', 'Steve','Gosling'] -In []: def change_name(x): -.....: x = [1,2,3] -.....: print(x, 'in change') -.....: -In []: change_name(name) -In []: print(name) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Passing Arguments \ldots} -\begin{lstlisting} -In []: name = ['Mr.', 'Steve','Gosling'] -In []: def change_name(x): -.....: x[:] = [1,2,3] -.....: print(x, 'in change') -.....: -In []: change_name(name) -In []: print(name) - \end{lstlisting} -\end{frame} - - -\subsection{Examples} - -\begin{frame}[fragile] - \frametitle{Functions: example} - \begin{lstlisting} -def signum( r ): - """returns 0 if r is zero - -1 if r is negative - +1 if r is positive""" - if r < 0: - return -1 - elif r > 0: - return 1 - else: - return 0 - \end{lstlisting} - \emphbar{Note docstrings} -\end{frame} - -\begin{frame}[fragile] - \frametitle {What does this function do?} - \begin{lstlisting} -def what(n): - if n < 0: n = -n - while n > 0: - if n % 2 == 1: - return False - n /= 10 - return True - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{What does this function do?} -\begin{lstlisting} -def what(n): - i = 1 - while i * i < n: - i += 1 - return i * i == n, i - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle {What does this function do?} - \begin{lstlisting} -def what(x, n): - if n < 0: - n = -n - x = 1.0 / x - - z = 1.0 - while n > 0: - if n % 2 == 1: - z *= x - x *= x - n //= 2 - return z - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Nested functions} - \begin{lstlisting} - def f(x): - def g(x): - return x+1 - return g(x)**2 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Nested functions: returning functions} - \begin{lstlisting} - def f(): - def g(x): - return x+1 - return g - - In []: func = f() - In []: func(1) - In []: f()(1) # Also valid! - \end{lstlisting} -\end{frame} - - -\begin{frame} - \frametitle{Summary} - \begin{itemize} - \item Defining functions - \item Taking either 0, or more arguments - \item Returning \typ{None} implicitly or any number of values - \item Default and keyword arguments - \item Variable scope, \typ{global} - \item Mutable and immutable arguments - \item Nested functions - \end{itemize} -\end{frame} - -\end{document} diff --git a/basic_python/modules.tex b/basic_python/modules.tex deleted file mode 100644 index 57f720d..0000000 --- a/basic_python/modules.tex +++ /dev/null @@ -1,278 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2017, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} -\input{macros.tex} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Modules]{Python language: modules} - -\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} - -\section{Python modules} - -\begin{frame} - \frametitle{Modules} - \begin{itemize} - \item Organize your code - \item Collect similar functionality - \item Functions, classes, constants, etc. - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Modules} - \begin{itemize} - \item Define variables, functions and classes in a file with a - \texttt{.py} extension - \item This file becomes a module! - \item File name should be valid variable name - \end{itemize} -\end{frame} - -\begin{frame} - \frametitle{Modules \ldots} - \begin{itemize} - \item The \typ{import} keyword ``loads'' a module - \item One can also use: - \mbox{\typ{from module import name1, name2}}\\ - where \typ{name1} etc. are names in the module, \typ{module} - \item \typ{from module import *} \ --- imports everything from module, - \alert{use only in interactive mode} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Note on module file names} - \begin{itemize} - \item Should start with a letter or underscore - \item Can use \typ{\_} (underscore) and numbers - \item No \typ{.} allowed - \item No spaces or special characters - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Test} - \begin{itemize} - \item \typ{1\_script.py} - \item \typ{script\_1.py} - \item \typ{one11.py} - \item \typ{\_one11.py} - \item \typ{one script.py} - \item \typ{one,script;xxx.py} - \item \typ{one.two.py} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Modules: example} - \begin{lstlisting} -# --- fib.py --- -some_var = 1 -def fib(n): - """Print Fibonacci series up to n. - """ - a, b = 0, 1 - while b < n: - print(b, end=' ') - a, b = b, a+b -# EOF - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Modules: example} - \begin{lstlisting} ->>> import fib ->>> fib.fib(10) -1 1 2 3 5 8 ->>> fib.some_var -1 - \end{lstlisting} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Python path} - \begin{itemize} - \item In IPython type the following - \end{itemize} - \begin{lstlisting} - import sys - sys.path - \end{lstlisting} - \begin{itemize} - \item List of locations where python searches for a module - \item \texttt{import sys} -- searches for file \texttt{sys.py} or - dir \texttt{sys} in all these locations - \item Modules can be in any one of the locations - \item Current working directory is one of the locations - \item Can also set \texttt{PYTHONPATH} env var - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Running a module} - \begin{itemize} - \item Let us say we want to run some code in \typ{fib.py} so we get: - \end{itemize} - \begin{lstlisting} - $ python fib.py - 1 1 2 3 5 8 - \end{lstlisting} %$ - -\end{frame} - -\begin{frame}[fragile] - \frametitle{Modules: Running a module} - \begin{lstlisting} -# --- fib.py --- -some_var = 1 -def fib(n): - """Print Fibonacci series up to n. - """ - a, b = 0, 1 - while b < n: - print(b, end=' ') - a, b = b, a+b - -fib(10) -# EOF - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Modules: example} - \begin{lstlisting} ->>> import fib -1 1 2 3 5 8 -\end{lstlisting} - -\begin{itemize} -\item So the code is called even when we import the module -\item We do not want this! -\end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Using \texttt{\_\_name\_\_}} - \begin{lstlisting} - import fib - \end{lstlisting} - \begin{itemize} - \item The import is successful - \item But \typ{fib(10)}, gets run - \pause - \item Add it to the following \texttt{if} block - \end{itemize} - \begin{lstlisting} - if __name__ == "__main__": - fib(10) - \end{lstlisting} - \begin{itemize} - \item Now the script runs properly - \item As well as the import works; the code is not executed - \item \texttt{\_\_name\_\_} is local to every module and is equal - to \texttt{'\_\_main\_\_'} only when the file is run as a script. - \end{itemize} -\end{frame} - - -\begin{frame}[fragile] - \frametitle{Modules: using \typ{\_\_name\_\_}} - \vspace*{-1ex} - \begin{lstlisting} -# --- fib.py --- -def fib(n): - """Print Fibonacci series up to n. - """ - a, b = 0, 1 - while b < n: - print(b, end=' ') - a, b = b, a+b - -print(__name__) -if __name__ == '__main__': - fib(10) -# EOF - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Modules: using \typ{\_\_name\_\_}} - \begin{lstlisting} - >>> import fib - \end{lstlisting} - Try this: - \begin{lstlisting} - $ python fib.py - \end{lstlisting} %$ -\end{frame} - -\begin{frame}[fragile] - \frametitle{Stand-alone scripts} -Consider a file \texttt{f.py}: -\footnotesize -\begin{lstlisting} -#!/usr/bin/env python -"""Module level documentation.""" -# First line tells the shell that it should use Python -# to interpret the code in the file. -def f(): - print "f" - -# Check if we are running standalone or as module. -# When imported, __name__ will not be '__main__' -if __name__ == '__main__': - # This is not executed when f.py is imported. - f() -\end{lstlisting} -\end{frame} - -\begin{frame} - \frametitle{Standard library} - \begin{itemize} - \item Operating system interface: \typ{os}, \typ{os.path} - \item System, Command line arguments: \typ{sys} - \item Regular expressions: \typ{re} - \item Math: \typ{math}, \typ{random} - \item Internet access: \typ{urllib}, \typ{smtplib} - \item Data compression: \typ{zlib}, \typ{gzip}, \typ{bz2}, - \typ{zipfile}, and \typ{tarfile} - \item Unit testing: \typ{doctest} and \typ{unittest} - \item And a whole lot more! - \item Check out the Python Library reference: - \url{http://docs.python.org/lib/lib.html} - \end{itemize} -\end{frame} - -\begin{frame}[fragile] - \frametitle{Summary} - \begin{itemize} - \item Creating modules - \item Importing modules - \item Running modules as scripts - \item \texttt{\_\_name\_\_} - \end{itemize} -\end{frame} - -\end{document} diff --git a/basic_python/practice_basics.tex b/basic_python/practice_basics.tex deleted file mode 100644 index 37e535c..0000000 --- a/basic_python/practice_basics.tex +++ /dev/null @@ -1,318 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009-2017, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} - -\input{macros.tex} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Basic Python]{Practice exercises: Basics} - -\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}[fragile,plain] - \frametitle{Note: Python 2.x and 3.x} - - If you are using Python 2.x - \begin{itemize} - \item Use \typ{raw\_input} instead of \typ{input} - \item Use the following for \typ{print} - \end{itemize} - \begin{lstlisting} -from __future__ import print_function -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: print string} - \begin{enumerate} - \item Ask the user to enter a name - \begin{itemize} - \item use \typ{input()} (or \typ{raw\_input()} on 2.x) - \end{itemize} - \item Lets say the user entered: \\ \typ{abc}\\ then print \\ \typ{hello abc} - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Possible solution} -\begin{lstlisting} - name = input() # Or raw_input() - print("hello", name) -\end{lstlisting} - -\end{frame} - - -\begin{frame}[plain] - \frametitle{Exercise: input prompt} - \begin{enumerate} - \item Ask the user to enter a name but give them a prompt:\\ \typ{"Please - enter your name: "} \\ (note the trailing space) - \item Lets say the user entered: \\ \typ{abc}\\ then print \\ \typ{hello abc} - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Possible solution} -\begin{lstlisting} -name = input("Please enter your name: ") -print("hello", name) -\end{lstlisting} - -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: integers} - \begin{enumerate} - \item Ask the user for a single integer (no prompt string) - \item Print the square of this number - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Possible solution} -\begin{lstlisting} - x_str = input() - x = int(x_str) - print(x*x) -\end{lstlisting} - -\end{frame} - - -\begin{frame}[plain] - \frametitle{Exercise: digits of integer} - \begin{enumerate} - \item Ask the user for a single integer (use an empty prompt) - \item Square this integer - \item Print the number of digits the squared integer has - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Possible solution} -\begin{lstlisting} - x_str = input() - x = int(x_str) - y_str = str(x*x) - print(len(y_str)) -\end{lstlisting} - -\end{frame} - -\begin{frame}[fragile,plain] - \frametitle{Exercise: complex numbers} - \begin{enumerate} - \item Ask the user for a single complex number - \item If the number entered was \typ{1+2j}, print: - \begin{lstlisting} - 1 2 - \end{lstlisting} - \item Print the absolute value of this complex number - \item Print the conjugate of this complex number - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Possible solution} -\begin{lstlisting} - z_str = input() - z = complex(z_str) - print(z.real, z.imag) - print(abs(z)) - print(z.conjugate()) -\end{lstlisting} - -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: Booleans} - \begin{enumerate} - \item Ask the user to enter an integer (use an empty prompt) - \item Print \typ{True} if the number is odd, print \typ{False} otherwise - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Possible solution} -\begin{lstlisting} - x_str = input() - x = int(x_str) - print(x%2 == 1) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: Booleans} - \begin{enumerate} - \item Ask the user to enter an integer (use an empty prompt) - \item Print \typ{True} if the number is even, print \typ{False} otherwise - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Possible solution} -\begin{lstlisting} - x_str = input() - x = int(x_str) - print(x%2 == 0) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: string operations 1} - \begin{itemize} - \item Ask the user to enter a name (use an empty prompt) - \item Print the name entered but in upper case - \item For example, if the user enters 'abc', print 'ABC' - \end{itemize} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Possible solution} -\begin{lstlisting} - name = input() - print(name.upper()) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: string operations 2} - \begin{enumerate} - \item Ask the user to enter the name of a file (use an empty prompt) - \item Add an extension '.txt' to the name and print it - \item For example, if the user enters 'abc', print 'abc.txt' - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Possible solution} -\begin{lstlisting} - name = input() - print(name + '.txt') -\end{lstlisting} - -\end{frame} - - -\begin{frame}[fragile,plain] - \frametitle{Exercise: string slicing} - \begin{enumerate} - \item Ask the user to enter a string - \item Print the string without the first character - \item Print the string without the last character - \item Print the string in reverse - \item Finally print every alternate character of the string starting from - the first - \end{enumerate} - For example, if the user enters 'abcd', print the following: - \begin{lstlisting} - bcd - abc - dcba - ac - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Possible solution} -\begin{lstlisting} - name = input() - print(name[1:]) - print(name[:-1]) - print(name[::-1]) - print(name[::2]) -\end{lstlisting} - -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: string manipulations} - \begin{itemize} - \item Ask the user to enter a string - \item Count the number of vowels in the string - \item The code should be case-insensitive - \end{itemize} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Possible solution} -\begin{lstlisting} - x = input() - x = x.lower() - n = (x.count('a') + x.count('e') + - x.count('i') + x.count('o') + - x.count('u')) - print(n) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: string containership} - \begin{itemize} - \item Ask the user to enter a string - \item Check if the substrings 'abc' OR 'def' exist in the string - \item If it does, print True, else False - \end{itemize} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Possible solution} -\begin{lstlisting} - x = input().lower() - print('abc' in x or 'def' in x) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: digits of an integer} - Given a 2 digit integer\ \typ{x}, find the digits of the number. - \vspace*{1em} - - \begin{itemize} - \item For example, let us say \typ{x = 38} - \item Find a way to get \typ{a = 3} and \typ{b = 8} using \typ{x} - \item Print the digits, one in each line - \end{itemize} -\end{frame} - -\begin{frame}[fragile,plain] - \frametitle{Possible Solution} - \begin{lstlisting} -x = int(input()) -a = x//10 -b = x%10 -print(a) -print(b) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] - \frametitle{Another Solution} -\begin{lstlisting} - x = input() - print(x[0]) - print(x[1]) -\end{lstlisting} -\end{frame} - -\end{document} diff --git a/basic_python/practice_control_flow.tex b/basic_python/practice_control_flow.tex deleted file mode 100644 index 4fa966b..0000000 --- a/basic_python/practice_control_flow.tex +++ /dev/null @@ -1,399 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2009-2017, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} - -\input{macros.tex} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Basic Python]{Practice exercises: Control flow} - -\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}[fragile,plain] - \frametitle{Note: Python 2.x and 3.x} - - If you are using Python 2.x - \begin{itemize} - \item Use \typ{raw\_input} instead of \typ{input} - \item Use the following for \typ{print} - \end{itemize} - \begin{lstlisting} -from __future__ import print_function -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: simple \typ{if}} - \begin{enumerate} - \item Ask the user to enter an integer - \item If the number is positive, print "Positive" - \item If the number is negative, say -10 print:\\ "Negative of 10" - \item If the number is zero, print "Zero" - \item Finally, print "Done" - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - x = int(input()) - if x < 0: - print("Negative of", abs(x)) - elif x > 0: - print("Positive") - else: - print("Zero") - print("Done") -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: simple \typ{if} 2} - \begin{enumerate} - \item Ask the user to enter two integers, one on each line say \typ{x} and \typ{y} - \item If \typ{x} is larger than \typ{y} print, "first", store the value of \typ{x} in a - variable \typ{highest} - \item If \typ{y} is larger than \typ{x} print, "second", store the value of \typ{y} in a - variable \typ{highest} - \item If they are equal, print "same", store either as the \typ{highest} - \item Finally, print the square of the \typ{highest} - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - x = int(input()) - y = int(input()) - if x > y: - print("first") - highest = x - elif y > x: - print("second") - highest = y - else: - print("same") - highest = x - print(highest*highest) -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain] - \frametitle{Simple \typ{while} loop 1} - \begin{enumerate} - \item Use a while loop to print the numbers from 1 to 10 - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - x = 1 - while x < 11: - print(x) - x += 1 -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Simple \typ{while} loop 2} - \begin{enumerate} - \item Use a while loop to print the odd numbers from 1 to 10 - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - x = 1 - while x < 11: - print(x) - x += 2 -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Simple \typ{while} loop 2} - \begin{enumerate} - \item Use a while loop to generate the numbers from 1 to 10 - \item If a number divisible by 3 is found, print *** - \item If a number divisible by 5 is found, print ***** - \item Otherwise just print the number - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - x = 1 - while x < 11: - if x%3 == 0: - print('***') - elif x%5 == 0: - print('*****') - else: - print(x) - x += 1 -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Simple \typ{while} loop 3} - \begin{enumerate} - \item Use a while loop to generate the numbers from 10 to 1 - \item For each number, print that many * characters - \item That is, if the number is 1 print *, if the number is 3, print *** etc. - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - x = 10 - while x > 0: - print('*'*x) - x -= 1 -\end{lstlisting} -\end{frame} - -\begin{frame}[plain,fragile] - \frametitle{Simple \typ{while} loop 4} - \begin{enumerate} - \item Ask the user for an integer, \typ{n} (>=2) - \item Use a while loop to print \typ{n} numbers uniformly spaced between 0 and 1 - \item Include both 0 and 1 - \end{enumerate} - For example if the user entered 3, print - \begin{lstlisting} - 0.0 - 0.5 - 1.0 - \end{lstlisting} - -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - n = int(input()) - dx = 1.0/(n-1) - x = 0.0 - while x < (1.0-dx/2): - print(x) - x += dx - print(1.0) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain,fragile] - \frametitle{Simple \typ{for} loop 1} - \begin{enumerate} - \item Ask the user for an integer - \item Use a for loop to generate the multiplication table for the number (up - to 10) - \end{enumerate} - If the user entered 5, print the following - \begin{lstlisting} - 5 x 1 = 5 - 5 x 2 = 10 - 5 x 3 = 15 - ... - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - n = int(input()) - for i in range(1, 11): - print(n, 'x', i, '=', n*i) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain,fragile] - \frametitle{\typ{for} loop Fibonacci} - \begin{enumerate} - \item Ask the user for an integer, \typ{n} (>=1) - \item Print the first \typ{n} numbers of the Fibonacci sequence - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - n = int(input()) - a, b = 0, 1 - print(a) - for i in range(n-1): - print(b) - a, b = b, a+b -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain,fragile] - \frametitle{\typ{for} loop over list 1} - \begin{enumerate} - \item Ask the user for an integer, \typ{n} - \item Use the range to create numbers from 1 to \typ{n} - \item Print each value in this in a separate line - \end{enumerate} - For example let us say user enters \typ{3}, print - \begin{lstlisting} - 1 - 2 - 3 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - n = int(input()) - for x in range(1, n+1): - print(x) -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain,fragile] - \frametitle{\typ{for} loop over array} - \begin{enumerate} - \item Ask the user for an integer, \typ{n} - \item Use numpy's \typ{linspace} to create n points from 1 to 2 - \item Print each value in this in a separate line - \end{enumerate} - For example let us say user enters \typ{3}, print - \begin{lstlisting} - 1.0 - 1.5 - 2.0 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - from numpy import linspace - n = int(input()) - data = linspace(1, 2, n) - for x in data: - print(x) -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain,fragile] - \frametitle{\typ{for} loop over list 2} - \begin{enumerate} - \item Ask the user for an list of fruits separated by a comma - \item Print each fruit in a separate line - \end{enumerate} - For example let us say user enters \typ{apple, pear}, print - \begin{lstlisting} - apple - pear - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - fruits = input() - fruits = fruits.split(',') - for fruit in fruits: - print(fruit) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain,fragile] - \frametitle{\typ{for} loop over string} - \begin{enumerate} - \item Ask the user for a string - \item Print each character of the string using a for loop - \end{enumerate} - For example let us say user enters \typ{box}, print - \begin{lstlisting} - b - o - x - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - s = input() - for char in s: - print(char) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain,fragile] - \frametitle{Nested \typ{for} loops} - \begin{enumerate} - \item Let us say the user supplies an integer, \typ{n} (empty prompt) - \item Print an n x n matrix where each entry is the sum of the row + column - \end{enumerate} - For example let us say user enters \typ{3}, print - \begin{lstlisting} - 0 1 2 - 1 2 3 - 2 3 4 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - n = int(input()) - for i in range(n): - for j in range(n): - print(i+j, end=' ') - print() -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain,fragile] - \frametitle{Exercise: Fibonacci divisible by 4} - \begin{enumerate} - \item Find the first number in the Fibonacci sequence divisible by 4 but > 8 - and less than 500. - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} -a, b = 0, 1 -while b < 500: - if b % 4 == 0 and b > 8: - print(b) - break - a, b = b, a+b -\end{lstlisting} -\end{frame} - - -\end{document} diff --git a/basic_python/practice_ds.tex b/basic_python/practice_ds.tex deleted file mode 100644 index 50ebf7e..0000000 --- a/basic_python/practice_ds.tex +++ /dev/null @@ -1,411 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2017, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} - -\input{macros.tex} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Basic Python]{Practice exercises: data structures} - -\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}[fragile,plain] - \frametitle{Note: Python 2.x and 3.x} - - If you are using Python 2.x - \begin{itemize} - \item Use \typ{raw\_input} instead of \typ{input} - \item Use the following for \typ{print} - \end{itemize} - \begin{lstlisting} -from __future__ import print_function -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: simple list creation} - \begin{enumerate} - \item Ask the user to enter an integer, \typ{n} - \item Create a list of integers from 0 to \typ{n-1} - \item Print this list - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - n = int(input()) - x = list(range(n)) - print(x) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: more list creation} - \begin{enumerate} - \item Ask the user to enter an integer, \typ{n} - \item Store the square of all the odd numbers less than \typ{n} in a list - \item Print this list - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - n = int(input()) - result = [] - for i in range(1, n, 2): - result.append(i*i) - print(result) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: tuple creation} - \begin{enumerate} - \item Ask the user to enter an integer, \typ{n} - \item Store the square of all the odd numbers less than \typ{n} - \item Print a tuple of this list - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - n = int(input()) - result = [] - for i in range(1, n, 2): - result.append(i*i) - print(tuple(result)) -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain,fragile] - \frametitle{Hint: string to list/tuple} - Here is an easy way to convert a string to a list of characters. - - Try this: - \begin{lstlisting} - In []: x = 'hello' - In []: print(list(x)) - In []: print(tuple(x)) - \end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: list of Fibonacci} - \begin{enumerate} - \item Ask the user to enter an integer, \typ{n} ($\geq 1$) - \item Store the first \typ{n} numbers of the Fibonnaci series in a list - \item Print this list - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - n = int(input()) - a, b = 0, 1 - result = [0] - for i in range(n-1): - result.append(b) - a, b = b, a+b - print(result) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain,fragile] - \frametitle{Exercise: square a list of integers} - \begin{enumerate} - \item Ask the user to enter a list of integers separated by spaces - \item Convert this into a list of integers but square each element - \item Print this list - \end{enumerate} - For example, if the user enters \typ{1 2 3 4}, print: - \begin{lstlisting} - [1, 4, 9, 16] - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - text = input() - result = [] - for item in text.split(): - x = int(item) - result.append(x*x) - print(result) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain,fragile] - \frametitle{Exercise: list of tuples} - \begin{enumerate} - \item Ask the user to enter a list of integers separated by spaces - \item Convert this into a list of integers but square each element - \item Store the integer and its square in a tuple, put this into a list - \item Print this list - \end{enumerate} - For example, if the user enters \typ{1 2 3 4}, print: - \begin{lstlisting} - [(1, 1), (2, 4), (3, 9), (4, 16)] - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - text = input() - result = [] - for item in text.split(): - x = int(item) - result.append((x, x*x)) - print(result) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain,fragile] - \frametitle{Hint: iterating over a list of tuples} - Consider the following code: - \begin{small} - \begin{lstlisting} -In []: data = [(1, 1), (2, 4), (3, 9), (4, 16)] -\end{lstlisting} -\end{small} -We can iterate over this as follows: -\begin{small} -\begin{lstlisting} -In []: for x, y in data: -.....: print(x, y) -\end{lstlisting} -\end{small} -\end{frame} - - -\begin{frame}[plain,fragile] - \frametitle{Exercise: list methods} - \begin{enumerate} - \item Ask the user to enter a string - \item Convert this into a list of characters - \item Sort this list in ascending order - \item Now eliminate any repeated values in this list - \item Print this list - \end{enumerate} - For example, if the user enters \typ{hello}, print: - \begin{lstlisting} - ['e', 'h', 'l', 'o'] - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - text = input() - chars = list(text) - chars.sort() - result = [] - for c in chars: - if c not in result: - result.append(c) - print(result) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Another solution} -\begin{lstlisting} - text = input() - chars = set(text) - chars = list(chars) - chars.sort() - print(chars) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Another solution} -\begin{lstlisting} - chars = set(input()) - print(sorted(chars)) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain,fragile] - \frametitle{Exercise: simple dictionaries} - \begin{enumerate} - \item Ask the user for a list of integers separated by spaces - \item For each integer, store the string version as the key and the square of - the integer value as the value in a dictionary. - \item Print the resulting dictionary - \end{enumerate} -For example if the user enters "1 3 5", print: -\begin{lstlisting} -{'1': 1, '3': 9, '5': 25} -\end{lstlisting} -Hint: simply print the resulting dictionary -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} -text = input() -d = {} -for item in text.split(): - x = int(item) - d[item] = x*x -print(d) -\end{lstlisting} -\end{frame} - - -\begin{frame}[fragile,plain,fragile] - \frametitle{Exercise: mapping using dicts} - \begin{enumerate} - \item Create a mapping from 3 character month name to month number - \item Hint: for example \typ{\{'jan': 1, 'dec': 12\}} - \item Ask the user for a 3 character month code lower/upper mixed - \item Print the month number corresponding to the month the user entered. - \end{enumerate} -For example if the user enters "Jul", print: -\begin{lstlisting} -7 -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} -months = ('jan feb mar apr may jun jul ' + - 'aug sep oct nov dec').split() -month2mm = {} -for i in range(len(months)): - month2mm[months[i]] = i + 1 - -text = input() -mon = text[:3].lower() -print(month2mm[mon]) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Aside: using \typ{enumerate} example} -\begin{lstlisting} -for i, char in enumerate('hello'): - print(i, char) -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Aside: using \typ{enumerate}} -\begin{lstlisting} -months = ('jan feb mar apr may jun jul ' + - 'aug sep oct nov dec').split() -month2mm = {} -for i, month in enumerate(months): - month2mm[month] = i + 1 - -# Is easier/nicer than this: - -for i in range(len(months)): - month2mm[months[i]] = i + 1 -\end{lstlisting} - -\end{frame} - - - -\begin{frame}[plain,fragile] - \frametitle{Exercise: dictionaries} - \begin{enumerate} - \item Ask the user to enter a string - \item Convert this to lower case - \item Count the number of occurrences of each character in the string - \item Hint: use a dict - \item Print the result in sorted order of the characters - \end{enumerate} - For example, if the user enters \typ{helloo}, print: - \begin{lstlisting} - e 1 - h 1 - l 2 - o 2 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - text = input().lower() - result = {} - for char in text: - if char in result: - result[char] += 1 - else: - result[char] = 1 - - for char in sorted(result): - print(char, result[char]) -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain] - {Problem: datestring to date tuple} - - You are given date strings of the form ``29 Jul, 2009'', or ``4 January - 2008''. In other words a number, a string and another number, with a comma - sometimes separating the items. - - Write a program that takes such a string as input and prints a tuple (yyyy, - mm, dd) where all three elements are ints. -\end{frame} - -\begin{frame}[fragile] - \frametitle{Solution} - \small - \begin{lstlisting} -months = ('jan feb mar apr may jun jul ' + - 'aug sep oct nov dec').split() -month2mm = {} -for i, month in enumerate(months): - month2mm[month] = i + 1 - -date = input() -date = date.replace(',', ' ') -day, month, year = date.split() - -dd, yyyy = int(day), int(year) -mon = month[:3].lower() -mm = month2mm[mon] -print((yyyy, mm, dd)) -\end{lstlisting} -\end{frame} - -\begin{frame} - \centering - \Huge - - That's all folks! -\end{frame} -\end{document} diff --git a/basic_python/practice_files_exc.tex b/basic_python/practice_files_exc.tex deleted file mode 100644 index 1eda602..0000000 --- a/basic_python/practice_files_exc.tex +++ /dev/null @@ -1,217 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% 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 \typ{x} - \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} - \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} - - -\begin{frame} - \centering - \Huge - - Thank you! -\end{frame} -\end{document} - -\end{document} diff --git a/basic_python/practice_functions.tex b/basic_python/practice_functions.tex deleted file mode 100644 index d71168c..0000000 --- a/basic_python/practice_functions.tex +++ /dev/null @@ -1,357 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Tutorial slides on Python. -% -% Author: FOSSEE -% Copyright (c) 2017, FOSSEE, IIT Bombay -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -\documentclass[14pt,compress]{beamer} - -\input{macros.tex} - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Title page -\title[Basic Python]{Practice exercises: functions} - -\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}[fragile,plain] - \frametitle{Note: Python 2.x and 3.x} - - If you are using Python 2.x - \begin{itemize} - \item Use \typ{raw\_input} instead of \typ{input} - \item Use the following for \typ{print} - \end{itemize} - \begin{lstlisting} -from __future__ import print_function -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: function without arguments} - \begin{enumerate} - \item Define a function called \typ{prompt} - \item The function should ask the user to enter their name (no prompt) - \item The function should not take any arguments - \item The function should not return anything - \item The function should print \typ{Hello } - \end{enumerate} - For example if the user enters \typ{Sam}, print: - Hello Sam -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - def prompt(): - name = input() - print('Hello', name) -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: function with one argument} - \begin{enumerate} - \item Define a function called \typ{prompt} - \item The function should take a single string argument - \item \textbf{Do not ask the user for input, i.e. do not use input} - \item The function should not return anything - \item The function should print \typ{Hello } - \end{enumerate} - For example if the function is passed \typ{'Sam'}, print: - Hello Sam -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - def prompt(name): - print('Hello', name) -\end{lstlisting} -\end{frame} - - -\begin{frame}[plain,fragile] - \frametitle{Exercise: function with \typ{return}} - \begin{enumerate} - \item Define a function called \typ{prompt} - \item The function should take a single string argument - \item The function should return a string with \typ{'Hello'} - \item \textbf{Do not use input} - \item \textbf{Do not print anything} - \end{enumerate} - For example if the function is passed \typ{'Sam'}, return: - \begin{lstlisting} - 'Hello Sam' - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - def prompt(name): - return 'Hello ' + name -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: function with two args} - \begin{enumerate} - \item Define a function called \typ{add} - \item The function should take two arguments - \item The function should return the sum of the two arguments - \item \textbf{Do not use input} - \item \textbf{Do not print anything} - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - def add(a, b): - return a + b -\end{lstlisting} -\end{frame} - -\begin{frame}[plain] - \frametitle{Exercise: function returning boolean} - \begin{enumerate} - \item Define a function called \typ{is\_even} - \item The function should take a single integer argument - \item The function should return \typ{True} if the number is even and \typ{False} otherwise - \item \textbf{Do not use input} - \item \textbf{Do not print anything} - \end{enumerate} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Naive Solution} -\begin{lstlisting} - def is_even(x): - if x%2 == 0: - return True - else: - return False -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Elegant Solution} -\begin{lstlisting} - def is_even(x): - return x%2 == 0 -\end{lstlisting} -\end{frame} - -\begin{frame}[plain,fragile] - \frametitle{Exercise: function returning two values} - \begin{enumerate} - \item Define a function called \typ{even\_square} - \item The function should take a single argument - \item The function should return if the number is even and the square of the number - \item \textbf{Do not use input} - \item \textbf{Do not print anything} - \end{enumerate} - For example: - \begin{lstlisting} - In []: even_square(2) - Out[]: (True, 4) - In []: even_square(3) - Out[]: (False, 9) - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] - \frametitle{Solution} - \begin{lstlisting} - def even_square(x): - return x%2 == 0, x*x - \end{lstlisting} -\end{frame} - - -\begin{frame}[plain,fragile] - \frametitle{Exercise: default arguments} - \begin{enumerate} - \item Define a function called \typ{greet} - \item The function should take one positional argument, \typ{name} - \item The function should take one optional argument, \typ{message} - \item If \typ{message} is not given, it should default to \typ{'Hello'} - \item It should return the string with the greeting - \end{enumerate} - For example: - \begin{lstlisting} - In []: greet('Sam') - Out[]: 'Hello Sam' - In []: greet('Sam', 'Hi') - Out[]: 'Hi Sam' - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] - \frametitle{Solution} - \begin{lstlisting} - def greet(name, message='Hello'): - return message + ' ' + name - \end{lstlisting} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Exercise: functions and lists} - \begin{enumerate} - \item Define a function called \typ{to\_lower} - \item The function should take a single list of strings - \item The function should return the list of strings but all in lowercase - \item \textbf{Do not use input} - \item \textbf{Do not print anything} - \end{enumerate} - For example: - \begin{lstlisting} -In []: to_lower(['I', 'am', 'Batman']) -Out[]: ['i', 'am', 'batman'] - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - def to_lower(data): - result = [] - for x in data: - result.append(x.lower()) - return result -\end{lstlisting} -\end{frame} - -\begin{frame}[plain,fragile] - \frametitle{Exercise: list of Fibonacci} - \begin{enumerate} - \item Define a function called \typ{fib} taking one argument \typ{n} - \item Where, \typ{n>0} is an integer but defaults to 8 - \item Return the first \typ{n} terms of the Fibonacci sequence - \end{enumerate} - For example: - \begin{lstlisting} - In []: fib(4) - Out[]: [0, 1, 1, 2] - In []: fib() - Out[]: [0, 1, 1, 2, 3, 5, 8, 13] - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - def fib(n=8): - a, b = 0, 1 - result = [0] - for i in range(n-1): - result.append(b) - a, b = b, a+b - return result -\end{lstlisting} -\end{frame} - -\begin{frame}[plain,fragile] - \frametitle{Exercise: returning a function} - \begin{enumerate} - \item Define a function called \typ{power2()} which takes no argument - \item It should return a function which takes a single argument \typ{x} but - returns $2^x$ - \end{enumerate} - For example: - \begin{lstlisting} - In []: f = power2() - In []: f(2) - Out[]: 4 - In []: power2()(4) - Out[]: 16 - \end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] -\frametitle{Solution} -\begin{lstlisting} - def power2(): - def f(x): - return 2**x - return f -\end{lstlisting} -\end{frame} - -\begin{frame}[fragile,plain] - \frametitle{Another solution} - \begin{lstlisting} - def power(n=2): - def f(x): - return n**x - return f - \end{lstlisting} - \begin{itemize} - \item This is called a closure. - \item Note that \typ{f} ``stores'' the value of \typ{n} - \end{itemize} - \pause - \begin{lstlisting} - In []: p2 = power(2) - In []: p3 = power(3) - In []: p2(2) - Out[]: 4 - In []: p3(2) - Out[]: 9 - \end{lstlisting} -\end{frame} - -\begin{frame}[plain,fragile] - \frametitle{Exercise: function as an argument} - \begin{enumerate} - \item Define a function called \typ{apply(f, data)} - \item Where \typ{f} is a function taking a single value - \item Where \typ{data} is a list - \item It should return a list where the function is applied to each element - of \typ{data} - \end{enumerate} - For example: - \begin{lstlisting} - In []: def double(x): - .....: return 2*x - .....: - In []: apply(double, [1, 2, 3]) - Out[]: [2, 4, 6] - \end{lstlisting} -\end{frame} - -\begin{frame}[plain, fragile] - \frametitle{Solution} - \begin{lstlisting} - def apply(f, data): - result = [] - for x in data: - result.append(f(x)) - return result - \end{lstlisting} -\end{frame} - -\begin{frame} - \centering - \Huge - - That's all folks! -\end{frame} -\end{document} - -\end{document} -- cgit