<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://www.liangzerui.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://www.liangzerui.com/" rel="alternate" type="text/html" /><updated>2026-08-16T14:12:12+00:00</updated><id>https://www.liangzerui.com/feed.xml</id><title type="html">Zerui Liang</title><subtitle>Zerui Liang is a communication researcher focusing on AI-mediated communication, media effects, health communication and digital society.</subtitle><author><name>Zerui Liang</name></author><entry><title type="html">Python Week 8 listsp</title><link href="https://www.liangzerui.com/Python-Week-8-Listsp/" rel="alternate" type="text/html" title="Python Week 8 listsp" /><published>2015-07-16T00:00:00+00:00</published><updated>2015-07-16T00:00:00+00:00</updated><id>https://www.liangzerui.com/Python-Week%208%20Listsp</id><content type="html" xml:base="https://www.liangzerui.com/Python-Week-8-Listsp/"><![CDATA[<p>This course introduces the concept of collection/list etc.<br />
<!--more--></p>

<hr />
<aside class="sidebar__right">
<nav class="toc">
    <header><h4 class="nav__title"><i class="fa fa-file-text"></i> On This Page</h4></header>
<ul class="toc__menu" id="markdown-toc">
  <li><a href="#1-concept-of-a-collection" id="markdown-toc-1-concept-of-a-collection">1. Concept of a collection</a></li>
  <li><a href="#2-lists-and-definite-loops" id="markdown-toc-2-lists-and-definite-loops">2. Lists and definite loops</a></li>
  <li><a href="#3-indexing-and-lookup" id="markdown-toc-3-indexing-and-lookup">3. Indexing and lookup</a></li>
  <li><a href="#4-list-mutability" id="markdown-toc-4-list-mutability">4. List mutability</a></li>
  <li><a href="#5-functions-len-min-max-sum" id="markdown-toc-5-functions-len-min-max-sum">5. Functions: len, min, max, sum</a></li>
  <li><a href="#6-slicing-lists" id="markdown-toc-6-slicing-lists">6. Slicing lists</a></li>
  <li><a href="#7-list-methods-append-remove" id="markdown-toc-7-list-methods-append-remove">7. List methods: append, remove</a></li>
  <li><a href="#8-sorting-lists" id="markdown-toc-8-sorting-lists">8. Sorting lists</a></li>
  <li><a href="#9-splitting-strings-into-lists-of-words" id="markdown-toc-9-splitting-strings-into-lists-of-words">9. Splitting strings into lists of words</a></li>
  <li><a href="#10-using-split-to-parse-strings" id="markdown-toc-10-using-split-to-parse-strings">10. Using split to parse strings</a></li>
</ul>

  </nav>
</aside>

<hr />

<h2 id="1-concept-of-a-collection">1. Concept of a collection</h2>

<ul>
  <li>A collection <strong><em>allows</em></strong> us to <strong><em>put many values</em></strong> in a <strong><em>single “variable”</em></strong></li>
  <li>A collection is nice because we can carry all many values around in one convenient package.</li>
</ul>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">friends</span> <span class="o">=</span> <span class="p">[</span> <span class="s">'Joseph'</span><span class="p">,</span> <span class="s">'Glenn'</span><span class="p">,</span> <span class="s">'Sally'</span> <span class="p">]</span>

<span class="n">carryon</span> <span class="o">=</span> <span class="p">[</span> <span class="s">'socks'</span><span class="p">,</span> <span class="s">'shirt'</span><span class="p">,</span> <span class="s">'perfume'</span> <span class="p">]</span>
</code></pre></div></div>

<ul>
  <li>What is not a “Collection”
    <ul>
      <li>Most of our variables have one value in them - when we put a new value in the variable - the old value is over written</li>
    </ul>
  </li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ python
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin
&gt;&gt;&gt; x = 2
&gt;&gt;&gt; x = 4
&gt;&gt;&gt; print x
4
</code></pre></div></div>

<hr />

<h2 id="2-lists-and-definite-loops">2. Lists and definite loops</h2>

<ul>
  <li>List constants are surrounded by square brackets and the elements in the list are separated by commas.</li>
  <li>A list element can be any Python object - even another list</li>
  <li>A list can be empty</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; print [1, 24, 76]
[1, 24, 76]
&gt;&gt;&gt; print ['red', 'yellow', 'blue']
['red', 'yellow', 'blue']
&gt;&gt;&gt; print ['red', 24, 98.6]
['red', 24, 98.599999999999994]
&gt;&gt;&gt; print [ 1, [5, 6], 7]
[1, [5, 6], 7]
&gt;&gt;&gt; print []
[]
</code></pre></div></div>

<hr />

<h2 id="3-indexing-and-lookup">3. Indexing and lookup</h2>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends :
    print 'Happy New Year:',  friend
print 'Done!'

Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: SallyDone!
</code></pre></div></div>

<ul>
  <li>Just like strings, we can get at any single element in a list using an index specified in square brackets</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; friends = [ 'Joseph', 'Glenn', 'Sally' ]
&gt;&gt;&gt; print friends[1]
Glenn
&gt;&gt;&gt;
</code></pre></div></div>

<hr />

<h2 id="4-list-mutability">4. List mutability</h2>

<ul>
  <li>Strings are “immutable” - we cannot change the contents of a string - we must make a new string to make any change</li>
  <li>Lists are “mutable” - we can change an element of a list using the index operator</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; fruit = 'Banana’
&gt;&gt;&gt; fruit[0] = 'b’
Traceback
TypeError: 'str' object does not
support item assignment
&gt;&gt;&gt; x = fruit.lower()
&gt;&gt;&gt; print x
banana
&gt;&gt;&gt; lotto = [2, 14, 26, 41, 63]
&gt;&gt;&gt; print lotto[2, 14, 26, 41, 63]
&gt;&gt;&gt; lotto[2] = 28
&gt;&gt;&gt; print lotto
[2, 14, 28, 41, 63]
</code></pre></div></div>

<hr />

<h2 id="5-functions-len-min-max-sum">5. Functions: len, min, max, sum</h2>

<ul>
  <li>The len() function takes a list as a parameter and returns the number of elements in the list</li>
  <li>Actually len() tells us the number of elements of any set or sequence (i.e. such as a string…)</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; greet = 'Hello Bob'
&gt;&gt;&gt; print len(greet)
9
&gt;&gt;&gt; x = [ 1, 2, 'joe', 99]
&gt;&gt;&gt; print len(x)
4
&gt;&gt;&gt;
</code></pre></div></div>

<hr />

<h2 id="6-slicing-lists">6. Slicing lists</h2>

<hr />

<h2 id="7-list-methods-append-remove">7. List methods: append, remove</h2>

<hr />

<h2 id="8-sorting-lists">8. Sorting lists</h2>

<hr />

<h2 id="9-splitting-strings-into-lists-of-words">9. Splitting strings into lists of words</h2>

<hr />

<h2 id="10-using-split-to-parse-strings">10. Using split to parse strings</h2>]]></content><author><name>Zerui Liang</name></author><summary type="html"><![CDATA[This course introduces the concept of collection/list etc.]]></summary></entry><entry><title type="html">Python Week 7 files</title><link href="https://www.liangzerui.com/Python-Week-7-Files/" rel="alternate" type="text/html" title="Python Week 7 files" /><published>2015-07-15T00:00:00+00:00</published><updated>2015-07-15T00:00:00+00:00</updated><id>https://www.liangzerui.com/Python-Week%207%20Files</id><content type="html" xml:base="https://www.liangzerui.com/Python-Week-7-Files/"><![CDATA[<p>How to open &amp; read &amp; oprate a file.<br />
<!--more--></p>

<hr />
<aside class="sidebar__right">
<nav class="toc">
    <header><h4 class="nav__title"><i class="fa fa-file-text"></i> On This Page</h4></header>
