%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %Tutorial slides on Python. % % Author: FOSSEE % Copyright (c) 2009, FOSSEE, IIT Bombay %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \documentclass[14pt,compress]{beamer} %\documentclass[draft]{beamer} %\documentclass[compress,handout]{beamer} %\usepackage{pgfpages} %\pgfpagesuselayout{2 on 1}[a4paper,border shrink=5mm] % Modified from: generic-ornate-15min-45min.de.tex \mode { \usetheme{Warsaw} \useoutertheme{infolines} \setbeamercovered{transparent} } \usepackage[english]{babel} \usepackage[latin1]{inputenc} %\usepackage{times} \usepackage[T1]{fontenc} % Taken from Fernando's slides. \usepackage{ae,aecompl} \usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} \definecolor{darkgreen}{rgb}{0,0.5,0} \usepackage{listings} \lstset{language=Python, basicstyle=\ttfamily\bfseries, commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, showstringspaces=false, keywordstyle=\color{blue}\bfseries} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Macros \setbeamercolor{emphbar}{bg=blue!20, fg=black} \newcommand{\emphbar}[1] {\begin{beamercolorbox}[rounded=true]{emphbar} {#1} \end{beamercolorbox} } \newcounter{time} \setcounter{time}{0} \newcommand{\inctime}[1]{\addtocounter{time}{#1}{\tiny \thetime\ m}} \newcommand{\typ}[1]{\textbf{\texttt{{#1}}}} \newcommand{\kwrd}[1]{ \texttt{\textbf{\color{blue}{#1}}} } %%% This is from Fernando's setup. % \usepackage{color} % \definecolor{orange}{cmyk}{0,0.4,0.8,0.2} % % Use and configure listings package for nicely formatted code % \usepackage{listings} % \lstset{ % language=Python, % basicstyle=\small\ttfamily, % commentstyle=\ttfamily\color{blue}, % stringstyle=\ttfamily\color{orange}, % showstringspaces=false, % breaklines=true, % postbreak = \space\dots % } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Title page \title[Basic Python]{Python language: Basics} \author[FOSSEE Team] {The FOSSEE Group} \institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay} \date[] {SciPy.in 2010, Tutorials} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %\pgfdeclareimage[height=0.75cm]{iitmlogo}{iitmlogo} %\logo{\pgfuseimage{iitmlogo}} %% Delete this, if you do not want the table of contents to pop up at %% the beginning of each subsection: \AtBeginSubsection[] { \begin{frame} \frametitle{Outline} \tableofcontents[currentsection,currentsubsection] \end{frame} } \AtBeginSection[] { \begin{frame} \frametitle{Outline} \tableofcontents[currentsection,currentsubsection] \end{frame} } % If you wish to uncover everything in a step-wise fashion, uncomment % the following command: %\beamerdefaultoverlayspecification{<+->} %\includeonlyframes{current,current1,current2,current3,current4,current5,current6} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 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 \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} \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 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} \begin{lstlisting} In []: c = 3+4j In []: abs(c) Out[]: 5.0 In []: c.imag Out[]: 4.0 In []: c.real Out[]: 3.0 \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{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{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} \section{Simple IO} \begin{frame}[fragile] \frametitle{Simple IO: Console Input} \small \begin{itemize} \item raw\_input() waits for user input. \begin{lstlisting} In []: a = raw_input() 5 In []: a Out[]: '5' In []: a = raw_input('Enter a value: ') Enter a value: 5 \end{lstlisting} \item Prompt string is optional. \item All keystrokes are strings! \item \typ{int()} converts string to int. \end{itemize} \end{frame} \begin{frame}[fragile] \frametitle{Simple IO: Console output} \begin{itemize} \item \typ{print} is straight forward \item Put the following code snippet in a file \typ{hello1.py} \end{itemize} \begin{lstlisting} print "Hello" print "World" In []: %run -i hello1.py Hello 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} print "Hello", print "World" In []: %run -i hello2.py Hello World \end{lstlisting} \emphbar{Note the distinction between \typ{print x} and \typ{print x,}} \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(raw_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} \end{frame} \section{Control flow} \subsection{Basic Looping} \begin{frame}[fragile] \frametitle{\typ{while}} \begin{block}{Example: Fibonacci series} Sum of previous two elements defines the next \end{block} \begin{lstlisting} In []: a, b = 0, 1 In []: while b < 10: ...: print b, ...: a, b = b, a + b ...: ...: \end{lstlisting} \typ{1 1 2 3 5 8}\\ \end{frame} \begin{frame}[fragile] \frametitle{\typ{range()}} \kwrd{range([start,] stop[, step])}\\ \begin{itemize} \item \typ{range()} returns a list of integers \item The \typ{start} and the \typ{step} arguments are optional \item \typ{stop} is not included in the list \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 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{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} \subsection{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} \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 Data types: int, float, complex, boolean, string \item Operators: +, -, *, /, \%, **, +=, -=, *=, /=, >, <, <=, >=, ==, !=, a < b < c \item Simple IO: \kwrd{raw\_input} and \kwrd{print} \item Conditionals: \kwrd{if elif else} \item Looping: \kwrd{while} \& \kwrd{for} \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}