Python ch. 3 (If statements and conditionals)

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Conditional Statements

Let us write programs where we choose our path. These conditional statements are what allow us to get to a huge variety of different outcomes. Our choices are based on comparisons and decisions made by if-then-else statements.

Branching

Another word used for a conditional.

Aliasing in Function Calls

Aliasing occurs when we use list parameters as well, since parameters are variables.

Where Did My List Go

>>> colors = 'red orange yellow green blue purple'.split() >>> colors ['blue', 'green', 'orange', 'purple', 'red', 'yellow'] >>> sorted_colors = colors.sort() >>> print sorted_colors None #Beginning programmers often forget that many list methods return None rather than creating and returning a new list. (Expe- rienced programmers sometimes forget too.) As a result, their lists sometimes seem to disappear.

Docstring

A docstring is pretty much the same as a comment.

Line

A line is defined as including all the characters up to and including the end of line marker.

Indention with if statement

After the line beginning with if we will have the result of what should happen if the statement were true. This line should be indented by four spaces.

Reading data from a file

In order to read data from a file, we must first open it using Python's built-in function open: file = open("data.txt", "r") The first argument to open is a string containing the name of the file. The second argument indicates a mode. The three options are "r" for reading, "w" for writing, and "a" for appending. (The difference between writing and appending is that writing a file erases anything that was already in it, while appending adds new data to the end.) The result of open is not the contents of the file. Instead, open returns a file object whose methods allow the program to access the contents of the file.

If-then-else nesting example(if False)

Let's assume the first condition was false. We would skip the entire indented first section, including the nested if statement. We would go straight to the else portion of the other statement. Ex: if False: print("It is cold.") if True: print("The heater is already on.") else: print("Turning the Heater on.") else: print("It is warm enough.") OUTPUT: It is warm enough.

Comparisons example 1

Let's define 3 variables-a, b and c. Let's assign a the value 1 and b and c the values of 2. Now let's do comparisons. a = 1 b = 2 c = 2 a > b #False a < b #True a >= b #False a <= b #True

Particular types

Like all other objects, lists have a particular type, and Python complains if you try to combine types in inappropriate ways. Here's what happens if you try to add a list and a string: ['H', 'He', 'Li'] + 'Be' Traceback (most recent call last): File "<stdin>", line 1, in <module> Type error: can only concatenate list (not "str") to list. #The error report hints at the fact that we might be able to concatenate lists with lists to create new lists, just as we concatenate strings to make new strings. Ex: original = ['H', 'He', 'Li'] final = original + ['Be'] final Output: ['H', 'He', 'Li', 'Be'] #As shown above, this doesn't modify either of the original lists. Instead it creates a new list whose entires refer back to the two originals.

Nested lists

Lists are heterogeneous, meaning a list can contain any type of data,even another list. The following list displays life expectancies in different in different countries: [['Canada', 76.5], ['United States', 75.5], ['Mexico', 72.0]] # Each element of the outer list is itself a list of two items. life = [['Canada', 76.5], ['United States', 75.5], ['Mexico', 72.0]] life[0] ['Canada', 76.5] life[1] ['United States', 75.5] life[2] ['Mexico', 72.0] We use standard notations to access the items in the outer list.

Files as lists

Most data is stored in files, which just ordered sequences of bytes. Those bytes may represent characters, pixels or postal codes; the important thing is that they're in a particular order. Which means that lists are usually a natural way to work with them.

using if statements with lists

You can do some interesting work when you combine lists and if state- ments. You can watch for special values that need to be treated differently than other values in the list. You can manage changing conditions effi- ciently, such as the availability of certain items in a restaurant throughout a shift. You can also begin to prove that your code works as you expect it to in all possible situations

Using "or" to Check Multiple Conditions

age_0 = 22 age_1 = 18 age_0 >= 21 or age_1 >= 21 True age_0 = 18 age_0 >= 21 or age_1 >= 21 False

Some functions and their descriptions

len(L) - returns the number of items in list "L" max(L) - returns the maximum value in list "L" min(L) - returns the minimum value in list "L" sum(L) - returns the sum of the values in list "L"

Conditional text real example

toy = soldier print("Is toy == 'soldier'? I predict True.") print(toy == 'soldier') print("Is toy == 'airplane'? I predict False.") print(toy == 'airplane') Output: Is toy == 'soldier'? I predict True. True Is toy == 'airplane'? I predict False. False