<ul class="toc__menu" id="markdown-toc">
  <li><a href="#week7-files" id="markdown-toc-week7-files">Week7 Files</a>    <ul>
      <li><a href="#1secondary-storage" id="markdown-toc-1secondary-storage">1.Secondary storage</a></li>
      <li><a href="#2opening-a-file---file-handle" id="markdown-toc-2opening-a-file---file-handle">2.Opening a file - file handle</a>        <ul>
          <li><a href="#21-using-open" id="markdown-toc-21-using-open">2.1 Using open()</a></li>
          <li><a href="#23-when-files-are-missing" id="markdown-toc-23-when-files-are-missing">2.3 When files are missing</a></li>
        </ul>
      </li>
      <li><a href="#3file-structure---newline-character" id="markdown-toc-3file-structure---newline-character">3.File structure - newline character</a></li>
      <li><a href="#4reading-a-file-line-by-line-with-a-for-loop" id="markdown-toc-4reading-a-file-line-by-line-with-a-for-loop">4.Reading a file line-by-line with a for loop</a>        <ul>
          <li><a href="#41-counting-lines-in-a-file" id="markdown-toc-41-counting-lines-in-a-file">4.1 Counting Lines in a File</a></li>
          <li><a href="#42-reading-the-whole-file" id="markdown-toc-42-reading-the-whole-file">4.2 Reading the <em>Whole</em> File</a></li>
        </ul>
      </li>
      <li><a href="#5searching-for-lines" id="markdown-toc-5searching-for-lines">5.Searching for lines</a>        <ul>
          <li><a href="#51-using-if-to-select" id="markdown-toc-51-using-if-to-select">5.1 using if to select</a></li>
          <li><a href="#52-skipping-with-continue" id="markdown-toc-52-skipping-with-continue">5.2 Skipping with continue</a></li>
          <li><a href="#53-using-in-to-select-lines" id="markdown-toc-53-using-in-to-select-lines">5.3 Using in to select lines</a></li>
        </ul>
      </li>
      <li><a href="#6reading-file-names" id="markdown-toc-6reading-file-names">6.Reading file names</a></li>
      <li><a href="#7dealing-with-bad-files" id="markdown-toc-7dealing-with-bad-files">7.Dealing with bad files</a></li>
    </ul>
  </li>
</ul>

  </nav>
</aside>

<hr />

<h1 id="week7-files">Week7 Files</h1>

<hr />
<h2 id="1secondary-storage">1.Secondary storage</h2>

<hr />
<h2 id="2opening-a-file---file-handle">2.Opening a file - file handle</h2>

<ol>
  <li>Before we can read the contents of the file we must tell Python which file we are going to work with and what we will be doing with the file</li>
  <li>This is done with the <strong><em>open()</em></strong> function</li>
  <li><strong><em>open()</em></strong> returns a “<strong><em>file handle</em></strong>” - a variable used to perform operations on the file</li>
  <li>Kind of like “File -&gt; Open” in a Word Processor</li>
</ol>

<h3 id="21-using-open">2.1 Using open()</h3>

<p>handle = open(filename, mode)</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fhand = open('mbox.txt', 'r')
</code></pre></div></div>

<ol>
  <li>returns a handle use to manipulate the file</li>
  <li>filename is a string</li>
  <li>mode is optional and should be ‘r’ if we are planning reading the file and ‘w’ if we are going to write to the file.</li>
</ol>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; fhand = open('mbox.txt')
&gt;&gt;&gt; print fhand
&lt;open file 'mbox.txt', mode 'r' at 0x1005088b0&gt;\
</code></pre></div></div>

<h3 id="23-when-files-are-missing">2.3 When files are missing</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; fhand = open('stuff.txt')
Traceback (most recent call last):  File "&lt;stdin&gt;", line 1, in &lt;module&gt;IOError: [Errno 2] No such file or directory: 'stuff.txt'
</code></pre></div></div>

<hr />

<h2 id="3file-structure---newline-character">3.File structure - newline character</h2>

<ol>
  <li>We use a special character to indicate when a line ends called the “newline”</li>
  <li>We represent it as \n in strings</li>
  <li>Newline is still one character - not two</li>
</ol>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; stuff = 'Hello\nWorld!’
&gt;&gt;&gt; stuff'Hello\nWorld!’
&gt;&gt;&gt; print stuff
HelloWorld!
&gt;&gt;&gt; stuff = 'X\nY’
&gt;&gt;&gt; print stuff
X
Y
&gt;&gt;&gt; len(stuff)3
</code></pre></div></div>

<hr />

<h2 id="4reading-a-file-line-by-line-with-a-for-loop">4.Reading a file line-by-line with a for loop</h2>

<ol>
  <li>A file handle open for read can be treated as a sequence of strings where each line in the file is a string in the sequence</li>
  <li>We can use the for statement to iterate through a sequence</li>
  <li>Remember - a sequence is an ordered set</li>
</ol>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>xfile = open('mbox.txt')
for cheese in xfile:
    print cheese
</code></pre></div></div>

<h3 id="41-counting-lines-in-a-file">4.1 Counting Lines in a File</h3>

<ol>
  <li>Open a file read-only</li>
  <li>Use a for loop to read each line</li>
  <li>Count the lines and print out the number of lines</li>
</ol>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fhand = open('mbox.txt')
count = 0
for line in fhand:
     count = count + 1
print 'Line Count:', count

$ python open.py
Line Count: 132045

</code></pre></div></div>

<h3 id="42-reading-the-whole-file">4.2 Reading the <em>Whole</em> File</h3>

<p>We can read the whole file (newlines and all) into a single string.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; fhand = open('mbox-short.txt')
&gt;&gt;&gt; inp = fhand.read()
&gt;&gt;&gt; print len(inp)94626
&gt;&gt;&gt; print inp[:20]From stephen.marquar
</code></pre></div></div>

<hr />

<h2 id="5searching-for-lines">5.Searching for lines</h2>

<h3 id="51-using-if-to-select">5.1 using if to select</h3>

<p>We can put an if statement in our for loop to only print lines that meet some criteria</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fhand = open('mbox-short.txt')
for line in fhand:
      if line.startswith('From:') :
            print line
            
            
From: stephen.marquard@uct.ac.za

From: louis@media.berkeley.edu

From: zqian@umich.edu

From: rjlowe@iupui.edu

            
</code></pre></div></div>

<blockquote>
  <p>Each line from the file has a newline at the end.<br />
The print statement adds a newline to each line.</p>
</blockquote>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>From: stephen.marquard@uct.ac.za\n
\n
From: louis@media.berkeley.edu\n
\n
From: zqian@umich.edu\n
\n
From: rjlowe@iupui.edu\n
\n
</code></pre></div></div>

<ul>
  <li>We can strip the whitespace from the right hand side of the string using rstrip() from the string library</li>
  <li>The newline is considered “white space” and is stripped</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fhand = open('mbox-short.txt')
for line in fhand:
      line = line.rstrip()
      if line.startswith('From:') :            
      
      
From: stephen.marquard@uct.ac.za
From: louis@media.berkeley.edu
From: zqian@umich.edu
From: rjlowe@iupui.edu
</code></pre></div></div>

<h3 id="52-skipping-with-continue">5.2 Skipping with continue</h3>

<p>We can convienently skip a line by using the continue statement</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fhand = open('mbox-short.txt')
for line in fhand:
    line = line.rstrip()
    if not line.startswith('From:') :
        continue
    print line
</code></pre></div></div>

<h3 id="53-using-in-to-select-lines">5.3 Using in to select lines</h3>

<ul>
  <li>We can look for a string anywhere in a line as our selection criteria</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fhand = open('mbox-short.txt')
for line in fhand:
    line = line.rstrip()
    if not '@uct.ac.za' in line : 
        continue
    print line
</code></pre></div></div>

<hr />

<h2 id="6reading-file-names">6.Reading file names</h2>

<p>Prompt for File Name</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fname = raw_input('Enter the file name:  ')
fhand = open(fname)
count = 0
for line in fhand:
    if line.startswith('Subject:') :
        count = count + 1
print 'There were', count, 'subject lines in', fname

Enter the file name:  mbox.txt
There were 1797 subject lines in mbox.txt

Enter the file name: mbox-short.txt
There were 27 subject lines in mbox-short.txt
</code></pre></div></div>

<hr />

<h2 id="7dealing-with-bad-files">7.Dealing with bad files</h2>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fname = raw_input('Enter the file name:  ')
try:
    fhand = open(fname)
except:
    print 'File cannot be opened:', fname
    exit()
count = 0
for line in fhand:
    if line.startswith('Subject:') :
        count = count + 1
print 'There were', count, 'subject lines in', fname

Enter the file name: mbox.txt
There were 1797 subject lines in mbox.txt

