Home > Essay examples > Decision-Making in Python Programming Language

Essay: Decision-Making in Python Programming Language

Essay details and download:

  • Subject area(s): Essay examples
  • Reading time: 7 minutes
  • Price: Free download
  • Published: 23 February 2023*
  • Last Modified: 22 July 2024
  • File format: Text
  • Words: 735 (approx)
  • Number of pages: 3 (approx)

Text preview of this essay:

This page of the essay has 735 words.



Activity 1.3.3 Branching and Output

Table of Contents

Introduction

Computers can sometimes appear intelligent because they can make a decision. A program that lets you text from a mobile device might decide to autocorrect your text. A program to provide driving directions might decide you've gone the wrong way. All programming languages have a way to branch, executing one set of instructions or another, depending on a condition.

How is this done in Python® programming language? And how can we get output from a program to know what the program has decided?

 

Procedure

1.    Form pairs as directed by your teacher. Meet or greet each other to practice professional skills. Launch Canopy and open an editor window. Set the working directory for the iPython session.

2.   In the previous activity, you learned that you can assign values to variables of different types. You learned that you can evaluate expressions and can define functions that return a value.

In []: a = 3

In []: a**2

Out[]: 9

Part I: Conditionals

3.   As you saw in Scratch™ programming language, computer programs can use if structures to make decisions. In an if structure, what gets executed depends on whether a Boolean expression, also known as a conditional, is true.

In []: a == 3 # Boolean expression, also called a conditional

Out[]: True

Note that the single = is used for assignment, while the double == is used for a Boolean expression. Other Boolean operators include >= (for ≥) and != (for ≠).

You can make compound conditionals by connecting Boolean expressions

with and, or, and not. In the following examples, remember that a is still 3.

In []: a+1 >= 2 and a**2 != 5 # compound conditional

Out[]: True

  The only two Boolean values are True and False.

In the following problems where the box is highlighted yellow, copy both your code from the iPython session and discuss the output.  Be sure to include a comment indicating the problem you are working on and highlight your answer.  An example is done for you.

Discuss, and explain the output:

In []: # 3 example 1:

In []: a*2 >= 4 and not a==4

In []: # 3 example 2:

In []: a+10 == 5 or a-1!=2

Out[]: False

In []: # 3 example 3:

In []: a < 1 or a > 2

Out[]: True

# 3 Example 1

a*2 >= 4 and not a==4

Out[12]: True

Since a=3, and 3×2 is greater or equal to 4 and a does not equal 4, this will be true

In [4]: a*2 >= 4 and not a==4

Out[4]: True

# 3 example 2:

a+10 == 5 or a-1 !=2

Out[16]: False

Since 3+10 does not equal 5, and 3-1 != 2 evaluates to False (3-1 does equal 2)

the output will be false

In [3]: a+10 == 5 or a-1 != 2

Out[3]: False

# 3 example 3

a < 1 or a > 2

Out[23]: True

Since 3 is not less than 1, but 3 is greater than 2, the output is true.  With or, only one Boolean operation needs to be true for the whole statement to evaluate to true.

In [5]: a < 1 or a > 2

Out[5]: True

Predict, try, discuss, and explain the output:

In []: # 3a. Prediction:

In []: a**2 >= 9 and not a>3

In []: # 3b. Prediction:

In []: a+2 == 5 or a-1 != 3

In []: # 3c. Prediction:

In []: a >7 or a-3 > 2

3a.

 In [7]: #3a Prediction: True

In [8]: a**2 >= 9 and not a>3

Out[8]: True

It is true because 3^2 is 9, which is equal to 9. Therefore, it is true.

3b.

In [9]: #3b prediction: True

In [10]: a+2 == 5 or a-1 != 3

Out[10]: True

True because 3 +2 does equal 5 and 3-1 does not equal 3

3c.

In [11]: #3c prediction: false

In [12]: a>7 or a-3>2

Out[12]: False

False because 3 is not greater than 7 and 0 is not greater than 2