conditional

A computer command that lets us make a decision about what option to use. We'll have a clear basis for making that decision-a way to know which choice is the right one. And depending on that choice different things will happen. Another term used for this is Branching.

Thermostat example for conditionals

A computer controlled thermostat needs to know whether or not to turn on the heat. It will have criteria, usually if the whether or not the temperature is above or below some minimum. If below it will turn on the heat, if not it will not. Some code to implement that: If the temperature is below 60 degrees... Then turn on the heater! If the temperature is between 60 and 70 degrees and if it is between 8 a.m. and 10 p.m. Then turn on the heater! If the temperature is above 80 degrees... Then turn on the air conditioner! #Start using a short piece of code using a conditional statement, if statement: if True: print("Turning on the heater!")

Aliasing

An alias is an alternative name for something. In Python, two variables are said to be aliases when they refer to the same value. The code below creates two variables, both of which refer to a single list. When we modify the list through one variable references through the other list show the change as well. Ex: celegans_markers = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma'] celegans_copy = celegans_markers celegans_markers[5] = 'Lvl' celegans_markers ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Lvl'] celegans_copy ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Lvl'] #Aliasing is one of the reasons why the notion of mutability is important. Ex, if x and y refer to the same list, than any of the changes you make in x you will see in y.

if-else statement example

An if-else block is similar to a simple if statement, but the else statement allows you to define an action or set of actions that are executed when the conditional test fails. We'll display the same message we had previously if the person is old enough to vote, but this time we'll add a message for anyone who is not old enough to vote. Ex: age = 17 if age >= 18: print("You are allowed to vote!" print("Have you registered to vote?") else: print("Sorry, you are too young to vote.") print("Please register to vote as soon as you are 18.")

Comparisons

Conditionals are only valuable when we don't know ahead of time whether the condition is True or False. We need to be able to take an expression and determine whether that expression is True or False. The most common way to do this is with comparisons, which let us compare two values.

Slicing

Geneticists describe C. elegans (nematodes, or microscopic worms) using three-letter short-form markers. Examples include Emb (embry- onic lethality), Him (High incidence of males), Unc (Uncoordinated), Dpy (dumpy: short and fat), Sma (small), and Lon (long). We can thus keep a list: celegans_markers = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma'] celegans_markers Output: ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma'] Dpy and Sma works are not that different from each other, so they are not as useful as markers as complex strains. We can produce a new list based on celegan_markers, but without Dpy or Sma, by taking a slice of the list. Ex: celegans_markers = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma'] useful_markers = celegan_markers[0:4] #The first index in the slice is the starting point the second index is one more than the index we want to use. So, list [i:j] is a slice from the original list from index I, inclusive up to, but not including index j. The first index can be omitted if we want to slice from the beginning of the list, and the last index can be omitted if we want to slice from the end. Ex: celegans_markers = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma'] celegan_markers[:4] Output: ['Emb', 'Him', 'Unc', 'Lon'] celegab_markers[4:] Output: ['Dpy', 'Sma'] #To create an entire copy of the list we just omit both indices so that the slice run from the start of the list to the end. Ex: celegans_markers = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma'] celegans_copy = celegans_markers[:] celegans_markers[5] = 'Lvl' >>> celegans_markers ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Lvl'] celegans_copy ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma']

Nesting Loops

He block of a statement inside a loop can also contain another loop. For example this program loops over the list inner once for each element of the list outer: outer = ['Li', 'Na', 'K'] inner = ['F', 'Cl', 'Br'] for metal in outer: for gas in inner: print(metal + gas) Output: LiF LiCl LiBr NaF NaCl NaBr KF KCl KBr #If the outer loop has N(o) iterations and the inner loop executes the N(i) times for each of them, the inner loop will execute a number of N(o)N(i) times. For every index execution in the outer loop the inner loop elements are executed three different times. Example (LiF, LiCl, LiBr) A special case of this is when

List methods 2