Enter the file name: na na boo boo
File cannot be opened: na na boo boo
</code></pre></div></div>]]></content><author><name>Zerui Liang</name></author><summary type="html"><![CDATA[How to open &amp; read &amp; oprate a file.]]></summary></entry><entry><title type="html">Python Week 6 strings</title><link href="https://www.liangzerui.com/Python-Week-6-Strings/" rel="alternate" type="text/html" title="Python Week 6 strings" /><published>2015-07-14T00:00:00+00:00</published><updated>2015-07-14T00:00:00+00:00</updated><id>https://www.liangzerui.com/Python-Week%206%20Strings</id><content type="html" xml:base="https://www.liangzerui.com/Python-Week-6-Strings/"><![CDATA[<p>Basic string types and how read&amp;convert it. Indexing, looping and slicing a string.<br />
<!--more--></p>

<hr />
<aside class="sidebar__right">
<nav class="toc">
    <header><h4 class="nav__title"><i class="fa fa-file-text"></i> On This Page</h4></header>
<ul class="toc__menu" id="markdown-toc">
  <li><a href="#week-6-strings" id="markdown-toc-week-6-strings">Week 6 Strings</a>    <ul>
      <li><a href="#1string-type" id="markdown-toc-1string-type">1.String type</a></li>
      <li><a href="#2readconvert" id="markdown-toc-2readconvert">2.Read/Convert</a></li>
      <li><a href="#3indexing-strings-" id="markdown-toc-3indexing-strings-">3.Indexing strings []</a>        <ul>
          <li><a href="#31-length-of-strings" id="markdown-toc-31-length-of-strings">3.1 length of strings</a></li>
        </ul>
      </li>
      <li><a href="#4slicing-strings-24" id="markdown-toc-4slicing-strings-24">4.Slicing strings [2:4]</a></li>
      <li><a href="#5looping-through-strings-with-for-and-while" id="markdown-toc-5looping-through-strings-with-for-and-while">5.Looping through strings with for and while</a></li>
      <li><a href="#6concatenating-strings-with-" id="markdown-toc-6concatenating-strings-with-">6.Concatenating strings with +</a></li>
      <li><a href="#7string-operations" id="markdown-toc-7string-operations">7.String operations</a>        <ul>
          <li><a href="#71-string-comparison" id="markdown-toc-71-string-comparison">7.1 String Comparison</a></li>
          <li><a href="#72-searching-a-string" id="markdown-toc-72-searching-a-string">7.2 Searching a String</a></li>
          <li><a href="#73-making-everything-upper-case" id="markdown-toc-73-making-everything-upper-case">7.3 Making everything UPPER CASE</a></li>
          <li><a href="#74-search-and-replace" id="markdown-toc-74-search-and-replace">7.4 Search and Replace</a></li>
          <li><a href="#75-stripping-whitespace" id="markdown-toc-75-stripping-whitespace">7.5 Stripping Whitespace</a></li>
          <li><a href="#76-prefixes" id="markdown-toc-76-prefixes">7.6 Prefixes</a></li>
          <li><a href="#77-parsing-and-extracting" id="markdown-toc-77-parsing-and-extracting">7.7 Parsing and Extracting</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

  </nav>
</aside>

<hr />
<h1 id="week-6-strings">Week 6 Strings</h1>

<hr />
<h2 id="1string-type">1.String type</h2>

<ul>
  <li>A string is a <strong>sequence of characters</strong></li>
  <li>A string literal <strong>uses quotes</strong>  ‘Hello’ or “Hello”</li>
  <li>For strings, <strong>+ means “concatenate”</strong></li>
  <li>When a string contains numbers, it is still a string</li>
  <li>We can convert numbers in a string into a number using int()</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; str1 = "Hello"
&gt;&gt;&gt; str2 = 'there'
&gt;&gt;&gt; bob = str1 + str2
&gt;&gt;&gt; print bob
Hellothere
&gt;&gt;&gt; str3 = '123'
&gt;&gt;&gt; str3 = str3 + 1
Traceback (most recent call last):  File "&lt;stdin&gt;", line 1, in &lt;module&gt;TypeError: cannot concatenate 'str' and 'int' objects
&gt;&gt;&gt; x = int(str3) + 1
&gt;&gt;&gt; print x
124
&gt;&gt;&gt; 

</code></pre></div></div>

<hr />

<h2 id="2readconvert">2.Read/Convert</h2>

<ul>
  <li>We prefer to read data in using strings and then parse and convert the data as we need</li>
  <li>This gives us more control over error situations and/or bad user input</li>
  <li>Raw input numbers must be converted from strings</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; name = raw_input('Enter:')
Enter:Chuck
&gt;&gt;&gt; print name
Chuck
&gt;&gt;&gt; apple = raw_input('Enter:')
Enter:100
&gt;&gt;&gt; x = apple – 10
Traceback (most recent call last):  File "&lt;stdin&gt;", line 1, in &lt;module&gt;TypeError: unsupported operand type(s) for -: 'str' and 'int'
&gt;&gt;&gt; x = int(apple) – 10
&gt;&gt;&gt; print x
90

</code></pre></div></div>

<hr />

<h2 id="3indexing-strings-">3.Indexing strings []</h2>

<ul>
  <li>We can get at any <strong><em>single character</em></strong> in a string using an index specified in square brackets</li>
  <li>The index value must be an <strong><em>integer</em></strong> and starts at <strong><em>zero</em></strong></li>
  <li>The index value can be an expression that is computed</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; fruit = 'banana'
&gt;&gt;&gt; letter = fruit[1]
&gt;&gt;&gt; print letter
a
&gt;&gt;&gt; n = 3
&gt;&gt;&gt; w = fruit[n - 1]
&gt;&gt;&gt; print w
n

</code></pre></div></div>

<ul>
  <li>You will get a python error if you attempt to index beyond the end of a string.</li>
  <li>So be careful when constructing index values and slices</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; zot = 'abc'
&gt;&gt;&gt; print zot[5]
Traceback (most recent call last):  File "&lt;stdin&gt;", line 1, in &lt;module&gt;IndexError: string index out of range
&gt;&gt;&gt; 

</code></pre></div></div>

<h3 id="31-length-of-strings">3.1 length of strings</h3>

<p>There is a built-in function len that gives us the length of a string</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; fruit = 'banana'
&gt;&gt;&gt; print len(fruit)
6
</code></pre></div></div>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; fruit = 'banana'
&gt;&gt;&gt; x = len(fruit)
&gt;&gt;&gt; print x
6

</code></pre></div></div>

<blockquote>
  <p>A function is some <strong>stored code</strong> that we use. A function takes some <strong>input</strong> and produces an <strong>output</strong>.</p>
</blockquote>

<hr />

<h2 id="4slicing-strings-24">4.Slicing strings [2:4]</h2>

<ul>
  <li>We can also look at any continuous section of a string using a colon operator</li>
  <li>The second number is one beyond the end of the slice - “up to but not including”</li>
  <li>If the second number is beyond the end of the string, it stops at the end</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; s = 'Monty Python'
&gt;&gt;&gt; print s[0:4]
Mont
&gt;&gt;&gt; print s[6:7]
P
&gt;&gt;&gt; print s[6:20]
Python
</code></pre></div></div>

<ul>
  <li>If we leave off the first number or the last number of the slice, it is assumed to be the beginning or end of the string respectively</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; s = 'Monty Python'
&gt;&gt;&gt; print s[:2]
Mo
&gt;&gt;&gt; print s[8:]
Thon
&gt;&gt;&gt; print s[:]
Monty Python
</code></pre></div></div>

<hr />

<h2 id="5looping-through-strings-with-for-and-while">5.Looping through strings with for and while</h2>

<ul>
  <li>Using a while statement and an iteration variable, and the len function, we can construct a loop to look at each of the letters in a string individually</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fruit = 'banana'
index = 0
while index &lt; len(fruit) : 
   letter = fruit[index]
    print index, letter
    index = index + 1

0 b
1 a
2 n
3 a
4 n
5 a

</code></pre></div></div>

<ul>
  <li>A definite loop using a for statement is much more elegant<br />
The iteration variable is completely taken care of by the for loop</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>fruit = 'banana'
for letter in fruit : 
   print letter

b
a
n
a
n
a

</code></pre></div></div>

<ul>
  <li>This is a simple loop that loops through each letter in a string and counts the number of times the loop encounters the ‘a’ character.</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>word = 'banana'
count = 0
for letter in word :
    if letter == 'a' : 
       count = count + 1
print count

</code></pre></div></div>

<ul>
  <li>The <strong>iteration variable</strong> “iterates” through the <strong>sequence</strong> (ordered set)</li>
  <li>The <strong>block (body)</strong> of code is executed once for each value <strong>in</strong> the <strong>sequence</strong></li>
  <li>The <strong>iteration variable</strong> moves through all of the values <strong>in</strong> the <strong>sequence</strong></li>