4.   One situation where a programmer would use a compound conditional is when deciding whether a mouse click is within a certain region on the screen. For example, you might want your program to respond if a user clicks a rectangular shape, like a button or tab, as shown in the figure on the left.

Creating a program that uses mouse input is part of Lesson 1.5. For now, we’ll just assign x and y arbitrary values—let’s say (65,40), using the assignment operator =. These coordinates are shown by the red dot in the figure above on the right.

Unlike most languages, Python allows multiple assignment in a single line of code, as shown here:

In []: x, y = (65, 40)

In []: x

Out[]: 65

You might have noticed that the positive y-axis points down in the figure above. Computer graphics usually number the pixel rows from 0 at the top left and increase down and to the right across the screen.

The following expression is True when the red point (x, y) is in the blue area shown above.

In []: x>50 and x<80 and y>=30 and y<=45

Out[]: True

Write a compound conditional to test whether (x, y) is in the rectangle shown in the figures below. The conditional should be False since (x, y) is still bound to the values (65,40) from before.

Include a screen print from the console:

In [18]: x>40 and x<130 and y>100 and y<120

Out[18]: False

5.   Assign (90,115) to x and y to match the range of the figure above. You can use the up arrow on your keyboard to go back in the iPython session history and reuse the compound conditional you typed in Step 4. You can press enter to execute the command again or modify it before pressing enter.  Paste your output from the iPython session and explain your result.  Is it what you expected?

Include a screen print from the console:

In [20]: x>40 and x<130 and y>100 and y<120

Out[20]: True

Part II: if–else Structures

6. An if structure causes a program to execute a block of code only if a Boolean expression is True.

Optionally, an else block can be included. The else block of code will be executed only if the Boolean expression was False.

No matter whether the Boolean expression was True or False, the execution continues after the else block of the if–else structure. The function below illustrates the if–else structure.

For the next set of exercises, you will code in the Code Editor.  Remember to leave each function you create in the Code Editor as you will make a screen print of all your functions.

1

2

3

4

5

6

7

8

9

10

def age_limit_output(age):

'''Step 6a if-else example'''

AGE_LIMIT = 13 # convention: use CAPS for constants

if age < AGE_LIMIT:

print str(age) + ' is below the age limit.'

else:

print str(age) + ' is old enough.'

print 'Minimum age is ' + str(AGE_LIMIT)

    Looking at the code, what is the variable role for:

age: Most recent holder

AGE_LIMIT: Fixed value

The colons at the end of lines 3, 5, and 7 are required by def, if, and else key words. The indentation tells the Python interpreter which block of code belongs to that def, if, or else block. Just as Scratch grouped the code in if/else blocks, Python uses indentation to group code. Always use four spaces for each level of indentation. All such stylistic conventions can be found at http://www.python.org/dev/peps/pep-0008/#indentation

When you try the code, notice that the output doesn’t come after an Out[]:. This is because print() sends output to the system out, which by default is set to be the screen. The print() command returns a null value, however. The return value of a function or expression is what iPython displays (also on the screen) after the Out[].

a. Make sure the code above (def age_limit function) is in to the code editor. Execute the code, run the play button, and then try the following input. Discuss the output.  Is it what you expect?

b. In []: age_limit_output(10)

c.  In []: age_limit_output(16)

Include screen prints from the console:

In [3]: age_limit_output(10)

10 is below the age limit.

Minimum age is 13

In [4]: age_limit_output(16)

16 is old enough.

Minimum age is 13

d.   Define a new function report_grade(percent) that reports mastery if the argument percent is 80 or more. You can write the function as an additional function in the same file of code as before. The beginning of the new code is shown here, and the required output is shown below. Pair program, strategizing first.

12

13

def report_grade(percent):

'''Step 6b if-else'''

In []: report_grade(79)

A grade of 79 does not indicate mastery.

Seek extra practice or help.

In []: report_grade(85)

A grade of 85 percent indicates mastery.

Keep up the good work!

Include a screen print of your function here.

Part III. The in operator and an introduction to collections

The in operator is another Boolean operator, like ==. Since it is Boolean, it returns True or False. You can use it to see if an element is in an iterable. Iterables are built out of zero or more elements and include strings like ‘Hello world’, lists talked about below and other variables we will learn about later.