Here is a simple example of how we can use methods to form a list about the colors of the rainbow: colors = 'red orange green black blue'.split() colors.append('purple') Colors ['red', 'orange', 'green', 'black', 'blue', 'purple'] Ex 2: colors.insert(2, 'yellow') colors ['red', 'orange', 'yellow', 'green', 'black', 'blue', 'black', 'purple'] colors.remove('black') colors ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] It is important to note that all of these methods modify a list instead of creating a new one. They do this because lists can grow to be enormous, a million patient records for example. Creating a new list could slow python down to the point where it would not be useful. Finally, a call to append is not the same as using +. First, append appends a single value, while + expects two lists as operands. Second, append modifies the list rather than creating a new one.

ReadLine method

If a file contains text and we probably want to process it one line at a time. We can use the file objects readline method to do this, which reads the next line of text from the file. Python calls it for us automatically when a file object is used in a for loop. Assume this data is in a file called data.txt: Mercury Venus Earth Mars This program opens that file and prints the length of each line: data = open('data.txt', 'r') for line in data: print len(line) ... 8 6 6 5 #There are only four characters in the word Mars, but our program is reporting that the line is five characters long. The reason for this is that each of the lines we read from the file has an end-of-line character at the end. We can get rid of it using string.strip, which returns a copy of a string that has leading and trailing whitespace characters (spaces, tabs, and newlines) stripped away: data = open('data.txt', 'r') for line in data: print len(line.strip()) 7 5 5 4 #Using string.strip, we can now produce the correct output when reading from our file: Download lists/fileinputloop_strip.cmd file = open('data.txt', 'r') for line in file: line = line.strip() print len(line) 7 5 5 4

Methods and their descriptions

L.append(v)-appends value v to list L L.insert(i,v)-Inserts value v at index i in list L. L.remove(v)-removes the first occurrence of value v in list L. L.reverse()-reverse the order of the values in list L. L.sort()-sorts the values in list L in ascending order(for strings, alphabetical order) L.pop()-removes and returns the last element of L.(which must me non empty.)

If statement practical use

Let's say we have a variable representing someone's age and we want to see if that person is old enough to vote. Ex: age = 19 if age >= 18: print("You are old enough to vote.") Output: You are old enough to vote! #All indented lines after an if statement will be executed if the test passes, and the entire block of indented lines will be ignored if the test does not pass. You can have as many lines of code as you want in the block follow- ing the if statement. Let's add another line of output if the person is old enough to vote, asking if the individual has registered to vote yet: Ex age = 19 if age >= 18: print("You are allowed to vote!") print("Have you voted yet?") Output: You are allowed to vote! Have you voted yet? #The conditional test passes, and both print statements are indented, so both lines are printed.

Other kinds of sequences

Lists aren't the only kind of sequences in Python. You've already met one of the others, a string. A string is an immutable sequence of characters. He sequence part means it can be indexed and sliced like a list to create new strings: rock = 'anthracite' rock[9] 'e' rock[0:3] 'ant' rock[-5:] 'acite' for character in rock[:5] print character a n t h r

Lists are heterogeneous

Lists can contain any type of data including integers, string and even other lists. Below is a list of information about the element krypton, including its name, symbol, melting point in degrees Celsius and boiling point in degrees Celsius. krypton = ['krypton', 'kr', '-157.2', '-153.5'] krypton[1] Output: kr krypton[2] Output: -157.199999

Processing list items

Lists were invented so that we wouldn't have to create a thousand variables to store a thousand values. For the same reason, Python has a "for" loop that lets us process each element in a list in turn, without having to write one statement per element. Below is the general form of a "for" loop: for variable in list: block #A block is just a sequence of one or more statements. When Python encounters a loop it executes the loops block once for each value in the list. Each pass through the block is called an iteration. Python assigns the next value in the list to the specified variable. In this way the program can do something with each value in turn. The code below prints every velocity of a falling object in metric and imperial units: velocities = [0.0, 9.81, 19.62, 29.43] for v in velocities: print("Metric:", v, "m/sec") print("Imperial:", v * 3.28, "ft/sec) Output: Metric: 0.0 m/sec; Imperial: 0.0 ft/sec Metric: 9.81 m/sec; Imperial: 32.1768 ft/sec Metric: 19.62 m/sec; Imperial: 64.3536 ft/sec Metric: 29.43 m/sec; Imperial: 96.5304 ft/sec #2 other things to notice about loop above: 1) In English we would say,"for each velocity in the list print the metric value, then print the imperial value." 2) As with function definitions, the statements in this block are indented. (Four spaces) In the case above, we created a new variable "v", to store the current value taken from the list inside the loop. We could equally have used an existing variable. The loop still starts with the first element of the list, whatever value the variable had before the loop is lost: speed = 2 velocities = [0.0, 9.81, 19.62, 29.43] for speed in velocities: print("Metric: ", speed, "m/sec") print("Final: ", speed) Metric: 0.0 m/sec Metric: 9.81 m/sec Metric: 19.62 m/sec Metric: 29.43 m/sec Final: 29.43 #The variable is left holding its last value (Final: 29.43). The last print statement is not indented and is not inside the "for" loop. It is executed after the "for" loop is finished and is executed only once.