</ul>

<hr />

<h2 id="6concatenating-strings-with-">6.Concatenating strings with +</h2>

<ul>
  <li>When the + operator is applied to strings, it means “concatenation”</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; a = 'Hello'
&gt;&gt;&gt; b = a + 'There'
&gt;&gt;&gt; print b
HelloThere
&gt;&gt;&gt; c = a + '  ' + 'There'
&gt;&gt;&gt; print c
Hello There
&gt;&gt;&gt; 
</code></pre></div></div>

<hr />

<h2 id="7string-operations">7.String operations</h2>

<ul>
  <li>Python has a number of <strong><em>string functions</em></strong> which are in the string library</li>
  <li>These functions are <strong><em>already built</em></strong> into every string - we invoke them by appending the function to the string variable</li>
  <li>These functions <strong><em>do not modify</em></strong> the original string, instead they <strong><em>return a new string</em></strong> that has been altered</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; stuff = 'Hello world’
&gt;&gt;&gt; type(stuff)&lt;type 'str'&gt;
&gt;&gt;&gt; dir(stuff)
['capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

</code></pre></div></div>

<h3 id="71-string-comparison">7.1 String Comparison</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>if word == 'banana':
    print  'All right, bananas.'

if word &lt; 'banana':
    print 'Your word,' + word + ', comes before banana.’
elif word &gt; 'banana':
    print 'Your word,' + word + ', comes after banana.’
else:
    print 'All right, bananas.'
</code></pre></div></div>

<h3 id="72-searching-a-string">7.2 Searching a String</h3>

<ul>
  <li>We use the find() function to search for a substring within another string</li>
  <li><strong><em>find()</em></strong> finds the first occurance of the substring<br />
If the substring is not found, find() returns -1<br />
Remember that string position starts at zero</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; fruit = 'banana'
&gt;&gt;&gt; pos = fruit.find('na')
&gt;&gt;&gt; print pos
2
&gt;&gt;&gt; aa = fruit.find('z')
&gt;&gt;&gt; print aa
-1
</code></pre></div></div>

<h3 id="73-making-everything-upper-case">7.3 Making everything UPPER CASE</h3>

<ul>
  <li>You can make a copy of a string in lower case or upper case</li>
  <li>Often when we are searching for a string using find()- we first convert the string to lower case so we can search a string regardless of case</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; greet = 'Hello Bob'
&gt;&gt;&gt; nnn = greet.upper()
&gt;&gt;&gt; print nnn
HELLO BOB
&gt;&gt;&gt; www = greet.lower()
&gt;&gt;&gt; print www
hello bob
&gt;&gt;&gt; 

</code></pre></div></div>

<h3 id="74-search-and-replace">7.4 Search and Replace</h3>

<ul>
  <li>The <strong><em>replace()</em></strong> function is like a “search and replace” operation in a word processor</li>
  <li>It replaces <em>all occurrences</em> of the search string with the <strong><em>replacement string</em></strong></li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; greet = 'Hello Bob'
&gt;&gt;&gt; nstr = greet.replace('Bob','Jane')
&gt;&gt;&gt; print nstr
Hello Jane
&gt;&gt;&gt; nstr = greet.replace('o','X')
&gt;&gt;&gt; print nstrHellX BXb
&gt;&gt;&gt; 
</code></pre></div></div>

<h3 id="75-stripping-whitespace">7.5 Stripping Whitespace</h3>

<ul>
  <li>Sometimes we want to take a string and remove whitespace at the beginning and/or end</li>
  <li><strong><em>lstrip()</em></strong> and <strong><em>rstrip()</em></strong> to the left and right only</li>
  <li><strong><em>strip()</em></strong> Removes both begin and ending whitespace</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; greet = '   Hello Bob  '
&gt;&gt;&gt; greet.lstrip()
'Hello Bob  '
&gt;&gt;&gt; greet.rstrip()
'   Hello Bob'
&gt;&gt;&gt; greet.strip()
'Hello Bob'
&gt;&gt;&gt; 
</code></pre></div></div>

<h3 id="76-prefixes">7.6 Prefixes</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; line = 'Please have a nice day’
&gt;&gt;&gt; line.startswith('Please')
True
&gt;&gt;&gt; line.startswith('p')
False
</code></pre></div></div>

<h3 id="77-parsing-and-extracting">7.7 Parsing and Extracting</h3>

<p>From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; data = 'From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008’
&gt;&gt;&gt; atpos = data.find('@')
&gt;&gt;&gt; print atpos
21
&gt;&gt;&gt; sppos = data.find(' ',atpos)
&gt;&gt;&gt; print sppos
31
&gt;&gt;&gt; host = data[atpos+1 : sppos]
&gt;&gt;&gt; print host
uct.ac.za

</code></pre></div></div>]]></content><author><name>Zerui Liang</name></author><summary type="html"><![CDATA[Basic string types and how read&amp;convert it. Indexing, looping and slicing a string.]]></summary></entry><entry><title type="html">Python Week 5 loops and iterations</title><link href="https://www.liangzerui.com/Python-Week-5-Loops-and-iterations/" rel="alternate" type="text/html" title="Python Week 5 loops and iterations" /><published>2015-07-13T00:00:00+00:00</published><updated>2015-07-13T00:00:00+00:00</updated><id>https://www.liangzerui.com/Python-Week%205%20Loops%20and%20iterations</id><content type="html" xml:base="https://www.liangzerui.com/Python-Week-5-Loops-and-iterations/"><![CDATA[<p>Introduces loops and iterations, example of infinite loop and using break&amp;continue.<br />
<!--more--></p>

<hr />
<aside class="sidebar__right">
<nav class="toc">
    <header><h4 class="nav__title"><i class="fa fa-file-text"></i> On This Page</h4></header>
<ul class="toc__menu" id="markdown-toc">
  <li><a href="#week-5-loops-and-iterations" id="markdown-toc-week-5-loops-and-iterations">Week 5 Loops and iterations</a>    <ul>
      <li><a href="#1-while-loops-indefinite" id="markdown-toc-1-while-loops-indefinite">1. While loops (indefinite)</a></li>
      <li><a href="#2-infinite-loops" id="markdown-toc-2-infinite-loops">2. Infinite loops</a></li>
      <li><a href="#3-using-break" id="markdown-toc-3-using-break">3. Using break</a></li>
      <li><a href="#4-using-continue" id="markdown-toc-4-using-continue">4. Using continue</a></li>
      <li><a href="#5-for-loops-definite" id="markdown-toc-5-for-loops-definite">5. For loops (definite)</a></li>
      <li><a href="#6-iteration-variables" id="markdown-toc-6-iteration-variables">6. Iteration variables</a>        <ul>
          <li><a href="#61-counting-in-a-loop" id="markdown-toc-61-counting-in-a-loop">6.1 Counting in a Loop</a></li>
          <li><a href="#62-summing-in-a-loop" id="markdown-toc-62-summing-in-a-loop">6.2 Summing in a Loop</a></li>
          <li><a href="#63-finding-the-average-in-a-loop" id="markdown-toc-63-finding-the-average-in-a-loop">6.3 Finding the Average in a Loop</a></li>
          <li><a href="#64-filtering-in-a-loop" id="markdown-toc-64-filtering-in-a-loop">6.4 Filtering in a Loop</a></li>
          <li><a href="#65-search-using-a-boolean-variable" id="markdown-toc-65-search-using-a-boolean-variable">6.5 Search Using a Boolean Variable</a></li>
        </ul>
      </li>
      <li><a href="#7-largest-or-smallest" id="markdown-toc-7-largest-or-smallest">7. Largest or smallest</a></li>
    </ul>
  </li>
</ul>

  </nav>
</aside>

<hr />
<h1 id="week-5-loops-and-iterations">Week 5 Loops and iterations</h1>

<hr />
<h2 id="1-while-loops-indefinite">1. While loops (indefinite)</h2>

<p><strong>Loops</strong> (repeated steps) have <strong>iteration variables</strong> that change each time through a loop.  Often these iteration</p>

<blockquote>
  <p>While loops are called “indefinite loops” because they keep going until   a logical condition becomes False</p>
</blockquote>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>n = 5
while n &gt; 0 :
    print n
    n = n – 1
print 'Blastoff!'
print n

</code></pre></div></div>

<h2 id="2-infinite-loops">2. Infinite loops</h2>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>n = 5
while n &gt; 0 :
    print 'Lather’
    print 'Rinse'
print 'Dry off!'