7. Examine the following examples using the in operator:

In []:'t' in 'string' # includes lowercase t character

Out[]: True

In []:'T' in 'string' # case matters

Out[]: False

In []: 3 in [1,2,3] # this list contains the int 3

Out[]: True

In []:'3' in [1,2,3] # '3' is a string, different than 3

Out[]: False

8.  The following function  vowel(letter) returns True if the letter is 'a',  'e',  'i',  'o',  'u', or any of their uppercase counterparts and returns False otherwise.

1

2

3

4

5

6

7

def vowel(letter):

vowels = 'aeiouAEIOU'

if letter in vowels:

     return True

else:

     return False

# should check len(letter)==1

In your Python file for this activity, define a function letter_in_word(guess, word) that returns True if guess is a letter in word and returns False otherwise.   You will pass in two strings when you call the function as shown below.

In []: letter_in_word('t', 'secret hangman phrase')

Out[]: True

Include a screen print of your function here.

 (Done at home)

Another iterable in Python is a list.  Remember in Scratch we made lists, which we called aggregators to hold items we put in the list, like high scores.

   

To create a list in Python, we define the elements in a list with brackets.  We can put different type of elements in a list (integer, floats, strings, Boolean) and then work with those elements.

To create a list, just assign the elements to a variable:

a_list = [‘apples’,5, 3.35, ‘peaches’, 7]

We will work with list much more in the next activity.

9.   In MasterMind, one player has a secret sequence of colored pegs. Another player tries to guess the sequence.

Define a function hint(color, secret) that takes two parameters: a string (representing a color) and a list of strings (representing a sequence of colors). The function should print a hint telling whether the color is in string.

In []:

In []: hint('red', ['red','red','yellow','yellow','black'])

The color red IS in the secret sequence of colors.

In []: hint('green', ['red','red','yellow','yellow','black'])

The color green IS NOT in the secret sequence of colors.

Include a screen print of your function here.

Conclusion

1.  Describe the relationship between blocks of code indented after the colon in if  and else blocks.

 It means that if the if statement is true, whatever is coded in that section should be executed. If it is not true, then whatever was coded after the “else” statement should be executed.

2. Steve and Latisha wrote this code:

21

22

23

24

25

 print('Code complete.')

 if check == 2:

     print('All systems are ready.')

else:

     print('Not all systems are ready')

Ira, Jayla, and Kendra are all saying it would be better to move lines 22 and 24 to a single line executing print ('Code complete.') just before line 21. These three students have different reasons for their opinions. Their reasons are below. Do you think each of them is right, wrong, or somewhere in between? Explain.

Ira: “It would be better to have a single print statement because that code is going to happen no matter what. The program will run slower by having it there twice.”

 Incorrect, the program will not run slower because of the code occurring twice.

Jayla: “It would be better to have a single print statement because that code is going to happen no matter what. Later, if you want to change your program (message ‘Code complete’), you’re going to have to remember to change it in two places the way the code is now.”

 Correct, however it is very important that it is remembered to change the code in two separate spots if it needed to change.

Kendra: “It would be better to have a single print statement because it is going to happen no matter what. That program would take up less memory if you just wrote it once.”

  Correct, it would take up less memory

Modify the code above so that it is as efficient as possible.  Make use of the boolean operators mentioned in Part I.

 if check == 2:

     print('Code complete.')

else:

     print('Code complete.')

     print('Not all systems are ready')

About this essay:

If you use part of this page in your own work, you need to provide a citation, as follows:

Essay Sauce, Decision-Making in Python Programming Language. Available from:<https://www.essaysauce.com/essay-examples/2017-10-17-1508214803/> [Accessed 15-04-26].

These Essay examples have been submitted to us by students in order to help you with your studies.

* This essay may have been previously published on EssaySauce.com and/or Essay.uk.com at an earlier date than indicated.

NB: Our essay examples category includes User Generated Content which may not have yet been reviewed. If you find content which you believe we need to review in this section, please do email us: essaysauce77 AT gmail.com.