C if the User Does Not Enter a Valid Choice Then the Program Should Ask the Same Question Again
Making Choices
Overview
Teaching: thirty min
Exercises: 0 minQuestions
How can my programs do different things based on data values?
Objectives
Write conditional statements including
if,elif, andelsebranches.Correctly evaluate expressions containing
andandor.
In our last lesson, we discovered something suspicious was going on in our inflammation information by cartoon some plots. How can we use Python to automatically recognize the different features nosotros saw, and have a different activeness for each? In this lesson, nosotros'll learn how to write code that runs only when certain atmospheric condition are true.
Conditionals
We can ask Python to have different actions, depending on a condition, with an if statement:
num = 37 if num > 100 : print ( 'greater' ) else : print ( 'not greater' ) print ( 'done' ) The second line of this code uses the keyword if to tell Python that we want to make a choice. If the test that follows the if statement is truthful, the body of the if (i.due east., the set of lines indented underneath it) is executed, and "greater" is printed. If the test is false, the body of the else is executed instead, and "non greater" is printed. Only one or the other is ever executed before continuing on with plan execution to impress "done":
Conditional statements don't have to include an else. If there isn't ane, Python simply does null if the test is faux:
num = 53 impress ( 'before conditional...' ) if num > 100 : print ( num , 'is greater than 100' ) print ( '...after conditional' ) before conditional... ...after conditional We can also chain several tests together using elif, which is brusk for "else if". The following Python code uses elif to print the sign of a number.
num = - 3 if num > 0 : impress ( num , 'is positive' ) elif num == 0 : impress ( num , 'is nix' ) else : print ( num , 'is negative' ) Annotation that to test for equality we employ a double equals sign == rather than a single equals sign = which is used to assign values.
Comparing in Python
Along with the
>and==operators we take already used for comparison values in our conditionals, in that location are a few more options to know nigh:
>: greater than<: less than==: equal to!=: does not equal>=: greater than or equal to<=: less than or equal to
We can likewise combine tests using and and or. and is only truthful if both parts are truthful:
if ( 1 > 0 ) and ( - 1 >= 0 ): impress ( 'both parts are truthful' ) else : print ( 'at least 1 office is false' ) at to the lowest degree one part is false while or is truthful if at least one part is true:
if ( 1 < 0 ) or ( 1 >= 0 ): print ( 'at to the lowest degree one test is true' ) at least ane examination is true
TruthfulandFalse
TrueandFalseare special words in Python calledbooleans, which represent truth values. A statement such as1 < 0returns the valueFalse, while-1 < 0returns the valueTrue.
Checking our Information
Now that we've seen how conditionals piece of work, we can use them to check for the suspicious features we saw in our inflammation data. We are virtually to use functions provided by the numpy module over again. Therefore, if yous're working in a new Python session, make sure to load the module with:
From the start couple of plots, we saw that maximum daily inflammation exhibits a strange behavior and raises one unit a mean solar day. Wouldn't it exist a good idea to detect such behavior and report it equally suspicious? Let's do that! Withal, instead of checking every single day of the study, permit'southward just bank check if maximum inflammation in the beginning (twenty-four hours 0) and in the middle (mean solar day 20) of the study are equal to the corresponding day numbers.
max_inflammation_0 = numpy . max ( data , axis = 0 )[ 0 ] max_inflammation_20 = numpy . max ( data , centrality = 0 )[ 20 ] if max_inflammation_0 == 0 and max_inflammation_20 == 20 : impress ( 'Suspicious looking maxima!' ) We also saw a different problem in the tertiary dataset; the minima per day were all zero (looks like a healthy person snuck into our study). Nosotros can also bank check for this with an elif status:
elif numpy . sum ( numpy . min ( data , axis = 0 )) == 0 : print ( 'Minima add upwardly to zero!' ) And if neither of these conditions are true, we can utilise else to give the all-clear:
Let's examination that out:
data = numpy . loadtxt ( fname = 'inflammation-01.csv' , delimiter = ',' ) max_inflammation_0 = numpy . max ( data , axis = 0 )[ 0 ] max_inflammation_20 = numpy . max ( data , axis = 0 )[ twenty ] if max_inflammation_0 == 0 and max_inflammation_20 == 20 : print ( 'Suspicious looking maxima!' ) elif numpy . sum ( numpy . min ( data , axis = 0 )) == 0 : print ( 'Minima add upwards to zero!' ) else : impress ( 'Seems OK!' ) Suspicious looking maxima! data = numpy . loadtxt ( fname = 'inflammation-03.csv' , delimiter = ',' ) max_inflammation_0 = numpy . max ( information , axis = 0 )[ 0 ] max_inflammation_20 = numpy . max ( data , axis = 0 )[ 20 ] if max_inflammation_0 == 0 and max_inflammation_20 == xx : print ( 'Suspicious looking maxima!' ) elif numpy . sum ( numpy . min ( information , axis = 0 )) == 0 : print ( 'Minima add up to zero!' ) else : print ( 'Seems OK!' ) In this way, we have asked Python to do something unlike depending on the status of our data. Here nosotros printed letters in all cases, simply we could also imagine non using the else grab-all so that letters are merely printed when something is incorrect, freeing us from having to manually examine every plot for features we've seen before.
How Many Paths?
Consider this lawmaking:
if 4 > five : print ( 'A' ) elif 4 == five : print ( 'B' ) elif 4 < five : print ( 'C' )Which of the following would be printed if you were to run this code? Why did y'all pick this respond?
- A
- B
- C
- B and C
Solution
C gets printed considering the first 2 conditions,
iv > vandfour == 5, are not truthful, but4 < fiveis truthful.
What Is Truth?
TrueandFalsebooleans are not the only values in Python that are true and false. In fact, whatsoever value tin can be used in aniforelif. After reading and running the code below, explain what the rule is for which values are considered true and which are considered faux.if '' : print ( 'empty string is truthful' ) if 'word' : print ( 'discussion is true' ) if []: impress ( 'empty list is true' ) if [ 1 , 2 , 3 ]: print ( 'non-empty list is truthful' ) if 0 : print ( 'zero is truthful' ) if one : print ( 'one is truthful' )
That's Not Not What I Meant
Sometimes it is useful to check whether some condition is not true. The Boolean operator
noncan exercise this explicitly. After reading and running the code below, write someifstatements that usenonto examination the rule that you formulated in the previous challenge.if not '' : print ( 'empty string is non truthful' ) if non 'discussion' : impress ( 'word is not truthful' ) if not not True : impress ( 'not not True is true' )
Close Plenty
Write some atmospheric condition that print
Trueif the variableais within ten% of the variablebandFauxotherwise. Compare your implementation with your partner's: do yous get the same answer for all possible pairs of numbers?Hint
There is a congenital-in office
absthat returns the absolute value of a number:Solution 1
a = 5 b = v.i if abs ( a - b ) <= 0.i * abs ( b ): print ( 'Truthful' ) else : impress ( 'False' )Solution 2
print ( abs ( a - b ) <= 0.1 * abs ( b ))This works because the Booleans
TrueandFalsehave string representations which tin can be printed.
In-Identify Operators
Python (and most other languages in the C family unit) provides in-place operators that work like this:
x = ane # original value x += ane # add one to x, assigning result back to ten x *= 3 # multiply x by iii print ( x )Write some lawmaking that sums the positive and negative numbers in a list separately, using in-place operators. Practice y'all think the result is more or less readable than writing the same without in-place operators?
Solution
positive_sum = 0 negative_sum = 0 test_list = [ 3 , 4 , 6 , 1 , - 1 , - 5 , 0 , 7 , - 8 ] for num in test_list : if num > 0 : positive_sum += num elif num == 0 : pass else : negative_sum += num print ( positive_sum , negative_sum )Hither
passmeans "don't exercise annihilation". In this particular example, it's not actually needed, since ifnum == 0neither sum needs to alter, but it illustrates the use ofelifandpass.
Sorting a Listing Into Buckets
In our
informationfolder, big information sets are stored in files whose names get-go with "inflammation-" and small data sets – in files whose names beginning with "small-scale-". We also have some other files that nosotros do not care about at this signal. We'd like to break all these files into three lists chosenlarge_files,small_files, andother_files, respectively.Add code to the template below to do this. Note that the string method
startswithreturnsTrueif and only if the string it is chosen on starts with the string passed as an argument, that is:'Cord' . startswith ( 'Str' )But
'Cord' . startswith ( 'str' )Utilise the post-obit Python code as your starting point:
filenames = [ 'inflammation-01.csv' , 'myscript.py' , 'inflammation-02.csv' , 'small-01.csv' , 'small-02.csv' ] large_files = [] small_files = [] other_files = []Your solution should:
- loop over the names of the files
- figure out which grouping each filename belongs in
- suspend the filename to that listing
In the stop the three lists should be:
large_files = [ 'inflammation-01.csv' , 'inflammation-02.csv' ] small_files = [ 'small-scale-01.csv' , 'small-02.csv' ] other_files = [ 'myscript.py' ]Solution
for filename in filenames : if filename . startswith ( 'inflammation-' ): large_files . suspend ( filename ) elif filename . startswith ( 'small-scale-' ): small_files . suspend ( filename ) else : other_files . suspend ( filename ) print ( 'large_files:' , large_files ) impress ( 'small_files:' , small_files ) print ( 'other_files:' , other_files )
Counting Vowels
- Write a loop that counts the number of vowels in a character string.
- Test it on a few private words and full sentences.
- Once you are done, compare your solution to your neighbour'southward. Did yous brand the same decisions about how to handle the letter 'y' (which some people think is a vowel, and some do non)?
Solution
vowels = 'aeiouAEIOU' judgement = 'Mary had a little lamb.' count = 0 for char in judgement : if char in vowels : count += 1 print ( 'The number of vowels in this string is ' + str ( count ))
Key Points
Use
if conditionto start a provisional statement,elif conditionto provide additional tests, andelseto provide a default.The bodies of the branches of conditional statements must be indented.
Use
==to exam for equality.
X and Yis simply true if bothXandYare true.
X or Yis truthful if either10orY, or both, are true.Zero, the empty cord, and the empty list are considered false; all other numbers, strings, and lists are considered true.
TrueandFalserepresent truth values.
Source: https://swcarpentry.github.io/python-novice-inflammation/07-cond/index.html
0 Response to "C if the User Does Not Enter a Valid Choice Then the Program Should Ask the Same Question Again"
Post a Comment