</code></pre></div></div>

<h2 id="3-using-break">3. Using break</h2>

<ul>
  <li>The <strong>break</strong> statement <strong>ends</strong> the <strong>current loop</strong> and jumps to the statement immediately following the loop</li>
  <li>It is like a loop test that can happen anywhere in the body of the loop</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>while True:
    line = raw_input('&gt; ')
    if line == 'done' :
        break
    print line
print 'Done!'
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt; hello there
hello there
&gt; finished
finished
&gt; done
Done!
</code></pre></div></div>

<h2 id="4-using-continue">4. Using continue</h2>
<p>The <strong>continue</strong> statement ends the current iteration and jumps to the <strong>top of the loop</strong> and starts the next iteration</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>while True:
    line = raw_input('&gt; ')
    if line[0] == '#' :
        continue
    if line == 'done' 
:        break
    print line
print 'Done!'

</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt; hello there
hello there
&gt; # don't print this
&gt; print this!
print this!
&gt; done
Done!
</code></pre></div></div>

<h2 id="5-for-loops-definite">5. For loops (definite)</h2>

<ul>
  <li>Quite often we have a <strong>list</strong> of items of the <strong>lines in a file</strong> effectively a <strong>finite set</strong> of things</li>
  <li>We can write a loop to run the loop once for each of the items in a set using the Python <strong>for</strong> construct</li>
  <li>These loops are called “<strong>definite loops</strong>” because they execute an exact number of times</li>
  <li>We say that “<strong>definite loops iterate through the members of a set</strong>”</li>
</ul>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends : 
   print 'Happy New Year:',  friend
print 'Done!'
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!
</code></pre></div></div>

<h2 id="6-iteration-variables">6. Iteration variables</h2>

<ul>
  <li>The iteration variable “iterates” though the sequence (ordered set)</li>
  <li>The block (body) of code is executed once for each value in the sequence</li>
  <li>The iteration variable moves through all of the values in the sequence</li>
</ul>

<h3 id="61-counting-in-a-loop">6.1 Counting in a Loop</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>zork = 0
print 'Before', zork
for thing in [9, 41, 12, 3, 74, 15] :
    zork = zork + 1
    print zork, thing
print 'After', zork

#To count how many times we execute a loop we introduce a counter variable that starts at 0 and we add one to it each time through the loop.

$ python countloop.py
Before 0
1 9
2 41
3 12
4 3
5 74
6 15
After 6

</code></pre></div></div>

<h3 id="62-summing-in-a-loop">6.2 Summing in a Loop</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>zork = 0
print 'Before', zork
for thing in [9, 41, 12, 3, 74, 15] :
    zork = zork + thing
    print zork, thing
print 'After', zork

#To add up a value we encounter in a loop,  we introduce a sum variable that starts at 0 and we add the value to the sum each time through the loop.

$ python countloop.py 
Before 0
9 9
50 41
62 12
65 3
139 74
154 15
After 154
</code></pre></div></div>

<h3 id="63-finding-the-average-in-a-loop">6.3 Finding the Average in a Loop</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>count = 0
sum = 0
print 'Before', count, sum
for value in [9, 41, 12, 3, 74, 15] :
    count = count + 1
    sum = sum + value
    print count, sum, value
print 'After', count, sum, sum / count

#An average just combines the counting and sum patterns and divides when the loop is done.

$ python averageloop.py 
Before 0 0
1 9 9
2 50 41
3 62 12
4 65 3
5 139 74
6 154 15
After 6 154 25
</code></pre></div></div>

<h3 id="64-filtering-in-a-loop">6.4 Filtering in a Loop</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>print 'Before'
for value in [9, 41, 12, 3, 74, 15] :
    if value &gt; 20:
 	    print 'Large number',value
print 'After'

# We use an if statement in the loop to catch / filter the values we are looking for.

$ python search1.py 
Before
Large number 41
Large number 74
After
</code></pre></div></div>

<h3 id="65-search-using-a-boolean-variable">6.5 Search Using a Boolean Variable</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>found = False
print 'Before', found
for value in [9, 41, 12, 3, 74, 15] : 
   if value == 3 :
         found = True
    print found, value
print 'After', found

#If we just want to search and know if a value was found - we use a variable that starts at False and is set to True as soon as we find what we are looking for.

$ python search1.py 
Before False
False 9
False 41
False 12
True 3
True 74
True 15
After True

</code></pre></div></div>

<h2 id="7-largest-or-smallest">7. Largest or smallest</h2>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>smallest = None #特殊类型变量
print 'Before'
for value in [9, 41, 12, 3, 74, 15] :
    if smallest is None : #IS是逻辑运算符，少用 主要是为了检查是否是 none 或 false
        smallest = value
    elif value &lt; smallest : 
        smallest = value
    print smallest, value
print 'After', smallest

# We still have a variable that is the smallest so far.  The first time through the loop smallest is None so we take the first value to be the smallest.

    $ python smallest.py 
    Before
    9 9
    9 41
    9 12
    3 3
    3 74
    3 15
    After 3

</code></pre></div></div>]]></content><author><name>Zerui Liang</name></author><summary type="html"><![CDATA[Introduces loops and iterations, example of infinite loop and using break&amp;continue.]]></summary></entry><entry><title type="html">Python Week 4 functions</title><link href="https://www.liangzerui.com/Python-Week-4-Functions/" rel="alternate" type="text/html" title="Python Week 4 functions" /><published>2015-07-12T00:00:00+00:00</published><updated>2015-07-12T00:00:00+00:00</updated><id>https://www.liangzerui.com/Python-Week%204%20Functions</id><content type="html" xml:base="https://www.liangzerui.com/Python-Week-4-Functions/"><![CDATA[<p>Introduces functions prams and arguments. How to define and use founctions.<br />
<!--more--></p>

<hr />
<aside class="sidebar__right">
<nav class="toc">
    <header><h4 class="nav__title"><i class="fa fa-file-text"></i> On This Page</h4></header>
<ul class="toc__menu" id="markdown-toc">
  <li><a href="#week-4-functions" id="markdown-toc-week-4-functions">Week 4 Functions</a>    <ul>
      <li><a href="#1stored-and-reused-steps" id="markdown-toc-1stored-and-reused-steps">1.Stored (and reused) Steps</a></li>
      <li><a href="#2python-functions" id="markdown-toc-2python-functions">2.Python Functions</a>        <ul>
          <li><a href="#21-built-in-functions-that-are-provided" id="markdown-toc-21-built-in-functions-that-are-provided">2.1. <strong>Built in functions</strong> that are provided</a></li>
          <li><a href="#22-defined-functions" id="markdown-toc-22-defined-functions">2.2. <strong>Defined functions</strong></a></li>
        </ul>
      </li>
      <li><a href="#3arguments" id="markdown-toc-3arguments">3.Arguments</a>        <ul>
          <li><a href="#31-parameters" id="markdown-toc-31-parameters">3.1 Parameters</a></li>
          <li><a href="#32-return-values" id="markdown-toc-32-return-values">3.2 Return Values</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

  </nav>
</aside>

<hr />

<h1 id="week-4-functions">Week 4 Functions</h1>

<hr />
<h3 id="1stored-and-reused-steps">1.Stored (and reused) Steps</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>def hello(): #定义函数(store)
    print 'Hello'
    print 'Fun'
    
hello() #调用函数(reuse)
print 'Zip'
hello() #调用函数(reuse)
</code></pre></div></div>

<blockquote>

  <p><strong>Type Conversion</strong> <br />
Built in functions <strong>int()</strong> and <strong>float()</strong></p>
</blockquote>

<hr />

<h3 id="2python-functions">2.Python Functions</h3>

<h4 id="21-built-in-functions-that-are-provided">2.1. <strong>Built in functions</strong> that are provided</h4>

<p>-input: raw_input()<br />
-type conversions: type()<br />
-string conversions: str() int()</p>

<h4 id="22-defined-functions">2.2. <strong>Defined functions</strong></h4>

<p>-<strong>arguments</strong> as input<br />
-<strong>def</strong> to define</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>big= max('Hello world') #定义函数 不会执行
print big #调用函数 执行
</code></pre></div></div>

<blockquote>
  <p><strong>Names</strong> of built in function == <strong>New reserved words</strong></p>
</blockquote>

<hr />

<h3 id="3arguments">3.Arguments</h3>

<blockquote>
  <ul>
    <li>is a value pass into the function</li>
    <li>need to be in the ()</li>
  </ul>
</blockquote>

