Conditional Statements and Boolean Expressions in Python, Exams of Programming Languages

Boolean expressions and conditional statements go hand in hand, as we will see in the exercise. ... Python uses the shorthand elif in its syntax for else if.

Typology: Exams

2022/2023

Uploaded on 02/28/2023

freddye
freddye 🇺🇸

4.3

(11)

235 documents

1 / 13

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Conditional statements
Conditional statements allow for selective execution of code depending on the outcome of a
comparison. Boolean expressions and conditional statements go hand in hand, as we will see in
the exercise.
Boolean expressions
Boolean expressions are expressions that evaluate to either true or false. They are a common
feature of programming languages. The following comparison operators are commonly used in
Boolean expressions.
Comparison Operators:
x == y # x is equal to y
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
x is y # x points to the same object as y (rarely used
)
x is not y # x does not point to the same object as y
A common error is to use = in place of == . = is an assignment operator (i.e. set x = y),
whereas == is a comparison operator (i.e. is x = y).
Assign a volume to the variable vol :
In [1]:
What type of value is the variable? Confirm your answer using the type() function:
In [2]:
When evaulated by the Python interpreter, Boolean expressions that evaulate produce special
values - True if true and False if false. True and False belong to a class of values
called bool .
Out[2]:
int
vol = 100
type(vol)
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Conditional Statements and Boolean Expressions in Python and more Exams Programming Languages in PDF only on Docsity!

Conditional statements

Conditional statements allow for selective execution of code depending on the outcome of a comparison. Boolean expressions and conditional statements go hand in hand, as we will see in the exercise.

Boolean expressions

Boolean expressions are expressions that evaluate to either true or false. They are a common feature of programming languages. The following comparison operators are commonly used in Boolean expressions. Comparison Operators: x == y # x is equal to y x != y # x is not equal to y x > y # x is greater than y x < y # x is less than y x >= y # x is greater than or equal to y x <= y # x is less than or equal to y x is y # x points to the same object as y (rarely used ) x is not y # x does not point to the same object as y A common error is to use = in place of ==. = is an assignment operator (i.e. set x = y), whereas == is a comparison operator (i.e. is x = y). Assign a volume to the variable vol : In [1]: What type of value is the variable? Confirm your answer using the type() function: In [2]: When evaulated by the Python interpreter, Boolean expressions that evaulate produce special values - True if true and False if false. True and False belong to a class of values called bool. Out[2]: (^) int vol = 100 type(vol)

In [3]: Use the == operator to test if vol is equal to 100: In [4]: Use the <= operator to determine if vol is less than or equal to 100: In [5]: Use the != operator to determine if vol is not equal to 100: In [6]: Assign an RNA sequence to two different variables, for example rna1 and rna2 : In [7]: Compare the two RNA sequences to determine if they are equivelent using == : In [8]: Compare the two RNA sequence variable from above using the is operator: In [9]: The is operator at first glance seems similar to == but it is quite different. is tests whether two values point to the same object. The variables rna1 and rna2 point to the same object, a value that python has interned or stored away. But it's dangerous to use is when making comparisons unless you know the object has been interned. Let's look at an example using a type of object we haven't seen yet, a list: Out[3]: (^) bool Out[4]: True Out[5]: True Out[6]: (^) False Out[8]: (^) True Out[9]: True type( True ) vol == 100 vol <= 100 vol != 100 rna1 = 'AUG' rna2 = 'AUG' rna1 == rna rna1 is rna

In [15]: The code above generates errors because < 105 by itself is not an expression that can be evalauted. Test if n is equal to 100 or 101: In [16]: In the example above with and we saw a harmless syntax error, harmless in that it's an easy fix and we can move on with our code. But what about this: In [17]: A far more dangerous semantics error. Test if n is not equal to 100 or 101 using the not operator: In [18]: As you can probably see, negating something with the not operator often makes code difficult to follow so when possible it should be avoided. Test if n is not eqaul to 100 or 101 using the != operator: File "<ipython-input-15-230e87afb517>", line 1 n > 95 and < 105 ^ SyntaxError: invalid syntax n is 100 or 101. n is 100 or 101. n is not 100 or 101 n > 95 and < 105 n = 100 if n == 100 or n == 101 : print("n is 100 or 101.") n = 5 if n == 100 or 101 : print("n is 100 or 101.") n = 5 if not n == 100 or n == 101 : print("n is not 100 or 101")

