You are on page 1of 40

1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

CS 1101 Programming Fundamentals - AY2022-T2


Dashboard / My courses /
CS 1101 - AY2022-T2 / 2 December - 8 December /
Discussion Forum Unit 4 /
Discussion Unit 4

 Search forums

Discussion Forum Unit 4


Discussion Unit 4

Settings

Display replies in nested form

The cut-off date for posting to this forum is reached so you can no longer post to it.

Discussion Unit 4
by Leonidas Papoulakis (Instructor) - Wednesday, 10 November 2021, 7:09 AM

Section 6.9 of your textbook ("Debugging") lists three possibilities to consider if a function is not working.

Describe each possibility in your own words.

Define "precondition" and "postcondition" as part of your description.

Create your own example of each possibility in Python code. List the code for each example, along with sample output from
trying to run it.

58 words

Permalink

Re: Discussion Unit 4


by Samrawi Berhe - Saturday, 4 December 2021, 4:58 AM

                                       Discussion Forum Unit


4

                                                       Questions
Section
6.9 of your textbook ("Debugging") lists three possibilities to
consider if a function is not working.


Describe each possibility in your own words.


Define "precondition" and "postcondition" as part of your description.


Create your own example of each possibility in Python code. List the code for
each example, along with sample output from
trying to run it

                                                 Answer

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 1/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

        First
Part(Description)

First,
let’s describe what is debugging? It is
the process of tracing programming error that occurs during different execution
time (Downey, 2015, p. 6 ). Those errors occur due to a logic error, a type error,
or an input error. So, we must handle them
before they occur. Therefore, to do
this we define a function to encapsulate statements that have similar work into
one block.
Then we call the function to perform what we want to do. There are
requirements called arguments and return types together
with return values to
accomplish the function for what we need it to do, like parameter names and
values. Here, for example,
we want to write a program that calculates age taking
the date of birth and today’s calendar from the user. We know that age
must be
a positive number. So, the user should supply a positive number. These requirements
we set are called Precondition
and must be true before the function is
running. The other thing is,  we want the
program to display the age of the given
person as an output of the program in the
way that we wanted it to do. This is called Postcondition (Downey, 2015,
p. 36 ).
The third one is the way we use it or return value. If either of them fails
to fulfill, there is wrong

1. with
the arguments, the function is set to get which is => There is a violation of precondition.
2.  with
the function=> There is a violation of postcondition.
3. with
the return value or the way, we use it.

    Second
Part(Show by example)

1. Let’s
see, a problem with the argument's the function is set to get (There is a violation of precondition.

The script looks like as below

dob = int(input("Please enter your date of birth\n"))  # user prompt to enter date of birth