<h4 id="31-parameters">3.1 Parameters</h4>

<blockquote>
  <p>A parameter is a variable which we use in the functions</p>
</blockquote>

<p>definition that is a “handle” that allows the code in the function to access the arguments for a particular function invocation.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>        def greet(lang):
            if lang == 'es':
               print 'Hola’
            elif lang == 'fr':
               print 'Bonjour’
            else:
               print 'Hello’
    greet('en')Hello
    greet('es')Hola
    greet('fr')Bonjour
</code></pre></div></div>

<h4 id="32-return-values">3.2 Return Values</h4>

<blockquote>
  <p>Often a function will take its arguments, do some computation and <strong>return</strong> a value to be used as the value of the function call in the <strong>calling expression</strong>.  The return keyword is used for this.</p>
</blockquote>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt;&gt; def greet(lang):
...         if lang == 'es':
...            return 'Hola’
...         elif lang == 'fr':
...            return 'Bonjour’
...         else:
...            return 'Hello’
... &gt;&gt;&gt; print greet('en'),'Glenn’
Hello Glenn
&gt;&gt;&gt; print greet('es'),'Sally’
Hola Sally
&gt;&gt;&gt; print greet('fr'),'Michael’
Bonjour Michael
&gt;&gt;&gt; 
</code></pre></div></div>]]></content><author><name>Zerui Liang</name></author><summary type="html"><![CDATA[Introduces functions prams and arguments. How to define and use founctions.]]></summary></entry><entry><title type="html">Python Week 3 conditional execution</title><link href="https://www.liangzerui.com/Python-Week-3-Conditional-execution/" rel="alternate" type="text/html" title="Python Week 3 conditional execution" /><published>2015-07-11T00:00:00+00:00</published><updated>2015-07-11T00:00:00+00:00</updated><id>https://www.liangzerui.com/Python-Week%203%20Conditional%20execution</id><content type="html" xml:base="https://www.liangzerui.com/Python-Week-3-Conditional-execution/"><![CDATA[<p>The concept of conditional execution and basic examples.<br />
<!--more--></p>

<hr />
<aside class="sidebar__right">
<nav class="toc">
    <header><h4 class="nav__title"><i class="fa fa-file-text"></i> On This Page</h4></header>
<ul class="toc__menu" id="markdown-toc">
  <li><a href="#week-3-conditional-execution" id="markdown-toc-week-3-conditional-execution">Week 3 Conditional execution</a>    <ul>
      <li><a href="#1-conditional-steps" id="markdown-toc-1-conditional-steps">1. Conditional Steps</a></li>
      <li><a href="#2-comparison-operators" id="markdown-toc-2-comparison-operators">2. Comparison Operators</a></li>
      <li><a href="#3-logical-operators-and-or-not" id="markdown-toc-3-logical-operators-and-or-not">3. Logical operators: and or not</a></li>
      <li><a href="#4-indentation" id="markdown-toc-4-indentation">4. Indentation</a></li>
      <li><a href="#5-one-way-decisions" id="markdown-toc-5-one-way-decisions">5. One Way Decisions</a>        <ul>
          <li><a href="#51-流程图如下" id="markdown-toc-51-流程图如下">5.1 流程图如下</a></li>
          <li><a href="#52-代码如下" id="markdown-toc-52-代码如下">5.2 代码如下：</a></li>
          <li><a href="#53-显示结果如下" id="markdown-toc-53-显示结果如下">5.3 显示结果如下：</a></li>
        </ul>
      </li>
      <li><a href="#6-two-way-decisions--if---and-else-" id="markdown-toc-6-two-way-decisions--if---and-else-">6. Two way Decisions  if :  and else :</a>        <ul>
          <li><a href="#61-流程图如下" id="markdown-toc-61-流程图如下">6.1 流程图如下：</a></li>
          <li><a href="#62-代码如下" id="markdown-toc-62-代码如下">6.2 代码如下：</a></li>
        </ul>
      </li>
      <li><a href="#7-nested-decisions嵌套" id="markdown-toc-7-nested-decisions嵌套">7. Nested Decisions(嵌套)</a>        <ul>
          <li><a href="#71-流程图如下" id="markdown-toc-71-流程图如下">7.1 流程图如下：</a></li>
          <li><a href="#72-代码如下" id="markdown-toc-72-代码如下">7.2 代码如下：</a></li>
        </ul>
      </li>
      <li><a href="#8-multiway-decisions-using-elif" id="markdown-toc-8-multiway-decisions-using-elif">8. Multiway decisions using elif</a>        <ul>
          <li><a href="#81-流程图如下" id="markdown-toc-81-流程图如下">8.1 流程图如下:</a></li>
          <li><a href="#82代码如下" id="markdown-toc-82代码如下">8.2代码如下：</a></li>
          <li><a href="#83-multi-way-puzzles-which-will-never-print" id="markdown-toc-83-multi-way-puzzles-which-will-never-print">8.3 Multi-way Puzzles-Which will never print?</a></li>
        </ul>
      </li>
      <li><a href="#9-try--except-to-compensate-for-errors" id="markdown-toc-9-try--except-to-compensate-for-errors">9. Try / Except to compensate for errors</a>        <ul>
          <li><a href="#91-示例代码如下" id="markdown-toc-91-示例代码如下">9.1 示例代码如下：</a></li>
        </ul>
      </li>
      <li><a href="#10-exercise" id="markdown-toc-10-exercise">10. Exercise</a>        <ul>
          <li><a href="#101-exercise-31" id="markdown-toc-101-exercise-31">10.1 Exercise 3.1</a></li>
          <li><a href="#102-exercise-33" id="markdown-toc-102-exercise-33">10.2 Exercise 3.3</a></li>
        </ul>
      </li>
    </ul>
  </li>
</ul>

  </nav>
</aside>

<hr />

<h1 id="week-3-conditional-execution">Week 3 Conditional execution</h1>

<hr />
<h3 id="1-conditional-steps">1. Conditional Steps</h3>

<pre><code class="language-flow">st=&gt;start: x=5
e=&gt;end: print 'finis'
cond1=&gt;condition: x&lt;10?
op1=&gt;operation: print 'Smaller'
cond2=&gt;condition: x&gt;20?
op2=&gt;operation: print 'Bigger'
st-&gt;cond1-&gt;cond2
cond1(yes)-&gt;op1-&gt;e
cond1(no)-&gt;cond2
cond2(yes)-&gt;op2-&gt;e
cond2(no)-&gt;e
</code></pre>

<hr />

<h3 id="2-comparison-operators">2. Comparison Operators</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;     less than
&lt;=	  less than or equal
==    equal to
&gt;=    greater than or equal
&gt;     greater than 
!=    not equal
</code></pre></div></div>

<ol>
  <li><strong>Boolean expressions</strong> ask a question and produce a Yes or No result which we use to control program flow</li>
  <li><strong>Boolean expressions</strong> using <strong><em>comparison operators</em></strong>  evaluate to - <strong>True / False</strong> - <strong>Yes / No</strong></li>
  <li><strong>Comparison operators</strong> look at variables but <strong>do not</strong> change the variables</li>
</ol>

<hr />

<h3 id="3-logical-operators-and-or-not">3. Logical operators: and or not</h3>

<hr />

<h3 id="4-indentation">4. Indentation</h3>

<p><code class="language-plaintext highlighter-rouge">Indentation</code> <strong>DO</strong> <code class="language-plaintext highlighter-rouge">matter in python.</code></p>
<ol>
  <li><strong>Increase indent</strong> after an if statement or for statement (after : )</li>
  <li><strong>Maintain indent</strong> to indicate the scope of the block (which lines are affected by the if/for)</li>
  <li><strong>Reduce indent</strong> to back to the level of the if statement or for statement to indicate the end of the block</li>
  <li><strong><em>Blank lines are ignored</em></strong> - they do not affect indentation</li>
  <li><strong>Comments</strong> on a line by themselves <strong>are ignored</strong>
    <blockquote>
      <p><strong>Warning: Turn Off Tabs</strong> <br />
Or change the editor setting</p>
    </blockquote>
  </li>
</ol>

<hr />

<h3 id="5-one-way-decisions">5. One Way Decisions</h3>

<h4 id="51-流程图如下">5.1 流程图如下</h4>