In [20]:

Chained conditionals

What if we want to test multiple conditions or execute distinct blocks of code depending on which of multiple possible conditions is true? We can simply add another condition, else if , to an if statement (previewed last week). Python uses the shorthand elif in its syntax for else if (it saves a couple keystrokes). Notice that conditional statements use boolean expressions: if boolean expression evaluates to True : block of code elif alternative boolean expression evaluates to True : block of code else : # (i.e. neither boolean expression evaluates to True) block of code Prompt the user for the mass of an RNA sample: In [22]: Next, prompt the user and the units of mass (e.g. ng or ug): In [23]: Deterime if the mass is less than 10 ng, assuming a mass less than 10 ng is insufficient for the experiment: In [24]: Enter mass of RNA: 11 enter ng or ug: ng proceed with experiment. n = 100 if n != 100 and n != 101 : print("n is not 100 or 101") mass = float(input("Enter mass of RNA: ")) units = input("enter ng or ug: ") if mass > 10 and units == 'ng': print("proceed with experiment.") elif mass > 0.01 and units == 'ug': print("proceed with experiment.") else : print("insufficient mass.")

if primary expression evaluates to True : if secondary expression evaluates to True : block of code else : block of code elif alternative primary expression evaluates to True : block of code else : block of code

Exercise 3b

Modify your code from exercise 3a to work with either DNA (A, C, T, G) or RNA (A, C, U, G) by prompting the user to indicate if the sequence is DNA or RNA and then use a nested conditional statement to test if it the 3-nt seqeunce entered is a start or stop codon.

In [1]:

try and except

An error detected during execution of code is called an exception. The error message is often ugly and difficult to understand unless you're familiar with Python: In [5]: try and except provide a convienent way to 'catch an exception' and provide a more informative custom error message. The syntax is as follows: enter a codon sequence: ATG dna or rna: dna Start!


TypeErrorTraceback (most recent call last) <ipython-input-5-99ebec2895cb> in () 1 n = 'ATG' ----> 2 print(n** 2 ) 3 print(n* 2 ) TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int ' codon = input("enter a codon sequence: ") nt = input("dna or rna: ") if nt == 'dna': if codon == 'ATG': print("Start!") elif codon == "TAG" or codon == "TAA" or codon == "TGA": print("Stop!") else : print("Neither!") elif nt == 'rna': if codon == 'AUG': print("Start!") elif codon == "UAG" or codon == "UAA" or codon == "UGA": print("Stop!") else : print("Neither!") else : print("I didn't understand your input.") n = 'ATG' print(n ****** 2 ) print(n ***** 2 )

In [8]:

Membership operators

The in and not in operators provide a very simple way of determining if something is in something else, such as whether a string is in a variable. Assign a DNA sequence to a variable: In [14]: Test if the sequence contains the string ATG: In [15]: Test if the sequence does not contain the string TGA: In [16]:

The len() function

The length function, len() , returns the length of an object. The object can be many different things, but when used on a string len() returns the number of characters contained in the string. Assign a sequence to a variable seq and identify its length: In [17]: Enter tail length: 6 AAAAAA Out[15]: True Out[16]: (^) True Out[17]: 6 try : num = int(input("Enter tail length: ")) print(f"{num*'A'}") except : print("Invalid number.") dna = 'ATGCCC' 'ATG' in dna 'TGA' not in dna seq = 'AAAGGA' len(seq)

Of course we can store the value returned by len() as a variable: In [20]:

Exercise 3d

Write a script that prompts a user for their email address and computes whether or not the email address is valid (assume its valid if it contains an @ ). In [22]:

Questions

Q. What are Boolean expressions? A. Q. What are the three logical operators in Python? A. Q. What are the membership operators in Python and how are they used? A.

Additional exercises

Except where noted otherwise, you can use whatever method you prefer to do the exercises (notebook, shell, script). ATTGGA is 6 nt long enter email: [email protected] Thank you! seq = 'ATTGGA' #seqlen = len(seq) print(f"{seq} is {len(seq)} nt long") email = input("enter email: ") if '@' in email: print("Thank you!") else : print("Invalid email adress")

! Present " Slides # Themes? Help