today_cal
= int(input("Please enter
today's date\n"))  # user prompt to enter today’s date

age
= today_cal - dob  # Age calculation
Expression

def
calc_age(db, cal, ag):  # Function definition with 3 parameter

   print("Your date of birth is=", dob, "Today's date is=", today_cal, "Your age is=",

         age)  # date of birth, today date


and age output to the console

calc_age(dob, today_cal, age)  # Function call and Passing parameter

Output

Please
enter your date of birth

1989

Please
enter today's date

-2021

Your
date of birth is= 1989 Today's date is= -2021 Your age is= -4010

Process
finished with exit code 0

From
the above output, we can see everything is ok but age shouldn’t be negative and
must not accept a negative number.
There are two ways to fix this one is defining
using the keyword “assert” for precondition to be true. So, let’s do this.

The
script looks like as below

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 2/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4
dob = int(input("Please enter your date of birth\n"))  # user prompt to enter date of birth

today_cal = int(input("Please enter today's date\n"))  # user prompt to enter today’s date

age = today_cal - dob  # Age calculation Expression

def calc_age(db, cal, ag):  # Function definition with 3 parameter

   assert db > 0 and today_cal > 0

   print("Your date of birth is=", dob, "Today's date is=", today_cal, "Your age is=",

         age)  # date of birth, today date and age output to the console

calc_age(dob, today_cal, age)  # Function call and Passing parameter

And the
output of the above looks like as follows.

Please
enter your date of birth

-1989

Please
enter today's date

-2021

Traceback
(most recent call last):

File
"C:\Users\PC\PycharmProjects\pythonProject\age_calc.py", line 12, in
<module>

   calc_age(dob, today_cal, age)  # Function call and Passing parameter

File "C:\Users\PC\PycharmProjects\pythonProject\age_calc.py",
line 7, in calc_age

   assert db > 0 and today_cal > 0

AssertionError

Process
finished with exit code 1

From
the above output, we can see that the assertion error is fired. So, to fix this we
must force the user to enter a positive
integer only. So, we can use isinstance(int, int) exception handler.

The snippet code looks as below.

except isinstance(int, int) as ins:

   print(f"You are supposed to enter number only. You entered {dob | today_cal}")

And the output looks as follows.

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 3/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Please enter your date


of birth

-2000

Please enter today's


date

-2010

You entered, -2000,


-2010, which is not positive number., try again

Process finished with


exit code 0

2. 
Let’s
see, a problem with the function(There is a violation of postcondition.)

The
script looks like as below

dob = int(input("Please enter your date of birth\n"))

today_cal = int(input("Please enter today's date\n"))

age = today_cal - dob

def calc_age(db, cal, ag):

   print("dob is\n", dob)

   print("today\n", today_cal)

   print("your Date of birth=", dob, "Todays calendar is=", today_cal, "Your age is=", age)

   #calc_age("your age is", age)

calc_age(age)

Output

Please
enter your date of birth

1989

Please
enter today's date

2021

Traceback
(most recent call last):

File
"C:\Users\PC\PycharmProjects\pythonProject\age_calc.py", line 13, in
<module>

   calc_age(age)

TypeError:
calc_age() missing 2 required positional arguments: 'cal' and 'ag'

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 4/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Process
finished with exit code 1

From
the above output, we can see that there is a type error in which there is a missing
number of parameters that should be
passed to the function call.

So let's
fix that we pass the required number of parameters to the function
call and see what will happen.

Script
after fixing looks like as below

dob = int(input("Please enter your date of birth\n")) # user prompt to enter date of birth

today_cal = int(input("Please enter today's date\n")) # user prompt to enter today’s date

age = today_cal – dob # Age calculation Expression

def calc_age(db, cal, ag): # Function definition with 3 parameter

  

   print("Your date of birth is=", dob, "Today’s date is=", today_cal, "Your age is=", age) # date of birth, today
date and age output to the console

  

calc_age(dob, today_cal, age) # Function call and Passing parameter

The
output after fixing the problem is as below

Please
enter your date of birth

1989

Please
enter today's date

2021

Your date
of birth is= 1989 Today's date is= 2021 Your age is= 32

Process
finished with exit code 0

Again,
let’s test it for negative number input and see the output

Please
enter your date of birth

1989

Please
enter today's date

-2021

Your
date of birth is= 1989 Today's date is= -2021 Your age is= -4010

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 5/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Process
finished with exit code 0

We can
conclude from the above output that there is no function which means no postcondition violation.

3.  
Let’s
see, a problem with the return value or the way we use it.

The
script is as it is. We just check if we didn’t enter integer instead we
entered string. So, let’s see the output.

Please
enter your date of birth

sep1998

Traceback
(most recent call last):

File
"C:\Users\PC\PycharmProjects\pythonProject\age_calc.py", line 1, in
<module>

   dob = int(input("Please enter your


date of birth\n"))  # user prompt to
enter date of birth

ValueError:
invalid literal for int() with base 10: 'sep1998'

Process
finished with exit code 1

From
the above error, we can see that there is a value error. So, we should enforce the
user to use not to use other than
integers. thus, we can use ValueError exception handler as learned from Python ValueError Exception
Handling Examples
(2020).

The snippet code looks as below.

except ValueError as ve:

   print('You are supposed to enter number only')

and
the output is

Please
enter your date of birth

2000

Please
enter today's date

sept2021

You are
supposed to enter number only, try again

Process
finished with exit code 0

Finally,
after fixing all errors the script looks like below.

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 6/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4
def calc_age(db, cal, ag):  # Function definition with 3 parameter

   ag = cal - db  # Age calculation Expression

   # assert db > 0 and cal > 0 and ag is not int

   print("Your age is=", ag)  # date of birth, today date and age output to the console

   return ag

try:

   dob = int(input("Please enter your date of birth\n"))  # user prompt to enter date of birth

   today_cal = int(input("Please enter today's date\n"))  # user prompt to enter today’s date

   age = today_cal - dob  # Age calculation Expression

   try:

       if dob >= 0 and today_cal >= 0:

           print(f"your input are, today's date={today_cal}, your date of birth={dob}")

           calc_age(dob, today_cal, age)  # Function call and Passing parameter

       else:

           print(f"You entered, {dob}, {today_cal}, which is not positive number., try again")

   except isinstance(int, int) as ins:

       print(f"You are supposed to enter number only. You entered {dob | today_cal}")

except ValueError as ve:

   print(f'You are supposed to enter number only, try again')

And the
output looks as follows.

Please
enter your date of birth

1989

Please
enter today's date

2021 
your
input are, today's date=2021, your date of birth=1989

Your  age is= 32

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 7/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Process
finished with exit code 0

                                                  Reference

Downey, A. (2015, pp. 41-42 ). Think


Python: How to Think Like a Computer Scientist (2nd ed., Version 2.4.0). Needham: Green
Tea Press.
Python
ValueError Exception Handling Examples. (2020, December 10). Retrieved from
https://www.journaldev.com/33500/python-valueerror-exception-handling-examples

1540 words
Tags:
Discussion Forum Unit 4

Permalink Show parent

Re: Discussion Unit 4


by Yahya Al Hussain - Saturday, 4 December 2021, 12:01 PM

Samrawi,

very comprehensive detailed answer, you dealt with all the questions and went the extra mile, showing how to fix the
errors was a nice touch too.

keep it up!
30 words

Permalink Show parent

Re: Discussion Unit 4


by Samrawi Berhe - Monday, 6 December 2021, 4:34 AM

Thank you, Yahya, for your comments.


6 words

Permalink Show parent

Re: Discussion Unit 4


by Ahmet Yilmazlar - Monday, 6 December 2021, 8:43 AM

very good detailed answer


4 words

Permalink Show parent


Re: Discussion Unit 4
by Juan Duran Solorzano - Tuesday, 7 December 2021, 1:23 AM

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 8/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Dear Samrawi,

Very detailed, great explanation and it helped me to fully understand some concepts where I was struggling.
19 words

Permalink Show parent

Re: Discussion Unit 4


by Simon Njoroge - Tuesday, 7 December 2021, 10:02 AM

You have put a great effort in participating in the discussion. The codes given are quite accurate and the explanation for
the terms as well as the codes are quite easy to follow. This is good work. Keep up.
39 words

Permalink Show parent

Re: Discussion Unit 4


by Janelle Bianca Cadawas Marcos - Tuesday, 7 December 2021, 2:28 PM

Oh wow, this is very detailed and easy to read. It's easy to tell how much work you put into this. You went above and
beyond. Good job!
28 words

Permalink Show parent

Re: Discussion Unit 4


by Wilmer Portillo - Tuesday, 7 December 2021, 5:41 PM

I should applaud you for such a detailed and on point discussion. I must say that going over your discussion made me
reaffirm a couple things I was not so sure about. Keep up the great work.
37 words

Permalink Show parent

Re: Discussion Unit 4


by Fouad Tarabay - Wednesday, 8 December 2021, 9:31 AM

Hello Samrawi,

You mentioned everything in detail and I like the way you solve the errors.

Great gob!
18 words

Permalink Show parent

Re: Discussion Unit 4


by Newton Sudi - Wednesday, 8 December 2021, 5:03 PM

This is incredible. I love the use of meaningful examples. Keep going.


12 words

Permalink Show parent


Re: Discussion Unit 4


by Ismail Ahmed - Wednesday, 8 December 2021, 5:26 PM

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 9/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Hi Samrawi

You did great and detailed effort. I loved the examples. Keep up the good work.
17 words

Permalink Show parent

Re: Discussion Unit 4


by Peter Odetola - Wednesday, 8 December 2021, 11:24 PM

Thanks for the thorough step-by-step approach Samrawi. The examples you gave are really an eye-opener to me in the
approaches you use for them. Thank you
26 words

Permalink Show parent

Re: Discussion Unit 4


by Yahya Al Hussain - Saturday, 4 December 2021, 11:38 AM

When writing code that accepts input, most of the time the function is expecting a specific type of input, an integer , a string,
or a float for example, if the function is expecting an integer and you input a float, then the code will return an error or return
nothing, that is called a precondition, the error was caused because of a preset or condition that was baked into the code
wasn't met, or inputted incorrectly by the end user or by a another function, just like standing under the shower expecting
warm water, but getting bombarded with a stream of cold icy water, or you could be expecting either, then turning on the
shower and getting chunks of cheese, it's not even in the same category (type), let's see an example of that.
         

Example 1.1(W/a debugging measure)   Example 1.2 ( Without)

____________________________________________________________________________

def water(w:int):                 | def water(w:int): #w:int is a pre-condition for expecting an integer

  happy = w+9               |   happy = w+9

if 100>happy>50:   | if 100>happy>50 #happy is a post-condition that takes place only after the
precondition has been met

print('water is warm')    | print('water is warm')

return happy  | return happy

elif 1<happy<50:              | elif 1<happy<50:

print('water is cold') | print('water is cold')

return happy | return happy

else: | #after executing the function, if the post-condition isn't met we


should have a safe guard or else the function returns nothing

print('wait... what!')

return w |

|

>>>shower(999999) | >>>shower(41)

>>>wait... what!  | >>>

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 10/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

>>>999999
           

in Example 1.1 we know what went wrong, because we put in a conditional(guard) that helps us identify the cause of the error,

it might not look necessary in this example, but when the code gets complex and long, not having it like in Example 1.2 will
give you a hard time trying to debug what went wrong.

however in a postcondition like in both examples after the function has been called, a post-condition if 50>happy>1 starts if
we place an integer that isn't a part of

the parameters, the function will do nothing (in this case).

If for example, we misused the value of the variable "happy", we end up with an error like in Example 2.1 or a dead code.
Example 2.1

def water(w:int):

   happy = w+9

   if 100>happy>50:

       print('water is warm')

       return happy + ' ' + "to be here"                 #the return value is being misused here

   elif 1<happy<50:

       print('water is cold')

       return "not"+' '+ happy + ' ' + "to be here"

   else:

       print('iddk')

       return w

>>>water(9)

>>>water is cold

Traceback (most recent call last):                      #we get an error in return

File "<pyshell#246>", line 1, in <module>

   water(9)

File "<pyshell#245>", line 8, in water

   return "not"+' '+ happy + ' ' + "to be here"

TypeError: can only concatenate str (not "int") to str

469 words

Permalink Show parent

Re: Discussion Unit 4



by Samrawi Berhe - Monday, 6 December 2021, 4:46 AM

Dear Yahya, your works are good. You have explained what are precondition and postcondition debugging very nice. But I
was expecting the output of the precondition and what kind of error was raised. Basically, in debugging there are 3 things
https://my.uopeople.edu/mod/forum/discuss.php?d=640877 11/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

that go wrong, and try to understand them. Those are as follows.

1. with the arguments, the function is set to get which is => There is a violation of precondition.

2. with the function=> There is a violation of postcondition.

3. with the return value or the way, we use it.


92 words

Permalink Show parent

Re: Discussion Unit 4


by Ahmet Yilmazlar - Monday, 6 December 2021, 8:44 AM

great work
2 words

Permalink Show parent

Re: Discussion Unit 4


by Wilmer Portillo - Tuesday, 7 December 2021, 5:43 PM

Hi Yahya,

You discussion was easy to understand and the example/scenarios you used were on point! Great work sir.
19 words

Permalink Show parent

Re: Discussion Unit 4


by Yahya Al Hussain - Tuesday, 7 December 2021, 10:22 PM

Thank you sir

3 words

Permalink Show parent

Re: Discussion Unit 4


by Stephen Chuks - Wednesday, 8 December 2021, 2:11 PM

Good points from you. Your explanations are very clear. And your codes are straight forward

15 words

Permalink Show parent

Re: Discussion Unit 4


by Newton Sudi - Wednesday, 8 December 2021, 5:22 PM

Nice examples. Also, I think you are understanding this programming concept. Keep it up.
14 words

Permalink Show parent


Re: Discussion Unit 4


by Ismail Ahmed - Wednesday, 8 December 2021, 5:27 PM

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 12/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Hi Yahya

The examples are clear. Well organized too. Keep up the good work.
14 words

Permalink Show parent

Re: Discussion Unit 4


by Ahmet Yilmazlar - Sunday, 5 December 2021, 11:36 AM

Debugging is defined as the processing of tracking down programming errors or bugs according to downey. Learning to
debug can really be hard and unbearable but it is an important skill in programming and beyond.

Functions are a vital object in writing programs not only in python but in other programminf languages as they help in
organizing and simplifying our progams. Three possible causes of function failure

1.

import math

def area_circle(r):

#assert r > 0, ' radius must be greater than 0 '

print (' if r =' , r)

a = round(math.pi*r**2)

return a

print ( ' then, area =' , area_circle(float(input(' Enter a number : = ' )))

outputs:

Enter a number: = -3

if r = -3.0

then, area = 28

[ Program finished ]

2.

import math

def area_circle(r):

#assert r > 0, ' radius must be greater than 0 '

print (' if r =' , r)

a = round(math.pi*r**2)

return a

print ( ' then, area =' , area_circle(float(input(' Enter a number : = ' )))

output:

Traceback (most recent call last): File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py ", line 31, in
start(fakepyfile, mainpyfile) File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py ", line 30, in start
exec(open(mainpyfile).read(), File "", line 6 _main_._dict_)

return a

indentionerror: unexpected indent

[ Program finished ]

it is a result of an inconsistency in indentation.


3.

this step helps to know what function was going wrong.

import math

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 13/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

def area_circle(r):

#assert r > 0, ' radius must be greater than 0 '

print (' if r =' , r)

a = round(math.pi*r**2)

return a

print ( ' then, area =' , area_circle(float(input(' Enter a number : = ' )))

output:

enter a number: 3

if r = 3.0

then, area = 62

[ Program finished ]

the program above executed successfully but the return value doesnt seem like what it would be.

references

Downey, A. (2015). think like python, how to think like a computer scentist
320 words

Permalink Show parent

Re: Discussion Unit 4


by Samrawi Berhe - Monday, 6 December 2021, 4:52 AM

Dear Ahmet, your works are good. You have explained is debugging nicely. But I was expecting an explanation of what
precondition and postcondition are, what kind of error was raised when testing. Basically, in debugging there are 3 things
that go wrong, and try to understand them. Those are as follows.

1. with the arguments, the function is set to get which is => There is a violation of precondition.

2. with the function=> There is a violation of postcondition.

3. with the return value or the way, we use it.


91 words

Permalink Show parent

Re: Discussion Unit 4


by Janelle Bianca Cadawas Marcos - Tuesday, 7 December 2021, 2:32 PM

Hey Ahmet,

I don't think you answered what was asked completely. I don't see any of the possibilities described in your own words,
just the codes with not much explanation. Also forgot to mention precondition and postcondition. Make sure to read the
entire prompt again next time and double check that you did it completely. The APA citation can be worked on a bit more
too, as well as the indentation of your code, it's hard to read without indents on the text.
83 words

Permalink Show parent

Re: Discussion Unit 4


by Newton Sudi - Wednesday, 8 December 2021, 5:24 PM

This is great. Well explained. I like the idea of coming up with mathematical programs.
15 words

Permalink Show parent

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 14/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4
Re: Discussion Unit 4
by Simon Njoroge - Sunday, 5 December 2021, 12:36 PM

Discussion Assignment

Section 6.9
(“Debugging”) list three possibilities to consider if a function is not working

Describe each
possibility in your own words.

1ST
Possibility.

There is a problem with


the argument in the function posing a possible problem even before the function
is run. This happens
when there is wrong with the argument in the function it
is therefore a precondition violation. The solution to this problem is
to use
print statement prompting to check parameters of the argument. This will ensure
the correct type of data is used by
pre-checking the argument.

2nd Possibility

An error would occur as


a result of wrong entry of the function itself causing a violation. The second
possibility need to be
crosschecked if the parameters of the argument are
proven to have no problem. The best way to check out this is by
substituting
the missing values in the function in order to call the function and verify if
there is any possible problem.

3rd possibility

The third possible


error could occur as a result of using return values erroneously. The solution
to this is by crosschecking the
function value to verify its correctness in the
manner it is being utilized.

Define "precondition" and "postcondition" as


part of your description.

A precondition refers to the checks on the function that are set


to examine the argument in order to ensure that the
paramenters of the argument
are met before execution of the function. They are set in the process of
creating a function, it is
set ahead before running a function.  Preconditions normally enable the user to
determine the correctness of the data entered
in the argument.

Postcondition is a condition that is set in order to examine the


correctness of the entered elements in a function in order to
determine that
the return value is accurate for execution. It may include the expected return
results, state and condition of the
expected output.  

Example in each possibility

1st Possibility - Precondition is violated –


Something is wrong with the arguments

In this example I have created a function that calculates the


percentage score of a subject by combining two elements –
composition and
gramma.

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 15/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Precondition test is used in the example to first verify if c is


less than or equal 40 and g is less or equal to 50 . The entry is
verified and
a print out of a report showing the entry looks fine is given out. This is an
example of precondition check for any
errors during debugging.

2nd Possibility There is


something wrong with the function; a post condition is violated.

In the same example I have used the


parameter of print (type(percentage_score) this is used to verify the type of
data for
percentage after calculations just before a report of the same is
displayed. This is a post-condition in order to ascertain the
accuracy of the
function execution before printing the output.

3rd Possibility -  There is something wrong with the return


value or the way it is being used.

In order to verify the correctness and


accuracy of the return value I have added a new report to print out that can be
used to
detect any error upon execution. Refer to the example below:

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 16/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Print(percentage_score,”is<100”)  print out report can be used to ascertain the


correctness of the return value upon execution
of the function.

Reference

Downey, A. (2015). Think Python:


How to Think Like a Computer Scientist (2nd ed.). Green
Tea

           Press

576 words

Permalink Show parent

Re: Discussion Unit 4


by Yahya Al Hussain - Sunday, 5 December 2021, 3:38 PM

nicely done Simon,

i appreciate the simplicity of your code and the comments, easy to read and understand!

keep up the good work!


23 words

Permalink Show parent

Re: Discussion Unit 4


by Samrawi Berhe - Monday, 6 December 2021, 4:57 AM

Dear Simon, you have done a fantastic explanation and the way you present it. Your work is very neat and clear. Your
examples are very clear and easily understandable. Keep it up!
32 words

Permalink Show parent

Re: Discussion Unit 4


by Ahmet Yilmazlar - Monday, 6 December 2021, 8:44 AM

i appreciate the simplicity of your code and the comments, easy to read and understand!
15 words

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 17/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Permalink Show parent

Re: Discussion Unit 4


by Janelle Bianca Cadawas Marcos - Tuesday, 7 December 2021, 2:34 PM

Hi Simon,

This was really easy to understand and read. Good work and keep it up!
16 words

Permalink Show parent

Re: Discussion Unit 4


by Wilmer Portillo - Tuesday, 7 December 2021, 5:47 PM

Hi Simon, your discussion and examples are relevant to the topic and you kept it simple. The structure of your work
definitely helps in the proper reading and understanding of it. Keep up the good and on point work.
39 words

Permalink Show parent

Re: Discussion Unit 4


by Fouad Tarabay - Wednesday, 8 December 2021, 9:37 AM

Hello Simon,

Your explanation was great and clear to understand as well as your examples.

Keep it up!
18 words

Permalink Show parent

Re: Discussion Unit 4


by Ismail Ahmed - Wednesday, 8 December 2021, 5:28 PM

Hi Simon

Loved your code. Well organized too. Keep up the good work.
13 words

Permalink Show parent

Re: Discussion Unit 4


by Peter Odetola - Wednesday, 8 December 2021, 11:29 PM

Hi Simon,

I really appreciate your coding workflow. The comments were explanatory and the entire coding is easy to read and
understand. Thank you
24 words

Permalink Show parent


Re: Discussion Unit 4
by Fouad Tarabay - Monday, 6 December 2021, 10:52 AM

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 18/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

A precondition is a condition that requires to be true before a function executes, in our case, in the function the arguments
given must be valid to make the code execute properly. To prevent such errors we can add a print statement at the beginning
of the function to print out the values of the parameters so we can make sure they are correct.

A postcondition is a condition that we expect after the function executes. After checking for the validity of the parameters, we
can add a print function before each statement that produces a return value.

Finally, after checking the postcondition and the precondition we can have a look at the function call to approve if it’s being
correctly used.

Precondition Example:

def s(a, b):

s = a+b

return s

print(s("fouad",21))

output:

TypeError: can only concatenate str (not "int") to str

Postcondition Example:

def s(a, b):

s = a-b

return s

print(s(12,21))

output:

-9

Return Example:

def s(a, b):

s = a+b

return s

n1 = int(input("Enter the first number to add: "))

n2 = int(input("Enter the second number to add: "))

print(s(n1,n2))

input:

Output:

Reference:

Bors M.L (2018). Preconditions and Postconditions. https://medium.com/@mlbors/preconditions-and-postconditions-


5913fc0fcdaf
198 words

Permalink Show parent

Re: Discussion Unit 4


by Yahya Al Hussain - Monday, 6 December 2021, 12:59 PM
https://my.uopeople.edu/mod/forum/discuss.php?d=640877 19/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Mr. Fouad,

great Description,thank you for including a reference, simple and neat code, but some comments could have made it
easier to read.
23 words

Permalink Show parent

Re: Discussion Unit 4


by Juan Duran Solorzano - Tuesday, 7 December 2021, 1:09 AM

Good explanation, it would have been easier to follow if you add some comments and format the text separating code,
instructions, and outputs.

Just wanted to add while debugging we could also use built-in such as type(), and isinstance() functions to make sure we
are working with the right data type.
51 words

Permalink Show parent

Re: Discussion Unit 4


by Siphumelelise Ntshwenyese - Tuesday, 7 December 2021, 6:16 AM

Fouad,

Great explanation, you demonstrated understanding of the concepts, however, more code comments would improve your
discussions next time, well done
21 words

Permalink Show parent

Re: Discussion Unit 4


by Simon Njoroge - Tuesday, 7 December 2021, 9:41 AM

Your contribution to this assignment or discussion is extremely valuable. I am impressed and have gotten more
understanding in the topic which is extremely important in this exercise. The codes may look simple but very well thought
out.
38 words

Permalink Show parent

Re: Discussion Unit 4


by Wilmer Portillo - Monday, 6 December 2021, 9:41 PM

Discussion Assignment Unit 4:

Section 6.9 of your textbook ("Debugging") lists three possibilities to consider if a function is not working.

Describe each possibility in your own words.

   The 3 possibilities include: 

1. The argument the function is getting has an error whereby a precondition is violated. In other words, something about
the argument is not true before a block of code run. An example for this is dividing a number by ‘0’ in the interpreter,

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 20/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

that is impossible. The book stated that there are 2 ways to prevent this: one is that a print statement can be added to
the beginning of the function and display the values of the parameters, secondly, a code that checks preconditions can
be written.
2. The function has an error whereby a postcondition is violated. In this case, something that the function guarantees to do
when it executes, is not true. To prevent this, we can add a print statement before each return statement and display the
return value.
3. There is an issue with the return value. To prevent this we need to look keenly at the function call to make sure the return
value is being used correctly.

Define "precondition" and "postcondition" as part of your description.

Precondition: simply mean that something (argument for example) must be true/correct at the start of a  function for it to
run/work properly. It expresses a function's expectation on its arguments and/or the state of objects that may be used by the
function.
Postcondition: simply mean that something that the function guarantees must be true when it finishes. It  expresses the
conditions that a function should ensure for the return value and/or the state of objects that may be used by the function.

Create your own example of each possibility in Python code. List the code for each example, along with sample output from
trying to run it.

Precondition Violation Example:

Output:

In this case, this error can be considered as a precondition violation as we are telling the interpreter to add the variable ‘a’ to
an integer which is mathematically incorrect.
Postcondition Violation Example:
Input:

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 21/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Output:

In this case, this error can be considered as a postcondition violation as we are telling the interpreter that the result should be
the addition of a string with an integer which is incorrect as the data type should be the same for integer addition in the
function.

References:

Downey, A. (2015). Think Python: How to think like a computer scientist. Green Tea Press. This book is licensed under Creative
Commons Attribution-NonCommercial 3.0 Unported (CC BY-NC 3.0).

433 words

Permalink Show parent

Re: Discussion Unit 4


by Juan Duran Solorzano - Tuesday, 7 December 2021, 1:04 AM

Great explanation, also when the programs start to get more confusing and we start using more variables and different
data types, we could use built-in functions such as type(), isinstance(), to check what kind of data are the functions
returning.
40 words

Permalink Show parent

Re: Discussion Unit 4


by Siphumelelise Ntshwenyese - Tuesday, 7 December 2021, 3:29 AM

Wilmer,

Fantastic explanation, however, I struggled to follow your code, comments would have been helpful, thank you for citing

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 22/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

your work, keep it up.

24 words
26 words

Permalink Show parent

Re: Discussion Unit 4


by Wilmer Portillo - Tuesday, 7 December 2021, 5:48 PM

Hi siphumelelise, I will include comments the next time. :) Thank you for your feedback.
15 words

Permalink Show parent

Re: Discussion Unit 4


by Crystal Noralez - Tuesday, 7 December 2021, 12:59 PM

Wilmer,

Will done on explaining the worksheet. I can see that you check the data and the variables very well. Job well done.
23 words

Permalink Show parent

Re: Discussion Unit 4


by Fouad Tarabay - Wednesday, 8 December 2021, 9:45 AM

Hello Wilmer,

The explanation was great and clear, I can understand more if you include some comments.

Great work.
19 words

Permalink Show parent

Re: Discussion Unit 4


by Peter Odetola - Wednesday, 8 December 2021, 11:31 PM

Thanks a lot Wilmer for your work output. You use a simple, clear example to explain the concept of precondition and
postcondition. Thanks
23 words

Permalink Show parent

Re: Discussion Unit 4


by Juan Duran Solorzano - Monday, 6 December 2021, 10:26 PM

  Precondition and postcondition are different phases of the cycle of a function, precondition is whenever we call a function
python must check everything is defined, and in order following python syntax rules.

  The postcondition is what happens after we call a function knowing all the preconditions match, basically what happens with
the data process, the changes made within the function, and what data the function will return. 

Once mentioned post and preconditions, if a function is not working correctly we should consider checking the following:

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 23/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

1 - First the function arguments could have been set in different places or they could have not been defined at all. In some
cases, the precondition could lead to misleading results or could break the code leading to an exception error. 

2-  Second we should check if the function is defined correctly following the syntax, and the result we are looking for.

3- Third we always have to be careful where we use the return value as sometimes we could have dead code meaning we
return the value before finishing the cycle of the function. 

Examples:

1- 

def say_my_name(name): #This function just print a name

print(name)

say_my_name(name) #In this line we are calling the function with the argument name.

name = “Juan Carlos” #The variable name has been defined after we call the function, giving us an error.

Output:

Traceback (most recent call last):

File "/Users/juank/Documents/test.py", line 7, in <module>

  say_my_name(name)

NameError: name 'name' is not defined

The way to fix this program is to define the variable before calling a function, otherwise, we would get a precondition error.

2- 

name = "Juan Carlos"

age = 5

def say_my_name(name): #This function just print a name

print(name + age) # This line is trying to concatinate a string with an interger

say_my_name(name) #In this line we are calling the function with the argument name.

Output:

Traceback (most recent call last):

File "/Users/juank/test.py", line 7, in say_my_name

print(name + age)

TypeError: can only concatenate str (not "int") to str

In the previous example, the data types used are not compatibles for the interpreter to do the action, having. a postcondition
error, as all the syntax, is correct but the data entered doesn’t match.

To fix this error, we could use different built-in functions to check what kind of data type each variable is.

3-

name = "Juan Carlos" 


def say_my_name(name):

return # return value is before the action required

print(name + 5) # dead code

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 24/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4
say_my_name(name)

Output:

(base) juank@Macs-MBP-3 Uopeople %

In this example, we are using the return value before printing the name that way the code after that will be considered dead
code, and the interpreter will not reach those lines

References

A. (2016, March 31). Preconditions and Postconditions. HeelpBook. https://www.heelpbook.net/2016/preconditions-and-


postconditions/

458 words

Permalink Show parent

Re: Discussion Unit 4


by Siphumelelise Ntshwenyese - Tuesday, 7 December 2021, 1:59 AM

Juan

You explained precondition and postconditions very simply and to the point, I like your point regarding dead-code, I have
made a few mistakes similar to that where you find unused logic.

Also great use of citation, well done.


39 words

Permalink Show parent

Re: Discussion Unit 4


by Siphumelelise Ntshwenyese - Tuesday, 7 December 2021, 1:18 AM

The "Pre" and "Post" condition Idea is a tough one to grasp but in a nutshell these are are constraints used in expressing
precisely what it means to use an operation that belongs to some class.

The important keywords to note here are:


Pre: What must be true for the operation to take place
Post: A condition that is guaranteed after the operation completes.

You can have one of these or both of these at the same time, here are some examples,

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 25/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

From the example above we can see from the comments how pre and post conditions can be identified within a function.

References

Downey, A. (2015). Think Python: How to think like a computer scientist. Green Tea Press.Ullah, M. Y.  Khalid (2017). Python
Tips. Retrieved from https://book.pythontips.com/en/latest/mutation.html

128 words

Permalink Show parent

Re: Discussion Unit 4


by Crystal Noralez - Tuesday, 7 December 2021, 1:07 PM

Hey Siphumelelise,

You did a good job in explaining the exercise. Keep up the great work.
16 words

Permalink Show parent

Re: Discussion Unit 4


by Siphumelelise Ntshwenyese - Wednesday, 8 December 2021, 12:01 AM

Thank you Crystal


3 words

Permalink Show parent

Re: Discussion Unit 4


by Luke Henderson - Tuesday, 7 December 2021, 3:10 AM

Debugging

Possibility 1:

There is an apparent contradiction in the arguments provided in the function, such as an input error. For example if the
function had a predefined data type that is required and the wrong data type was given, this could be part of the pre-
condition. When we refer to the pre-condition we mean that a condition that must be true so that a function or section of a
program can run as intended. if pre-conditions are met the function can do what it is intended to do(Software Carpentry, n.d.).

Possibility 2:

In the body of the function there maybe an inconsistency with the input and the conditions provided. e.g. if a value given is
higher than the required threshold. This kind of issue is often referred to as a post-condition problem, whereby a condition
that a function or section of a program should confirm to be true or false once it has finished executing. post-conditions are
often represented using the assert keyword(Software Carpentry, n.d.).

Possibility 3:

The return value is incorrect or one or more of the values required to produce the return value is invalid.

Possibility 1 Program

def double():

     
value = int(input())

     
print(value * 2)

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 26/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Input:

double()
“bill”

Output:

Traceback (most recent call last):

File "", line 1, in double()

File "", line 2, in double

value = int(input())

ValueError: invalid literal for int() with base 10: '"bill"'

Possibility 2 Program

def oneToTen():

      
num = int(input(“enter a number between 1 and 10”))

      
assert num > 10, “That is not a number between 1 and 10”

      
print(num)

Input:

oneToTen()

16

Output:

Traceback (most recent call last):

File "", line 1, in oneToTen()

File "", line 3, in oneToTen

assert num < 10 and num > 0, "That is not a number between 1 and 10"

AssertionError: That is not a number between 1 and 10

Possibility 3 Program:

def divider(val1, val2):

     
return val1 / val2

Input:

divider(12, "cheese")

Output:

Traceback (most recent call last):

File "", line 1, in divider(12, "cheese")

File "", line 2, in divider

return val1 / val2

TypeError: unsupported operand type(s) for /: 'int' and 'str'

Resources

Software Carpentry. (n.d.). Defensive programming. Retrieved on 06/12/21 from https://swcarpentry.github.io/python-novice-


inflammation-2.7/08-defensive.html
364 words

Permalink Show parent

Re: Discussion Unit 4


https://my.uopeople.edu/mod/forum/discuss.php?d=640877 27/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

by Simon Njoroge - Tuesday, 7 December 2021, 9:50 AM

Well done. You have shown a lot of effort in perfectly defining the terms required in the exercise. The examples you gave
also contributed to my understanding on this discussion. Your codes are simple but quite informative . Your work is highly
appreciated.
43 words

Permalink Show parent

Re: Discussion Unit 4


by Crystal Noralez - Tuesday, 7 December 2021, 1:01 PM

There was a lot of effort put in this exercise. You example very well and it was clear and understandable. Keep up the good
job.
25 words

Permalink Show parent

Re: Discussion Unit 4


by Crystal Noralez - Tuesday, 7 December 2021, 11:31 AM

Discussion Forum Unit 4

Debugging

Section 6.9 of your textbook ("Debugging") lists three possibilities to consider if a function is not working.

A. There is something wrong with the arguments the function is getting; a precondition

is violated. (Downey, 2015, p. 59)

Answer:
It might be that we do not defined and argument when submitting a code, due to that, we would get the bug and an error
notification. An Example would be:

Correct = float (input ('enter correct: '))

def Grade(correct, points):

grade=correct*points

if (grade < 69.9):

return 'D, You Failed’, grade

elif (grade >= 70 and grade < 79.9):

return 'C, You Average’, grade

elif (grade >= 80 and grade <89.9):

Return 'B, You Good’, grade

elif (grade >= 90 and grade < 95):

Return 'A, You Excellent’, grade

Quote, grade = Grade (correct, points)

Print ('your grade is: {} and: {}'.format (grade, quote))


= RESTART: D:\Users\Noralez\Documents\sync\UoPeople\Term 3\Programming Fundamentals\Unit 4\Assessments\Python
files\Discussion forum Unit 4.py

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 28/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

quote, grade = Grade(correct, points)

Name Error: name 'points' is not defined

Name Error: name 'points' is not defined.

In this case, the variable ‘Point’ is used, but Python do not recognized an assignment statement for this variable. This is call
“precondition.”

B. There is something wrong with the function; a postcondition is violated. (Downey, 2015, p. 59)

Answer:

I've never done programming before, nor used python, so I usually make mistakes at the moment of writing codes inside
functions. This error makes my program not work as I expect it to, or do the opposite of what I want it to do, or produce
runtime errors.

correct = float(input('enter correct: '))


points= float (input('enter points:'))

def Grade(correct,points):

grade=correct*points

if (grade < 69.9):

return 'D, You Failed',grade

elif (grade <= 70 and grade > 79.9):

return 'C, You Avarage',grade

elif (grade <= 80 and grade >89.9):

return 'B, You Good',grade

elif (grade <= 90 and grade > 95):

return 'A, You Excellent',grade

quote, grade = Grade(correct,points)

print('your grade is: {} and: {}'.format(grade, quote))

= RESTART: D:\Users\Noralez\Documents\sync\UoPeople\Term 3\Programming Fundamentals\Unit 4\Assesments\Python


files\Discussion forum Unit 4.py

enter correct: 9

enter points:10

your grade is: 90.0: A, Failed

This is what is known as postcondition violation

C. There is something wrong with the return value or the way it is being used. (Downey, 2015, p. 59)

If we don't type the return value of a function's arguments in the right way, we might not get the result as we want. This might
happen because we could write the codes inside the functions in the wrong way or the arguments might not be correctly
written.

def Grade(correct,points):


grade=correct*points

if (grade < 69.9):

return D, You Failed,grade

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 29/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Reference

Downey, A. (2015). Think Python| How to Think Like a Computer Scientist: Vol. Version 2.2.23 (2nd Edition). Green Tea Press.
https://my.uopeople.edu/pluginfile.php/1404469/mod_page/content/3/TEXT%20-%20Think%20Python%202e.pdf
459 words

Permalink Show parent

Re: Discussion Unit 4


by Luke Henderson - Wednesday, 8 December 2021, 12:24 AM

Great summary of the 3 debugging issues and an explanation for each. You gave some great examples too. I especially
liked that you demonstrated that return calls can be used more than once within a function definition. Keep up the great
work.
42 words

Permalink Show parent

Re: Discussion Unit 4


by Janelle Bianca Cadawas Marcos - Tuesday, 7 December 2021, 1:56 PM

According to our textbook, there are three possibilities to consider


for a faulty function.

First, the argument


used is invalid for the code, a “precondition.” Precondition
means the status of the argument used for the
function. For example
if the function needs an int input, a str will not work. You need to
double check the function arguments
before you call for it again.

>>>def
feed_dog(weight, age): #kg and months

. . .       if age <


13:

. . .           food
= str(20*weight)

. . .           return "Feed dog " + food + " grams per day."

. . .       else:

. . .          food
= str(10*weight)

. . .          return "Feed dog " + food + " grams per day."

...

>>>feed_dog(“20”,15)
#sample code for first possibility

. . .   ‘Feed dog
20202020202020202020 grams per day.’

This is not the


output we want from the function. The wrong precondition created a
semantic error.

Second possibility,
the function itself is wrong, a “postcondition” is not met.
Postcondition is what happens after the code is
run. In this case,
you need to look over the function and fix it.

>>>def
feed_dog(weight, age): #kg and months

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 30/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

. . .       if age <


13:

. . .          food
= 20*weight

. . .          return "Feed dog " + food + " grams per day."

. . .      else:

. . .         food
= 10*weight

. . .         return "Feed dog " + food + " grams per day."

...

>>>feed_dog(20,15)

. . .   Traceback
(most recent call last):

. . .       File
"<pyshell#57>", line 1, in <module>

. . .           feed_dog(20,15)

. . .       File
"<pyshell#56>", line 7, in feed_dog

. . .           return "Feed dog " + food + " grams per day."

. . .   TypeError:
can only concatenate str (not "int") to str

This error happened


because of the syntax error within the function.

Third possibility,
the way the return value was coded in is wrong.

>>>def
feed_dog(weight, age): #kg and months

. . .       if age <
13:

. . .          food
= str(20*weight)

. . .          return weight

. . .      else:

. . .          food
= str(10*weight)

. . .          return weight

...

>>>feed_dog(20,15)

. . .   20

This is not the


output we want, I used the wrong return value. To fix it, double
check if the return value is what you really want

to return.

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 31/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Reference:

Downey, A. (2015).
Think Python: How to think like a computer scientist. Green Tea
Press. This book is licensed under Creative
Commons
Attribution-NonCommercial 3.0 Unported (CC BY-NC 3.0).

435 words

Permalink Show parent

Re: Discussion Unit 4


by Yahya Al Hussain - Tuesday, 7 December 2021, 3:31 PM

great examples, neat simple and divided code for each example, shows understanding of the subject .

keep up the good work!


21 words

Permalink Show parent

Re: Discussion Unit 4


by Luke Henderson - Wednesday, 8 December 2021, 12:21 AM

This was a quick and concise post covering the 3 common debugging issues. You gave some great examples put perhaps
could have expanded on the terms a little more. Keep up the good work.
34 words

Permalink Show parent

Re: Discussion Unit 4


by Stephen Chuks - Wednesday, 8 December 2021, 2:26 PM

Great one from you. You explained in full detailed everything that was expected. And your examples are in order

19 words

Permalink Show parent

Re: Discussion Unit 4


by Hamidou Diallo - Wednesday, 8 December 2021, 11:14 PM

Hi, Janelle you did a good job. All of the descriptions was good. The examples are proof of what you've describe on top. I
can that you've add the reference which I forget on comment. Keep up the good work.
40 words

Permalink Show parent

Re: Discussion Unit 4


by Leameo Gilah - Tuesday, 7 December 2021, 6:11 PM

When you debug a code, it means you locate and correct the error(s) in the code. The three possibilities of a function not
working properly are:

1) Invalid arguments

2) Incorrect function operation

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 32/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

3) Incorrect return value or return type

Invalid arguments - This arises when the number of parameters does not match with the number of arguments passed to the
function.
This is also referred to as violation of precondition.

An example in python is as follows:

def addition(a, b):

return a + b

addition(5)

The above function receives 1 parameter, instead of two. 

Incorrect function operation - This arises when the function does not perform the required operation.
This is also referred to as
violation of post-condition. 

An example in python is as follows:

def squareNum(a):

return a * 2

The above function returns twice a number, instead of its square.

Incorrect return value or return type


This arises when the function returns a different value or data type, different from what it
is expected to return
An example in python is as follows:

def squareNum(a):

   sq = a**2

    return sq

The above function is expected to return the square of a number, but it returns the number itself
201 words

Permalink Show parent

Re: Discussion Unit 4


by Luke Henderson - Wednesday, 8 December 2021, 12:18 AM

You put the 3 possibilities of debug errors into your own words and gave a great example for the pre-condition issue,
however it appears there is some part missing from your post as you were also supposed to give an example for the post-
condition and return value issues seperately. Please be more careful so as not to receive a lower mark.
61 words

Permalink Show parent

Re: Discussion Unit 4


by Stephen Chuks - Wednesday, 8 December 2021, 2:18 PM

Good one from you. You made some good effort. However, I did not understand all your points.  And you did not call your
functions with argument to make it clear enough. But I like that you gave examples of each possibilities. 

41 words

Permalink Show parent

Re: Discussion Unit 4


by Stephen Chuks - Wednesday, 8 December 2021, 1:49 PM

If a python code is not working as expected, there are 3 probable causes Downey, A.(2015).

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 33/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

The first likely cause is  issue with the parameters. This type of problem is known as the precondition preconditions are
conditions that must always be true before a function call.  And to check for this, you use the print statement. After checking
and seeing that the precondition is in the order, the next possibility to consider if there is a problem with the argument. And
this second stage is known as the postcondition. Postconditions are conditions that must always be true immediately after a
function call. If after both checks and everything is in order, then we consider the a third option, which is to check if the return
value is being used correctly.

Downey, A. (2015). Think Python: How to think like a computer scientist. This book is licensed under Creative Commons
Attribution-NonCommercial 3.0 Unported (CC BY-NC 3.0)

155 words

Permalink Show parent

Re: Discussion Unit 4


by Ismail Ahmed - Wednesday, 8 December 2021, 4:19 PM

Greetings to our instructor and students

If a function is not working, there are three reasons:

1 The arguments passed are incorrect i.e. precondition is violated

2 The function body throws run-time error i.e. postcondition is violated

3 The return function is not as expected

Precondition: indicates what must be considered correct before executing the function

Post-condition: indicates what must be correct if the precondition is met

Below function definition prints out number if square root or not:

def square_root(num1,num2):

ans="This is square number"

ans2="This is not"

new_num = num1 / num2

if(new_num==num2):

return ans

else:

return ans2

For precondition example, pass three arguments instead of two:

input: square_root(10,2,1)

Output: TypeError: square_root() takes 2 positional arguments but 3 were given

For postcondition example, pass second number as 0:

input: square_root(10,0)

Output: ZeroDivisionError: division by zero

To check return type correct, delibarately pass ans variable instead of ans2 variable in return statement under else condition as
shown below:

def square_root(num1,num2):

ans="This is square number"

ans2="This is not"

new_num = num1 / num2

if(new_num==num2):

return ans

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 34/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

else:

return ans

input: square_root(10,3) or square_root(9,3) or square_root(15,5)

output: This is square number (whatever result ans variable is printed)

Reference:

Downey, A. (2015). Think Python: How to Think Like a Computer Scientist. Needham, Massachusetts: Green Tea Press
212 words

Permalink Show parent

Re: Discussion Unit 4


by Newton Sudi - Wednesday, 8 December 2021, 5:32 PM

You explained everything well and used the meaningful program examples. keep up the great work.
15 words

Permalink Show parent

Re: Discussion Unit 4


by Hamidou Diallo - Wednesday, 8 December 2021, 11:10 PM

Hi Ismail, you example was insights and refer to the different cases you've listed on top. Keep up the good work. You made
me realize that I miss to add reference thank you.
33 words

Permalink Show parent

Re: Discussion Unit 4


by Newton Sudi - Wednesday, 8 December 2021, 4:37 PM

1. Giving a function an invalid argument creates a violated precondition, which makes the function not work. Precondition is
the problem before the argument of the function which must be true at the beginning of the function for the call function to
run.

2. Postcondition is a problem caused by a function immediately following the arguments being passed (Downey, A.2015). A
variable can hold specific values inside a function and even mutate without the programmer's knowledge and that creates a
critical sequence of events that can cause a function not to work.

3. The moment of computation return can cause a function not to work if it's not provided. Without a return statement, there
will be no value to be returned and a function may end up calling unnecessary statements.

1.Precondition

input:

def countdown(n):

N=int(n)

if N =0:

print('Processing...')

else:

print(N)

countup(N+1)

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 35/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

def timercountdowncheck():

n=input("Enter Your Timer Duration  <=15:\n")


  N=int(n)
  if N==0 or N>15 or N<-15:
      print("Enter a value more or less than that. ")
  elif N>0:
      #counting the positive number.
   countdown(n)
  else:
      countup(n)

def auto_switcher(n):
  bulb = ("Turned")
  print('Switching', 'ON')
  if n==0:
      print("Switching", 'OFF')
      return 0
      
  else:
      recurse = auto_switcher(n-1)
      result = n * recurse
      print("Switching", result, "", "OFF")
      return result
auto_switcher(timercountdowncheck())

Output demonstrating precondition;

Enter Your Timer Duration <=15:


5
4
3
2
1
0
Processing
Switching ON
Traceback (most recent call last):
File "D:\Programs\morerecurse.py", line 43, in <module>
  auto_switcher(timercountdowncheck())
File "D:\Programs\morerecurse.py", line 38, in auto_switcher
  recurse = auto_switcher(n-2)
TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'

#Trying to replace the argument with an int or any kind of an expression will result in the function auto_swither not working
since the precondition will have been violated.

Reference
Downey, A. (2015). Think Python: How to think like a computer scientist. Green Tea Press.

295 words

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 36/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Permalink Show parent

Re: Discussion Unit 4


by Hamidou Diallo - Wednesday, 8 December 2021, 9:20 PM

A function cannot run if:

** When the function has arguments, it might not run if you make an error on one of the arguments.

For example:

def compil():

S=n*2

print(s)

compil(4)

In this example we didn't specify a parameter before we could generalize the function

** A conditional function will never run, if something wrong before the condition starts or the precondition.

def bigger_than(x,y):

s= t

if s>=0

print(" the expression is

positive", s)

else:

print(" the expression is

negative")

bigger_than(x,y)

This function won't run because t is not define it will outcome an error.

** all code that come after a return value wont run.

For example:

s=x+y

Return s

If s>0:

print(" this is a positive value")

else:

print(" this is a negative value")

Everything that after the retun value won't run as define on the book.
140 words

Permalink Show parent

Re: Discussion Unit 4


by Peter Odetola - Wednesday, 8 December 2021, 9:23 PM

CS1101 DISCUSSION UNIT 4

Describe three possibilities to consider if a function is not working. Define “precondition” and “postcondition” as part of your
description. There is something wrong with the arguments the function is getting; a precondition

is violated.

1. There is something wrong with the arguments the function is getting: since argument is an expression that occurs within the

parentheses of a method call, precondition shows a function’s expectation on its arguments while postcondition reflects the
outcome of running the method. If there is something wrong with the arguments the function is getting, a precondition is
violated. Debugging is therefore necessary if the user did not put the right arguments when calling the function. If the user

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 37/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

passes a float number instead of an integer, the precondition is violated. There is need to check the function parameters via
writing codes that troubleshoot them or print their values.

2. There is something wrong with the function: Since a function is a set of instructions to be carried out, precondition shows
what must be true before the function is called and postcondition shows what holds after running the method or upon exit
from a function. A function without the right logic violates the precondition. In order to debug the function error, we can print
different return values and we can also print the value of different calculated variables to test the expected values.

3. There is something wrong with the return value or the way it is being used: since a return value is a statement which
terminates the execution of the function body in which it occurs, precondition ensures that an expression is established first in
the function call, while postcondition is what the method expects in order to do its job properly. To debug error with the return
value, it is important to understand how the user it so as to ascertain correct input value. We can also write a documentation
for the user on how to use the function properly.

Create your own example of each possibility in Python code. List the code for each example, along with sample output from
trying to run it.

Example 1: Using the wrong argument type

>>> def add(a,b,c):

... d = a+b+c

... return d

...

>>> print(add(5,6))

Traceback (most recent call last):

File "", line 1, in print(add(5,6))

TypeError: add() missing 1 required positional argument: 'c'

Because the argument of print(add(5,6)) does not agree with the precondition statement def add(a,b,c):, the result shows an
TypeError for missing out the required positional argument for c.

Example 2: Something wrong in the function

>>> def add(a,b,c):

... d = abc

... return d

...

>>> print(add(5,6,7))

Traceback (most recent call last):

File "", line 1, in print(add(5,6,7))

File "", line 2, in add

d = abc

NameError: name 'abc' is not defined. Did you mean: 'abs'?

The postcondition statement in the computation is false because d = abc does not agree with the defined function.

Example 3: Something wrong with the return value

>>> def add(a,b,c):

... d = a+b+c

... return e

...

>>> print(add(5,6,7))

Traceback (most recent call last):

File "", line 1, in print(add(5,6,7))


File "", line 3, in add

return e

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 38/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

NameError: name 'e' is not defined

The return value is invalid as it is not linked with the original defined function.
554 words

Permalink Show parent

Re: Discussion Unit 4


by Hamidou Diallo - Wednesday, 8 December 2021, 11:07 PM

Hi Peter, you describes the conditions very well. You make me realize that I forgot to show the outcomes of my example.

Your examples was great and refer to you description. Keep up the good work.
36 words

Permalink Show parent

UoPeople Clock (GMT-5)

All activities close on Wednesdays at 11:55 PM, except for Learning Journals/Portfolios which close on Thursdays at 11:55 PM always
following the clock at the top of the page.

Due dates/times displayed in activities will vary with your chosen time zone, however you are still bound to the 11:55 PM GMT-5
deadline.

◄ Learning Guide Unit 4

Jump to...

Programming Assign. Unit 4 ►

Disclaimer Regarding Use of Course Material  - Terms of Use


University of the People is a 501(c)(3) not for profit organization. Contributions are tax deductible to the extent permitted by law.
Copyright © University of the People 2021. All rights reserved.

You are logged in as Stephen Chuks (Log out)


Reset user tour on this page
 www.uopeople.edu










Resources
UoPeople Library
Orientation Videos
LRC
Syllabus Repository
Honors Lists
Links

About Us
Policies

University Catalog
https://my.uopeople.edu/mod/forum/discuss.php?d=640877 39/40
1/5/22, 1:48 AM CS 1101 - AY2022-T2: Discussion Unit 4

Support
Student Portal
Faculty
Faculty Portal
CTEL Learning Community
Office 365
Tipalti
Contact us
English (‎en)‎
English (‎en)‎
‫ العربية‬‎(ar)‎
Data retention summary
Get the mobile app

https://my.uopeople.edu/mod/forum/discuss.php?d=640877 40/40

You might also like