<pre><code class="language-flow">st=&gt;start: x=5
e=&gt;end: print 'Afterwards 5'
cond1=&gt;condition: x==5?
op1=&gt;operation: print 'is 5'
op2=&gt;operation: print 'Still 5'
op3=&gt;operation: print 'Third 5'
op4=&gt;operation: print 'Before 5'
st-&gt;op4-&gt;cond1-&gt;e
cond1(yes)-&gt;op1-&gt;op2-&gt;op3-&gt;e
cond1(no)-&gt;e
</code></pre>

<h4 id="52-代码如下">5.2 代码如下：</h4>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">x</span> <span class="o">=</span> <span class="mi">5</span>
	<span class="k">print</span> <span class="s">'Before 5’
	if  x == 5 :
	    print '</span><span class="n">Is</span> <span class="mi">5</span><span class="err">’</span>
	    <span class="k">print</span> <span class="s">'Is Still 5’
	    print '</span><span class="n">Third</span> <span class="mi">5</span><span class="err">’</span>
	<span class="k">print</span> <span class="s">'Afterwards 5’
</span></code></pre></div></div>

<h4 id="53-显示结果如下">5.3 显示结果如下：</h4>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    Before 5
	Is 5
	Is Still 5
	Third 5
	Afterwards 5
</code></pre></div></div>

<hr />

<h3 id="6-two-way-decisions--if---and-else-">6. Two way Decisions  if :  and else :</h3>

<h4 id="61-流程图如下">6.1 流程图如下：</h4>

<pre><code class="language-flow">st=&gt;start: x=4
e=&gt;end: print 'All Done'
op1=&gt;operation: print 'Smaller'
op2=&gt;operation: print 'Bigger'
cond1=&gt;condition: x&gt;2
st-&gt;cond1
cond1(yes)-&gt;op2-&gt;e
cond1(no)-&gt;op1-&gt;e
</code></pre>

<h4 id="62-代码如下">6.2 代码如下：</h4>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">x</span><span class="o">=</span><span class="mi">4</span>
    <span class="k">if</span> <span class="n">x</span><span class="o">&gt;</span><span class="mi">2</span><span class="p">:</span>
	    <span class="k">print</span> <span class="s">'Bigger'</span>
	<span class="k">else</span><span class="p">:</span>
		<span class="k">print</span> <span class="s">'Smaller'</span>
	<span class="k">print</span> <span class="s">'All Done'</span>
</code></pre></div></div>

<hr />

<h3 id="7-nested-decisions嵌套">7. Nested Decisions(嵌套)</h3>

<h4 id="71-流程图如下">7.1 流程图如下：</h4>

<pre><code class="language-flow">st=&gt;start: start
e=&gt;end: end
cond1=&gt;condition: x&gt;1
cond2=&gt;condition: x&lt;100
op1=&gt;operation: print 'More than one'
op2=&gt;operation: print 'Less than 100'
op2=&gt;operation: print 'All Done'
st-&gt;cond1-&gt;e
cond1(no)-&gt;e
cond1(yes)-&gt;op1-&gt;cond2
cond2(yes)-&gt;op2-&gt;e
cond2(no)-&gt;e

</code></pre>

<h4 id="72-代码如下">7.2 代码如下：</h4>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">x</span> <span class="o">=</span> <span class="mi">42</span>

	<span class="k">if</span> <span class="n">x</span> <span class="o">&gt;</span> <span class="mi">1</span> <span class="p">:</span>
	    <span class="k">print</span> <span class="s">'More than one'</span>
	    <span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">100</span> <span class="p">:</span> 
	        <span class="k">print</span> <span class="s">'Less than 100'</span>

	<span class="k">print</span> <span class="s">'All done'</span>
</code></pre></div></div>

<hr />

<h3 id="8-multiway-decisions-using-elif">8. Multiway decisions using elif</h3>

<h4 id="81-流程图如下">8.1 流程图如下:</h4>

<pre><code class="language-flow">st=&gt;start: start
cond1=&gt;condition: x&lt;2
cond2=&gt;condition: x&lt;10
cond3=&gt;condition: x&lt;20
cond4=&gt;condition: x&lt;40
cond5=&gt;condition: x&lt;100
op1=&gt;operation: print 'Small'
op2=&gt;operation: print 'Medium'
op3=&gt;operation: print 'Big'
op4=&gt;operation: print 'Large'
op5=&gt;operation: print 'Huge'
op6=&gt;operation: print 'Ginormous'
st-&gt;cond1
cond1(yes)-&gt;op1
cond2(yes)-&gt;op2
cond3(yes)-&gt;op3
cond4(yes)-&gt;op4
cond5(yes)-&gt;op5
cond1(no)-&gt;cond2
cond2(no)-&gt;cond3
cond3(no)-&gt;cond4
cond4(no)-&gt;cond5
cond5(no)-&gt;op6-&gt;e
</code></pre>

<h4 id="82代码如下">8.2代码如下：</h4>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">2</span> <span class="p">:</span>
	    <span class="k">print</span> <span class="s">'Small'</span>
	<span class="k">elif</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">10</span> <span class="p">:</span>
	    <span class="k">print</span> <span class="s">'Medium'</span>
	<span class="k">elif</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">20</span> <span class="p">:</span> 
	    <span class="k">print</span> <span class="s">'Big'</span>
	<span class="k">elif</span> <span class="n">x</span><span class="o">&lt;</span> <span class="mi">40</span> <span class="p">:</span> 
	    <span class="k">print</span> <span class="s">'Large'</span>
	<span class="k">elif</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">100</span><span class="p">:</span>
	    <span class="k">print</span> <span class="s">'Huge'</span>
	<span class="k">else</span> <span class="p">:</span>
    <span class="k">print</span> <span class="s">'Ginormous'</span>
</code></pre></div></div>

<h4 id="83-multi-way-puzzles-which-will-never-print">8.3 Multi-way Puzzles-Which will never print?</h4>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">2</span> <span class="p">:</span>
    <span class="k">print</span> <span class="s">'Below 2'</span>
<span class="k">elif</span> <span class="n">x</span> <span class="o">&gt;=</span> <span class="mi">2</span> <span class="p">:</span> 
    <span class="k">print</span> <span class="s">'Two or more'</span>
<span class="o">**</span><span class="k">else</span> <span class="p">:</span> <span class="c1">#此行之后不执行
</span>    <span class="k">print</span> <span class="s">'Something else'</span><span class="o">**</span> 
</code></pre></div></div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">2</span> <span class="p">:</span>
    <span class="k">print</span> <span class="s">'Below 2'</span>
<span class="k">elif</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">20</span> <span class="p">:</span>
    <span class="k">print</span> <span class="s">'Below 20'</span>
<span class="o">**</span><span class="k">elif</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">10</span> <span class="p">:</span>  <span class="c1">#以下两行不执行
</span>    <span class="k">print</span> <span class="s">'Below 10'</span><span class="o">**</span>
<span class="k">else</span> <span class="p">:</span>
    <span class="k">print</span> <span class="s">'Something else'</span>
</code></pre></div></div>

<hr />

<h3 id="9-try--except-to-compensate-for-errors">9. Try / Except to compensate for errors</h3>

<ol>
  <li>You surround a dangerous section of code with <strong>try and except</strong>.</li>
  <li>If the code in the try <strong>works</strong> - the except is skipped</li>
  <li>If the code in the try <strong>fails</strong> - it jumps to the except section</li>
</ol>

<h4 id="91-示例代码如下">9.1 示例代码如下：</h4>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">rawstr</span> <span class="o">=</span> <span class="nb">raw_input</span><span class="p">(</span><span class="s">'Enter a number:'</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span> 
    <span class="n">ival</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">rawstr</span><span class="p">)</span>
<span class="k">except</span><span class="p">:</span> 
    <span class="n">ival</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span>

<span class="k">if</span> <span class="n">ival</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="p">:</span>  
    <span class="k">print</span> <span class="s">'Nice work'</span><span class="k">else</span><span class="p">:</span>  
    <span class="k">print</span> <span class="s">'Not a number'</span>
</code></pre></div></div>

<hr />

<h3 id="10-exercise">10. Exercise</h3>

<h4 id="101-exercise-31">10.1 Exercise 3.1</h4>

