%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %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}