Not logged in
Talk
Contributions
Create account
Log in
Navigation
Main page
About
People
Publications
Teaching
Resources
Research Blog
Wiki Functions
Recent changes
Help
Licensing
Page
Discussion
Edit
View history
Editing
Community Data Science Course (Spring 2015)/Day 1 Tutorial
(section)
From CommunityData
Jump to:
navigation
,
search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Making choices== We can use these expressions that <i>evaluate</i> to booleans to make decisions and conditionally execute code. [[File:Fork.png|100px]] ====if statements==== The simplest way to make a choice in Python is with the <code>if</code> keyword. Here's an example (don't try to type this one, just look at it for now): <code>if 6 > 5:</code><br /> <code>print("Six is greater than five!")</code> That is our first multi-line piece of code, and the way to type it at a Python prompt is a little different. Let's break down how to do this (type this out step by step): <ol> <li>First, type the<br /> <br /> <code>if 6 > 5:</code><br /> <br /> part, and press Enter. The next line will have <code>...</code> as a prompt, instead of the usual <code>>>></code>. This is Python telling us that we are in the middle of a '''code block''', and so long as we indent our code it should be a part of this code block.</li> <li>Press the spacebar 4 times to indent.</li> <li>Type<br /> <br /> <code>print("Six is greater than five!")</code><br /><br /></li> <li>Press Enter to end the line. The prompt will still be a <code>...</code></li> <li>Press Enter one more time to tell Python you are done with this code block. The code block will now execute.</li> </ol> All together, it will look like this: <pre> >>> if 6 > 5: ... print("Six is greater than five!") ... Six is greater than five! </pre> What is going on here? When Python encounters the <code>if</code> keyword, it <i>evaluates</i> the <i>expression</i> following the keyword and before the colon. If that expression is '''True''', Python executes the code in the indented code block under the <code>if</code> line. If that expression is '''False''', Python skips over the code block. In this case, because 6 really is greater than 5, Python executes the code block under the if statement, and we see "Six is greater than five!" printed to the screen. Guess what will happen with these other expressions, then type them out and see if your guess was correct: <pre> if 0 > 2: print("Zero is greater than two!") </pre> <pre> if "banana" in "bananarama": print("I miss the 80s.") </pre> ====more choices: <code>if</code> and <code>else</code>==== '''<code>if</code>''' lets you execute some code only if a condition is <code>True</code>. What if you want to execute different code if a condition is <code>False</code>? Use the '''<code>else</code>''' keyword, together with <code>if</code>, to execute different code when the <code>if</code> condition isn't <code>True</code>. Try this: <pre> sister_age = 15 brother_age = 12 if sister_age > brother_age: print("sister is older") else: print("brother is older") </pre> Like with <code>if</code>, the code block under the <code>else</code> condition must be indented so Python knows that it is a part of the <code>else</code> block. ====compound conditionals: <code>and</code> and <code>or</code>==== You can check multiple expressions together using the '''<code>and</code>''' and '''<code>or</code>''' keywords. If two expressions are joined by an <code>and</code>, they '''both''' have to be <code>True</code> for the overall expression to be <code>True</code>. If two expressions are joined by an <code>or</code>, as long as '''at least one''' is <code>True</code>, the overall expression is <code>True</code>. Try typing these out and see what you get: <pre> 1 > 0 and 1 < 2 </pre> <pre> 1 < 2 and "x" in "abc" </pre> <pre> "a" in "hello" or "e" in "hello" </pre> <pre> 1 <= 0 or "a" not in "abc" </pre> Guess what will happen when you enter these next two examples, and then type them out and see if you are correct. If you have trouble with the indenting, call over a staff member and practice together. It is important to be comfortable with indenting for tomorrow. <pre> temperature = 32 if temperature > 60 and temperature < 75: print("It's nice and cozy in here!") else: print("Too extreme for me.") </pre> <pre> hour = 11 if hour < 7 or hour > 23: print("Go away!") print("I'm sleeping!") else: print("Welcome to the cheese shop!") print("Can I interest you in some choice gouda?") </pre> You can have as many lines of code as you want in <code>if</code> and <code>else</code> blocks; just make sure to indent them so Python knows they are a part of the block. ====even more choices: <code>elif</code>==== If you need to execute code conditional based on more than two cases, you can use the '''<code>elif</code>''' keyword to check more cases. You can have as many <code>elif</code> cases as you want; Python will go down the code checking each <code>elif</code> until it finds a <code>True</code> condition or reaches the default <code>else</code> block. <pre> sister_age = 15 brother_age = 12 if sister_age > brother_age: print("sister is older") elif sister_age == brother_age: print("sister and brother are the same age") else: print("brother is older") </pre> You don't have to have an <code>else</code> block, if you don't need it. That just means there isn't default code to execute when none of the <code>if</code> or <code>elif</code> conditions are <code>True</code>: <pre> color = "orange" if color == "green" or color == "red": print("Christmas color!") elif color == "black" or color == "orange": print("Halloween color!") elif color == "pink": print("Valentine's Day color!") </pre> If color had been "purple", that code wouldn't have printed anything. '''Remember that '=' is for assignment and '==' is for comparison.''' ====In summary: the structure of if/elif/else==== Here's a diagram of <code>if/elif/else</code>: [[File:If-elif-else.png]] Do you understand the difference between <code>elif</code> and <code>else</code>? When do you indent? When do you use a colon? If you're not sure, talk about it with a neighbor or staff member.
Summary:
Please note that all contributions to CommunityData are considered to be released under the Attribution-Share Alike 3.0 Unported (see
CommunityData:Copyrights
for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource.
Do not submit copyrighted work without permission!
To protect the wiki against automated edit spam, we kindly ask you to solve the following CAPTCHA:
Cancel
Editing help
(opens in new window)
Tools
What links here
Related changes
Special pages
Page information