if-elif-else statement

Often, you'll need to test more than two possible situations, and to evaluate these you can use Python's if-elif-else syntax. Python executes only one block in an if-elif-else chain. It runs each conditional test in order until one passes. Example: An amusement park that charges different rates for different ages. Admission for anyone under age 4 is free. • Admission for anyone between the ages of 4 and 18 is $5. • Admission for anyone age 18 or older is $10. age = 12 if age < 4: print("Free admission") elif age < 18: print("Cost is $5.") else: print("Cost is $10." Output: Cost is $5. #10. Rather than printing the admission price within the if-elif-else block, it would be more concise to set just the price inside the if-elif-else chain and then have a simple print statement that runs after the chain has been evaluated: age = 12 if age < 4: price = 0 elif age < 18: price = 5 else: price = 10 print("Your admission cost is $" + str(price) + ".") Output: Your admission cost is $5.

Tuples

Python also has an immutable sequence type called a tuple. Tuples are written using parentheses instead of brackets. Like strings and lists: they can be subscripted, sliced and looped over: bases = ('A', 'C', 'G', 'T') for b in bases print(b) Output: A C G T #Although the () represents the empty tuple, a tuple with one element is not written as (x), but instead as (x,) with a trailing comma. This must be done to avoid ambiguity. If the trailing comma weren't required, (5 + 3) could mean either 8 (under the normal rules of arithmetic) or the tuple containing only the value 8. This is one of the few places where Python's syntax leaves something to be desired. Once a tuple is created it can not be changed: life = (['Canada', 76.5], ['United States', 75.5], ['Mexico', 72.0]) life[0] = life[1] Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object does not support item assignment life[0][1] = 80 life (['Canada', 80.0], ['United States', 75.5], ['Mexico', 72.0]) The references contained in a tuple cannot be changed after the tuple has been created, though the objects referred to may themselves change. Tuples exist because they make some operations more efficient and some safer.

Omitting the else block

Python does not require any else block at the end of an if-elif chain. Sometimes an else block is useful, sometimes an elif block is more useful because it catches to specific condition at use. Ex: Ex: age = 66 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 elif age >= 65: price = 5 print("Your cost of admission is $" + str(age) + ".") Output: Your cost of admission is $5.

Boolean for thermostat example

Say we have a Boolean variable "temp_is_low." Then instead of saying "if True" will be "if temp_is_low." In example below the output is still "Turning on the heater!" whenever "temp_is_low" is true. Ex: temp_is_low = True if temp_is_low: print("Turning on the heater!") else: print("Temperature is fine.") Output: Turning on the heater!

Modifying lists

Say we're typing in a list of the noble gases and our fingers slip. nobles = ['helium', 'none', 'argon', 'krypton', 'xenon', 'radon'] #the error here is that we typed 'none' instead of 'neon.' Rather than retyping the entire list, we can assign a new value to a specific element of the list: nobles = ['helium', 'none', 'argon', 'krypton', 'xenon', 'radon'] nobles[1] = neon nobles Output: ['helium', 'neon', 'argon', 'krypton', 'xenon', 'radon'] This lady example shows that lists are mutable, which means that there contents can be changed after they have been created. A noble gas is one whose outer most electron shell is completely full, which makes it chemically inert.

If statement BMW example

Say you have a list of cars you want to print out in title case. Though most car names are proper names "bmw" should be printed in all caps. The following code loops through a list of car names and looks for the value "bmw". Whenever the value is "bmw" it is printed in uppercase rather than title case. Ex: cars = ['audi', 'bmw', 'subaru', 'toyota'] for car in cars: if car == 'bmw' print(car.upper()) else print(car.title()) Output: Audi BMW Subaru Toyota #The loop in this example first checks of the value of car in cars is 'bmw', if it is the value will be upper case if not it will be title case.

Boolean variable

So far we've written everything out as true or false which assumes what we want the computer to find. If we know at the time we write the code if the statement is true or false, we don't even need a condition. Instead of writing true or false for the condition we need a value that can make the condition either true or false. This is called a BOOLEAN. A Boolean variable is a variable that can be either true or false.

Built in functions on lists

Some built in functions such as "len" can be applied to lists as well as can others that we haven't seen before. Below is an example in action working on the half-lives of our plutonium isotopes: half_lives = ['87.74', '24110.0', '6537.0', '14.4', '376000.0'] len(half_lives) Output: 5 max(half_lives) Output: 376000.0 min(half_lives) Output: 14.4 sum(half_lives) Output: 406769.14000000001 #We can use the results of built functions in expressions, the following code demonstrates that we can check whether an index is in range: half_lives = ['87.74', '24110.0', '6537.0', '14.4', '376000.0'] i = 2 0 <= i < len(half_lives) Output: True half_lives[i] Output: 6537.0 #The half life of a radioactive substance is the time taken for half of it to decay. After twice this time has gone by, three quarters of the material will have decayed, after three times, seven eighths and so on.

Checking whether a value is in a list

Sometimes it's important to check if a list contains a certain value before taking an action. For instance you might want to check if a new username already exists in a list of current user names before registering a user. In a mapping project you might want to check if a certain location already exists in a list of locations. To find out whether a particular value already exists in a list use the keyword "in". Let's consider some code you might write for a pizzeria. We'll make a list of toppings a customer has requested for a pizza and then check whether certain toppings are in the list. Ex: requested_toppings = ['mushrooms', 'onions', 'pineapples'] 'mushrooms' in requested_toppings True 'pepperonis' in requested_toppings False

Checking whether a value is not in a list

Sometimes it's important to check if a value is not in a list. To do this use the keyword "not." For example consider a list of users who are banned from commenting in a forum. You can check whether that user is banned before allowing them to submitted a comment. Ex: banned_users = ['andrew', 'carolina', 'david'] user = 'marie' if user not in banned_users: print(user.title() + ",you can post a response if you wish.") Output: Marie, you can post a response if you wish. Ex: banned_users = ['andrew', 'carolina', 'david'] user = 'andrew ' if user not in banned_users: print(user.title() + ",you can post a response if you wish.") else: print("You are banned.") Output: You are banned.

Conditional if-then-else statement

Suppose the thermostats decision is more complicated. Maybe it has a different minimum depending on the time of day. And maybe it also controls an air conditioner, and it turns on the ac if you get above the maximum temperature. For this we use an if-then-else statement with two sets of code that can be executed. One set if the condition is true and one if the condition is false. Ex: if True: print("Turning on the heater!") else: print("Temperature is fine") Output: Turning on the heater! #This code will be printed if the condition is true. If the condition is false, temperature is fine would be printed.

Nesting

The computer executes indented commands just like it executes the first ones. That means within the indented code we can have another if-then-else statement. This is called nesting because the one statement is entirely within the bounds of the other. Think of the first if statement as being the best and the other if statement as being inside of the nest.

Meaning of the expression L[i]"List[index]"

The expression L[i] behaves just like a simple variable. If it's on the right, it means get the value of the item at location "i" in the list "L." If it's on the left, it means figure out where item "i" in list "L" is located so that we can over ride it.

Testing multiple conditions

The if-elif-else statement is powerful, but it's only appropriate to use when you need one test to pass. As soon as Python finds one test that passes it skips he rest of the tests. This behaviors is beneficial because it's efficient and allows you to test for one specific condition. But sometimes it's important to check all conditions of interest. In this case you should use a series of simple if statements with no elif or else blocks. This makes sense when more than one condition could be true. Let's reconsider the pizzeria example. If someone requests a two-topping pizza, you'll need to be sure to include both toppings on their pizza: Ex: requested_toppings = ['mushrooms', 'extra cheese'] if 'mushrooms' in requested_toppings: print("Adding mushrooms") if 'pepperoni' in requested_toppings: print("Adding pepperoni") if 'extra cheese' in requested_toppings: print("Adding extra cheese") print("Finished making your pizza!") Output: Adding mushrooms Adding extra cheese Finished making your pizza!

Boolean value

There are exactly two boolean values: True and False. Boolean values result when a boolean expression is evaluated by the Python interepreter. They have type bool. Boolean values are often used to keep track of certain conditions like whether a game is running or whether a user can edit certain content on a website: game_active = true can_edit = false #boolean expressions provide an efficient way to track the state of a program or a particular condition that is important in your program.

Immutable elements of python

Things like numbers and strings are immutable in python. You cannot for example change a letter in a string after you have created it. Methods that appear to like 'upper' actually create new strings. Ex: name = 'Darwin' capitalized = name.upper() print(capitalized) Output: DARWIN

Key to writing good code

Understanding the range of options that are out there and choosing to write code that is clear and simple.

Negative indices in python

Unlike most coding languages, Python also lets us index backwards from the end of a list. The last item is at index -1, the one before at index -2 and so on. Ex: whales = [5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, 7, 1, 3] whales[-1] Output: 3 whales[-2] Output; 1

Checking for special items

We already learned how to handle a special value within a list with the 'bmw' example, which needed to be printed in a different format than the other values in the list. Let's dive deeper into how you can handle special values within a list. Continuing with the pizzeria scenario, the pizzeria displays a message whenever a topping is added to your pizza, as its being made. The code for this action can be written efficiently by making a list of toppings the customer requested and using a loop to add each topping as its requested. Ex: requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] for requested_topping in requested_toppings: print("Adding " + requested_topping + ".") print("\nFinished making your pizza!") Output: Adding mushrooms Adding green peppers Adding extra cheese Finished making your pizza! #But what if the pizzeria runs out of green peppers. An if statement inside the "for" loop can handle this situation properly: Ex: requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] for requested_topping in requested_toppings: if requested_topping == 'green peppers': print("Sorry we are out of green peppers.") else: print("Adding " + requested_topping + ".") print("Finished making your pizza!") Output: Adding mushrooms Sorry we are out of green peppers Adding extra cheese Finished making your pizza!

Command-line arguments

When we run a pro-gram, we can send arguments to it, much like when we call a function or method. These values end up in a special variable of the system module "sys" called "argv", which is just a list of the arguments (as strings). sys.argv[0] always contains the name of the Python program being run. In this case, it is read_lines_range.py. The rest of the command-line argu- ments are in sys.argv[1], sys.argv[2], and so on. Here, then, is a program that reads all the data from a file and displays lines with line numbers within the start and end line range: ''' Display the lines of data.txt from the given starting line number to the given end line number. Usage: read_lines_range.py start_line end_line import sys if __name__ == '__main__': # get the start and end line numbers start_line = int(sys.argv[1]) end_line = int(sys.argv[2]) # read the lines of the file and store them in a list data = open('data.txt', 'r') data_list = data.readlines() data.close() # display lines within start to end range for line in data_list[start_line:end_line]: print line.strip()

Checking for Inequality

When you want to determine whether two values are not equal, you can combine an exclamation point and an equal sign (!=) Ex: requested_topping = 'mushrooms' if requested_topping != 'anchovies': print("Hold the anchovies!") #The line atucompares the value of requested_topping to the value 'anchovies'. If these two values do not match, Python returns True and executes the code following the if statement. If the two values match, Python returns False and does not run the code following the if statement. Because the value of requested_topping is not 'anchovies', the print statement is executed.

Multiplying lists

You can multiply a list by an integer to get a new list with the elements from the original list repeated a certain number of times: metals = 'Fe Ni'.split() metals*3 Output: ['Fe', 'Ni', 'Fe', 'Ni', 'Fe', 'Ni'] #As with concatenation the original list isn't modified: instead a new list is created.

Using multiple elif blocks

You can use as many "elif" blocks in your code as you want. For example, continuing with the amusement park example, if they were to run a discount for seniors you could add one more conditional test to the code to determine whether someone qualified for the senior discount. Anyone over the age of 65 pays half the general admission of $5. Ex: age = 66 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 else: price = 5 print("Your cost of admission is $" + str(age) + ".") Output: Your cost of admission is $5.

Conditional testing

cars = ['audi', 'bmw', 'subaru', 'toyota'] for car in cars: if car == 'bmw' print(car.upper()) else print(car.title()) Evaluating an expression for true or false in an "if statement." Python uses the values of True and False to decide if it should execute the code in an "if statement." If the test evaluates to true Python executes the code, if it evaluates to false Python ignores the code from the if statement. Most conditional tests compare the current value of a variable to a specific value of interest. The simplest conditional test checks whether the value of a variable is equal to the value of interest. Ex: car = 'bmw' car == 'bmw' True #First we set value of car to 'bmw' with a single equal sign. The line below check whether the value of car is 'bmw' with a double equal sign. If we tried to set the value of car to anything else in this case the test would come back as false. Ex: car = audi car ==bmw False # A single equal sign is really a statement; you might read the code atu as "Set the value of car equal to 'audi'." On the other hand, a double equal sign, like the one atv, asks a question: "Is the value of car equal to 'bmw'?"

What happens if you want to print more than one line if the condition is true?

if True: print("Turning on the heater!") print("It was too cold") Output (if true): Turning on the heater! It was too cold #if the condition were false we would again have no output. If we didn't have the second print statement indented. Nothing would change if the statement were true. But if the statement were false the second print statement would still show on output because the lack of indentation makes it unaffected by the conditional because it's no longer a part of the statement.

Boolean Expression

in programming, an expression that evaluates to True or False. Just another name for a conditional test. A Boolean value is either true or false just like the vale of an expression after it has been evaluated.

Aliasing sublist

life = [['Canada', 76.5], ['United States', 75.5], ['Mexico', 72.0]] #Since each of these items is also a list we can immediately index it again, just as we can chain together method calls or pass the result of one function call to another function: life[1:0] United States life[1:1] 75.5 We can also assign sublists to variables. life = [['Canada', 76.5], ['United States', 75.5], ['Mexico', 72.0]] canada = life[0] canada ['Canada', 76.5] canada[0] 'Canada' canada[1] 76.5 #Assigning a sublist to a variable creates an alias for that sublist. Any changes we make through the sublist reference will show up in the main list and vice versa. Ex: life = [['Canada', 76.5], ['United States', 75.5], ['Mexico', 72.0]] canada = life[0] canada[1] = 80.0 canada ['Canada', 80.0] life [['Canada', 80.0], ['United States', 75.5], ['Mexico', 72.0]]

string.split()

metals = 'Fe Ni'.split() metals * 3 ['Fe', 'Ni', 'Fe', 'Ni', 'Fe', 'Ni'] #We use string.split() to turn the string 'Fe Ni' in a two element list, ['Fe', 'Ni']. This is a common trick in Python programs. String.split() creates a list out of strings.

Boolean for thermostat example(if value is false)

temp_is_low = false if temp_is_low: print("Turning on the heater!") else: print("Temperature is fine.") Output: Temperature is fine. #Any false conditional, however nonsensical, will have the same effect: Output would be "Temperature is fine."

If-then-else nesting example(True)

if True: print("It is cold") if True: print("The heater is already on") else: print("Turning the Heater on") else: print("It is warm enough") Output: It is cold The heater is already on #looking at the code we see the if statement has its own indented code. In this case where both conditions are true, as we execute the program we would first print "It is cold" and then output "The heater is already on". The rest of the code would be skipped.

==

Double equal sign used to compare for equality. Ex: a= 1 b= 2 c= 2 a == b #False a != b #True b == c #True b != c #False a = b #This assigns b to a

List Methods

Here is a simple function that takes and list, sorts it and reverses it: def sort_and_reverse(L): #this means return list L sorted and reversed. L.sort() L.reverse() return L celegans_markers = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Lvl'] sort_and_reverse(celegans_markers) ['Unc', 'Lvl', 'Lon', 'Him', 'Emb', 'Dpy'] celegans_markers ['Unc', 'Lvl', 'Lon', 'Him', 'Emb', 'Dpy']

An expression vs. a command

In python an expression and a command are different. A command performs an action such as assigning a value to a variable. An expression is something that gets evaluated to find a value.

Lists and indices

Lists allow you to store numerous values in one place instead of creating numerous variable for each value. To create a list in python we put the values, separated by commas, inside of square brackets. A list is an object with values, and like any other object it can be assigned to a variable. Ex: whales = [5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, 7, 1, 3] Ex: A list itself is one object but may contain references to other objects. We get to the at the objects in a list by providing an "index" that specifies which one we want. The first item in a list is at index 0, the second at index 1 and so on. To refer to a particular item in the list we put the index in square brackets after a reference to the list. Ex: whales = [5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, 7, 1, 3] whales[0] Output: 5 whales[1] Output: 4 whales[12] Output: 1 whales[13] Output: 3 #You can only use indices in the range of 0 to one less than the number of values in the list. For example in the list above we can use indices 0-13 because there are 14 items in the list.

Using multiple lists

People will ask for just about anything. Especially when it comes to pizza toppings. What if a customer wants French fries on their toppings? You can use lists and if statements to make sure your input makes sense before you use it. Let's watch out for unusual topping requests before we build our pizza. Let's make an example with two lists, the first will define available toppings at the pizzeria and the second will define toppings that the user requested. This time each item in requested_toppings is checked against the list of available toppings before it's added to the pizza. Ex: available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapples', 'extra cheese'] requested_toppings = ['mushrooms', 'French fries', 'extra cheese'] for requested_topping in requested_toppings: if requested_topping in available_topping: print("Adding " + requested_topping + ".") else: print("Sorry we don't have " + requested_topping + ".") print("\nFinished making your pizza!") Output: Adding mushrooms. Sorry we don't have French fries. Adding extra cheese. Finished making your pizza!

Assigning the values in a list to other variables

We can assign the values of a list to other variables. Ex: whales = [5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, 7, 1, 3] third = whales[2] print("Third day: ", third) or print "Third day: ", third Output: Third day: 7

Checking that a list is not empty

So far with making lists we've assumed that a list has at least one item in it. Soon we will let users provide the information stored in a list so we can't assume a list has any items in it each time a list is run. For instance in the pizzeria scenario sometimes a user may not want any toppings. Ex: requested_toppings = [] if requested_toppings: for requested_topping in requested_toppings: print("Adding " + requested_topping + ".") print("Finished making your pizza!") else: print("Are you sure you want a plain pizza?") Output: Are you sure you want a plain pizza? # Instead of jumping right into a "for" loop, we do a quick check at "if requested_toppings:" When the name of a list is used in an if statement, Python returns True if the list con- tains at least one item; an empty list evaluates to False. If requested_toppings passes the conditional test, we run the same "for" loop we used in the previous example. If the conditional test fails, we print a message asking the customer if they really want a plain pizza with no toppings. If the list is not empty the output will show each requested topping being added to the list.

Ignoring case when checking inequality

Testing for inequalities is case sensitive in Python. Two values with different capitalizations are not equal. Ex: car = 'Audi' car == 'audi' False # If case matters this behavior is advantageous but if it doesn't and you just want to test the value of a variable, you can change the values of the variable to lowercase before testing. Ex: car = 'Audi' car.lower() == 'audi' True

"in"

The keyword used to check if a particular value already exists within a list.

Read

The most fundamental of these methods is read. When it is called without any arguments, it reads all the data in the file and returns it as a string of characters. If we give read a positive integer argument, it reads only up to that many characters; this is useful when we are working with very large files. If there is no more data in the file the message returns an empty string.

!=

This sign is used to compare for inequality. To check whether two things are not equal. Ex: a= 1 b= 2 c= 2 a == b #False a != b #True b == c #True b != c #False a = b #This assigns b to a

Using "and" to Check Multiple Conditions

age_0 = 22 age_1 = 18 age_0 >= 21 and age_1 >= 21 False age_1 = 22 age_0 >= 21 and age_1 >= 21 True


Set pelajaran terkait

Interpersonal Communication exam review 1

View Set

bace pretest review - biological system

View Set

Macroeconomics Exam 3: Real vs. Nominal Interest Rate

View Set

World History-Semester Exam Review

View Set

AP Environmental Science Chapter 12

View Set

Chpt 19 Family-centered care of the Child with Chronic Illness or disability Peds

View Set

Clinical CHP 2 Health Disparities

View Set

Cross Cultural Psychology Chapter 2 Part 2

View Set