<p>Rewrite your pay computation to give the employee 1.5 times the hourly rate for hours worked above40 hours.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">hours</span><span class="o">=</span><span class="nb">raw_input</span><span class="p">(</span><span class="s">"How many hours do you work per week?</span><span class="se">\n</span><span class="s">"</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span> 
    <span class="n">Hours</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">hours</span><span class="p">)</span>
    <span class="n">rate</span><span class="o">=</span><span class="nb">raw_input</span><span class="p">(</span><span class="s">"How much do you get paid per hour?</span><span class="se">\n</span><span class="s">"</span><span class="p">)</span>
    <span class="k">try</span><span class="p">:</span> 
        <span class="n">Rate</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">rate</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">Hours</span> <span class="o">&lt;</span> <span class="mi">40</span> <span class="p">:</span>
            <span class="n">TotalPay</span><span class="o">=</span><span class="nb">float</span><span class="p">(</span><span class="n">Hours</span><span class="p">)</span><span class="o">*</span> <span class="nb">float</span><span class="p">(</span><span class="n">Rate</span><span class="p">)</span>
            <span class="k">print</span> <span class="s">"So, you get paid "</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">TotalPay</span><span class="p">)</span> <span class="o">+</span> <span class="s">" per week?"</span> 
        <span class="k">else</span><span class="p">:</span>
            <span class="n">TotalPay</span><span class="o">=</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="n">Hours</span><span class="p">)</span><span class="o">-</span><span class="mi">40</span><span class="p">)</span><span class="o">*</span><span class="mf">1.5</span><span class="o">*</span><span class="nb">float</span><span class="p">(</span><span class="n">Rate</span><span class="p">)</span><span class="o">+</span><span class="mi">40</span><span class="o">*</span><span class="nb">float</span><span class="p">(</span><span class="n">Rate</span><span class="p">)</span>
            <span class="k">print</span> <span class="s">"So, you get paid "</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">TotalPay</span><span class="p">)</span> <span class="o">+</span> <span class="s">" dollars per week?"</span>
    <span class="k">except</span><span class="p">:</span> 
        <span class="n">Rate</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span>
    <span class="k">if</span> <span class="n">Rate</span> <span class="o">&lt;</span><span class="mi">0</span> <span class="p">:</span>
        <span class="k">print</span> <span class="s">"Please enter numeric input!"</span>
<span class="k">except</span><span class="p">:</span> 
    <span class="n">Hours</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span>
<span class="k">if</span> <span class="n">Hours</span> <span class="o">&lt;</span><span class="mi">0</span> <span class="p">:</span>
    <span class="k">print</span> <span class="s">"Please enter numeric input!"</span>
</code></pre></div></div>

<h4 id="102-exercise-33">10.2 Exercise 3.3</h4>

<p>Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range print an error. If the score is between 0.0 and 1.0, print a grade using the following table:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">score</span><span class="o">=</span><span class="nb">raw_input</span><span class="p">(</span><span class="s">"Please input the score!</span><span class="se">\n</span><span class="s">"</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">Score</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="n">score</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">Score</span> <span class="o">&lt;</span> <span class="mf">0.6</span> <span class="p">:</span>
        <span class="k">print</span> <span class="s">"Your Grade is F!"</span>
    <span class="k">elif</span> <span class="n">Score</span> <span class="o">&lt;</span> <span class="mf">0.7</span> <span class="p">:</span>
        <span class="k">print</span> <span class="s">"Your Grade is D!"</span>
    <span class="k">elif</span> <span class="n">Score</span> <span class="o">&lt;</span> <span class="mf">0.8</span> <span class="p">:</span>
        <span class="k">print</span> <span class="s">"Your Grade is C!"</span>
    <span class="k">elif</span> <span class="n">Score</span> <span class="o">&lt;</span> <span class="mf">0.9</span> <span class="p">:</span>
        <span class="k">print</span> <span class="s">"Your Grade is B!"</span>
    <span class="k">elif</span> <span class="n">Score</span> <span class="o">&lt;</span> <span class="mf">1.0</span> <span class="p">:</span>
        <span class="k">print</span> <span class="s">"Your Grade is A!"</span>
    <span class="k">else</span> <span class="p">:</span>
        <span class="k">print</span> <span class="s">"Please enter the right score!"</span>
<span class="k">except</span><span class="p">:</span>
    <span class="n">Score</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span>
<span class="k">if</span> <span class="n">Score</span> <span class="o">&lt;</span> <span class="mi">0</span> <span class="p">:</span>
    <span class="k">print</span> <span class="s">"Error, please enter numeric input!"</span>
</code></pre></div></div>]]></content><author><name>Zerui Liang</name></author><summary type="html"><![CDATA[The concept of conditional execution and basic examples.]]></summary></entry><entry><title type="html">Python Week 2 expressions</title><link href="https://www.liangzerui.com/Python-Week-2-Expressions/" rel="alternate" type="text/html" title="Python Week 2 expressions" /><published>2015-07-10T00:00:00+00:00</published><updated>2015-07-10T00:00:00+00:00</updated><id>https://www.liangzerui.com/Python-Week%202%20Expressions</id><content type="html" xml:base="https://www.liangzerui.com/Python-Week-2-Expressions/"><![CDATA[<p>This lecture introduces expression and releases first two exercises<br />
<!--more--></p>

<hr />

<aside class="sidebar__right">
<nav class="toc">
    <header><h4 class="nav__title"><i class="fa fa-file-text"></i> On This Page</h4></header>
<ul class="toc__menu" id="markdown-toc">
  <li><a href="#week-2-expressions" id="markdown-toc-week-2-expressions">Week 2 expressions</a>    <ul>
      <li><a href="#1-values-and-types" id="markdown-toc-1-values-and-types">1. Values and types</a></li>
      <li><a href="#15-exercises" id="markdown-toc-15-exercises">15. Exercises</a></li>
      <li><a href="#exercises-22" id="markdown-toc-exercises-22">Exercises 2.2</a></li>
    </ul>
  </li>
</ul>

  </nav>
</aside>

<hr />

<h1 id="week-2-expressions">Week 2 expressions</h1>

<hr />

<h3 id="1-values-and-types">1. Values and types</h3>

<hr />

<h3 id="15-exercises">15. Exercises</h3>

<h3 id="exercises-22">Exercises 2.2</h3>

<p>Write a program that uses raw_input to prompt a user for their name and then welcomes them.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Name</span><span class="o">=</span><span class="nb">raw_input</span><span class="p">(</span><span class="s">'Hi! What is your name?</span><span class="se">\n</span><span class="s">'</span><span class="p">)</span>
<span class="k">print</span> <span class="s">'Hello '</span><span class="o">+</span> <span class="n">Name</span> <span class="o">+</span> <span class="s">', welcome to the new world !'</span>
</code></pre></div></div>

<p>2.3 Write a program to prompt the user for hours and rate per hour to compute gross pay</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Hours</span><span class="o">=</span><span class="nb">raw_input</span><span class="p">(</span><span class="s">"How many hours do you work per day?</span><span class="se">\n</span><span class="s">"</span><span class="p">)</span>
<span class="n">Rate</span><span class="o">=</span><span class="nb">raw_input</span><span class="p">(</span><span class="s">"How much do you get paid for an hours?</span><span class="se">\n</span><span class="s">"</span><span class="p">)</span>
<span class="n">TotalHours</span><span class="o">=</span><span class="nb">float</span><span class="p">(</span><span class="n">Hours</span><span class="p">)</span><span class="o">*</span> <span class="nb">float</span><span class="p">(</span><span class="n">Rate</span><span class="p">)</span>
<span class="k">print</span> <span class="s">"So, you work "</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">TotalHours</span><span class="p">)</span> <span class="o">+</span> <span class="s">" hours per week?"</span>
</code></pre></div></div>

<p>2.5 Write a program to prompt the user for a Celsius temperature, convert the temperature to Fahrenheit and print out the converted temperature.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Ctemp</span><span class="o">=</span><span class="nb">raw_input</span><span class="p">(</span><span class="s">"Please enter the Celsius temperature:</span><span class="se">\n</span><span class="s">"</span><span class="p">)</span>
<span class="n">Ftemp</span><span class="o">=</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">Ctemp</span><span class="p">)</span><span class="o">*</span><span class="mi">9</span><span class="o">/</span><span class="mi">5</span><span class="p">)</span><span class="o">+</span><span class="mi">32</span>
<span class="k">print</span> <span class="nb">str</span><span class="p">(</span><span class="n">Ctemp</span><span class="p">)</span> <span class="o">+</span> <span class="s">' degree celsius is '</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">Ftemp</span><span class="p">)</span> <span class="o">+</span> <span class="s">' degree fahrenheit!</span><span class="se">\n</span><span class="s"> '</span>
</code></pre></div></div>]]></content><author><name>Zerui Liang</name></author><summary type="html"><![CDATA[This lecture introduces expression and releases first two exercises]]></summary></entry></feed>