General Programming Introduction to Computing Science and Programming I.
-
Upload
patrick-hood -
Category
Documents
-
view
217 -
download
4
Transcript of General Programming Introduction to Computing Science and Programming I.
General ProgrammingGeneral Programming
Introduction to Computing Introduction to Computing Science and Programming IScience and Programming I
General ProgrammingGeneral Programming
Basic set of steps for writing a Basic set of steps for writing a programprogram Define the problem.Define the problem. Create an algorithm to solve the problem Create an algorithm to solve the problem
and write it out in pseudocodeand write it out in pseudocode Convert this algorithm into actual code, Convert this algorithm into actual code,
testing small parts of it along the waytesting small parts of it along the way When finished converting the algorithm to When finished converting the algorithm to
code, test for errorscode, test for errors Debug any errors and go back to the Debug any errors and go back to the
previous stepprevious step
General ProgrammingGeneral Programming
When you are finished writing your When you are finished writing your algorithm, look for pieces that you algorithm, look for pieces that you can program and test separately.can program and test separately.
To illustrate the point, let’s look at To illustrate the point, let’s look at the second part of Lab 2 and see how the second part of Lab 2 and see how we can break it apartwe can break it apart
ExampleExample Write a program that displays a menu to the user and based on their Write a program that displays a menu to the user and based on their
choice, calculates the area of a circle or triangle who’s attributes are input choice, calculates the area of a circle or triangle who’s attributes are input by the user.by the user.
AlgorithmAlgorithmwrite menu to screenwrite menu to screenread optionread optionif option is triangleif option is triangle
read base/height from userread base/height from userif base and height are >= 0if base and height are >= 0
calculate and display areacalculate and display areaelseelse
display errordisplay errorelse if option is circleelse if option is circle
read radiusread radiusif radius is >= 0if radius is >= 0
calculate and display circle’s areacalculate and display circle’s areaelseelse
display errordisplay errorelse else
write incorrect option enteredwrite incorrect option entered
ExampleExample
What parts of this algorithm can you What parts of this algorithm can you code and test separately?code and test separately? Menu StructureMenu Structure Triangle calculationTriangle calculation Circle calculationCircle calculation User input and check for negative valuesUser input and check for negative values
Each of these could be coded and Each of these could be coded and tested separately before combining.tested separately before combining.
General ProgrammingGeneral Programming
This idea of breaking the problem up This idea of breaking the problem up may seem unimportant when may seem unimportant when working with the small programs we working with the small programs we are now, but it is still helpful.are now, but it is still helpful.
When you move on to more complex When you move on to more complex programs the idea is essential.programs the idea is essential.
If you write large amounts of code If you write large amounts of code with having made sure small pieces with having made sure small pieces are correct, finding errors becomes are correct, finding errors becomes more difficult. more difficult.
ErrorsErrors
You will encounter errors as you You will encounter errors as you write your programs.write your programs.
There are other ways to categorize There are other ways to categorize them, but we will look at three basic them, but we will look at three basic types of error.types of error. Syntax ErrorsSyntax Errors Runtime ErrorsRuntime Errors Semantic ErrorsSemantic Errors
Syntax ErrorsSyntax Errors
Errors in the syntax of your code.Errors in the syntax of your code. Syntax refers to the rules that Syntax refers to the rules that
define proper statements. define proper statements. Python will detect syntax errors and Python will detect syntax errors and
not allow you to run your code until not allow you to run your code until you correct them.you correct them.
Runtime ErrorsRuntime Errors
Once your code has no syntactic errors, Once your code has no syntactic errors, you are allowed to execute ityou are allowed to execute it
Runtime errors refer to errors that do not Runtime errors refer to errors that do not present themselves until your code is present themselves until your code is executed (runtime).executed (runtime).
Examples:Examples: Division by zero.Division by zero. Improper conversions.Improper conversions.
Your program will be terminated if a Your program will be terminated if a runtime error occurs during execution.runtime error occurs during execution.
Semantic ErrorsSemantic Errors
Errors in the semantics of your code.Errors in the semantics of your code. Syntax defines how you can create Syntax defines how you can create
statements. Semantics tell you what statements. Semantics tell you what the meaning of those statements the meaning of those statements are.are.
A program has semantic errors if it A program has semantic errors if it runs and completes, but does not do runs and completes, but does not do what it was created to.what it was created to.
Error MessageError Message When an error occurs, Python prints some info to help you When an error occurs, Python prints some info to help you
understand what happened. Learning how to understand understand what happened. Learning how to understand these error message will help you solve problems in your these error message will help you solve problems in your programs.programs.
For ExampleFor Example>>> 4/0>>> 4/0Traceback (most recent call last):Traceback (most recent call last): File "<pyshell#6>", line 1, in <module>File "<pyshell#6>", line 1, in <module> 4/04/0ZeroDivisionError: integer division or modulo by zeroZeroDivisionError: integer division or modulo by zero
The last line tells you what type of error occurred.The last line tells you what type of error occurred. The third line prints out the statement from that line.The third line prints out the statement from that line. The second line tells you on what line of code the error The second line tells you on what line of code the error
occurred. This is more helpful when executing a program.occurred. This is more helpful when executing a program.
Some Python ErrorsSome Python Errors
ZeroDivisionErrorZeroDivisionError NameErrorNameError
Try to use a variable that doesn’t exist.Try to use a variable that doesn’t exist. ValueErrorValueError
Try to convert an inappropriate string to Try to convert an inappropriate string to a numbera number
Correcting ErrorsCorrecting Errors
Strategies for correcting errors Strategies for correcting errors (debugging)(debugging) Remove parts of your code to see if they Remove parts of your code to see if they
are involved in the error.are involved in the error. Add print statements to check the value Add print statements to check the value
of a variable that is involved. (remember of a variable that is involved. (remember to remove these statements when to remove these statements when finished)finished)
Coding StyleCoding Style
Coding style deals with how you Coding style deals with how you format your code. Good coding style format your code. Good coding style makes it easy for people to makes it easy for people to understand your codeunderstand your code
Coding style issues.Coding style issues. CommentsComments Proper spacingProper spacing Good variable/function namesGood variable/function names
CommentsComments
A comment is text you put in your A comment is text you put in your code that will be ignored. This allows code that will be ignored. This allows you to give short explanations to you to give short explanations to help people understand your code.help people understand your code.
Use the # character and anything Use the # character and anything written after it will be ignoredwritten after it will be ignored
CommentsComments Don’t add comments to explain every lineDon’t add comments to explain every line
#add one to x#add one to xx = x+1x = x+1
Often useful to add a comment for chunks Often useful to add a comment for chunks of code, such as before control structuresof code, such as before control structures
# if the user entered good data, add it inif value >= 0:
sum = sum + valuecount = count + 1
# search for a value that divides numwhile num%factor != 0:
factor = factor + 1
SpacingSpacing
Poor spacing can make lines of Poor spacing can make lines of code more difficult to code more difficult to understand.understand. Bad: y = 100 / x+1 Good: y = 100/x + 1
Add blank lines in the code to Add blank lines in the code to make it easier to read.make it easier to read.
Coding StyleCoding Style BadBad
a = int(raw_input("Enter an integer: "))b = 0
for i in range(a+1):if i>0: if a % i==0: b = b + 1
print "There are " + str(b) + " factors.“
GoodGood# get user input and initializenum = int(raw_input("Enter an integer: "))count = 0
# check every possible factor (1...num)for factor in range(1, num+1):
# if factor divides num, it really is a factorif num%factor == 0: count = count + 1
# output resultsprint "There are " + str(count) + " factors."