15 Feb DUE IN 10 HOURS, APA, Programming? The code for this assignment should be compared to chapter one below Python Programming 3.html Python Programming 4.html The assignment file is the python
DUE IN 10 HOURS, APA, Programming
The code for this assignment should be compared to chapter one below
Python Programming 3.html
Python Programming 4.html
The assignment file is the python 1.docx
Writing Programs
Now that we have an idea of the basic types of data and we have seen how they can be receives from users as input, stored in variables, manipulated with operators and statements, and displayed back on screen, we can begin to write programs that actually do useful things. First, however, there is some basic elements to a program that are important to use and important to understand.
Program Header
One of the biggest problems I have in day-to-day web application development is wasting time trying to figure out what the heck this 10-year-old file is and what it does. All of this frustration can be avoided by simply documenting your source code, starting with a program header. Just list the file name, the program name, the original author, creation date, and purpose. If you want to get fancy, you can add rows for modifications and edits. You can copy and paste this header template into the top of all your Python programs. Just remember to fill in the blanks.
# FILE: # NAME: # AUTHOR: # DATE: # PURPOSE:
Example:
# FILE: tipping.py # NAME: Tipping Calculator # AUTHOR: Heather Crites # DATE: 3/5/2017 # PURPOSE: Calculates tips and bill based upon user input
Comments
As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.
For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments, and they start with the # symbol:
# compute the percentage of the hour that has elapsed percentage = (minute * 100) / 60
In this case, the comment appears on a line by itself. You can also put comments at the end of a line:
percentage = (minute * 100) / 60 # percentage of an hour
Everything from the # to the end of the line is ignored – it has no effect on the execution of the program.
Comments are most useful when they document non-obvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is more useful to explain why.
This comment is redundant with the code and useless:
v = 5 # assign 5 to v
This comment contains useful information that is not in the code:
v = 5 # velocity in meters/second.
Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff.
Use as many useful comments as you can in your program to:
- explain assumptions
- explain important decisions
- explain important details
- explain problems you're trying to solve
- explain problems you're trying to overcome in your program, etc
Code tells you how, comments should tell you why.
This is useful for readers of your program so that they can easily understand what the program is doing. Remember, that person can be yourself after six months!
Variables
Unless you like writing unmaintainable code, I suggest that you use descriptive names for most of your variables.
While naming a variable x is short and sweet, it is pretty meaningless when you are trying to determine whether x is the tip or the tax rate or the user's input. Better variable names would be tax_rate or TaxRate or varTaxRate. Find a style you like and stick with it.
Indentation
Whitespace is important in Python. Actually, whitespace at the beginning of the line is important. This is called indentation. Leading whitespace (spaces and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements.
This means that statements which go together must have the same indentation. Each such set of statements is called a block. We will see examples of how blocks are important in later chapters.
One thing you should remember is that wrong indentation can give rise to errors. For example:
i = 5 # Error below! Notice a single space at the start of the line print('Value is', i) print('I repeat, the value is', i)
When you run this, you get the following error:
File "whitespace.py", line 3 print('Value is', i) ^ IndentationError: unexpected indent
Did you notice that there is a single space at the beginning of the second line? The error indicated by Python tells us that the syntax of the program is invalid i.e. the program was not properly written. What this means to you is that you cannot arbitrarily start new blocks of statements (except for the default main block which you have been using all along, of course). Cases where you can use new blocks will be detailed in later lessons such as the control flow.
Use four spaces for indentation. This is the official Python language recommendation. Good editors will automatically do this for you. Make sure you use a consistent number of spaces for indentation, otherwise your program will not run or will have unexpected behavior.
Logical and Physical Line
A physical line is what you see when you write the program. A logical line is what Python sees as a single statement. Python implicitly assumes that each physical line corresponds to a logical line.
An example of a logical line is a statement like print('hello world') – if this was on a line by itself (as you see it in an editor), then this also corresponds to a physical line.
Implicitly, Python encourages the use of a single statement per line which makes code more readable.
If you want to specify more than one logical line on a single physical line, then you have to explicitly specify this using a semicolon (;) which indicates the end of a logical line/statement. For example:
i = 5 print(i)
is effectively same as
i = 5; print(i);
which is also same as
i = 5; print(i);
and same as
i = 5; print(i)
However, I strongly recommend that you stick to writing a maximum of a single logical line on each single physical line. The idea is that you should never use the semicolon. In fact, I have never used or even seen a semicolon in a Python program.
There is one kind of situation where this concept is really useful: if you have a long line of code, you can break it into multiple physical lines by using the backslash. This is referred to as explicit line joining:
Code | Output |
---|---|
s = 'This is a string. This continues the string.' print(s) |
This is a string. This continues the string. |
Similarly,
i = 5
is the same as
i = 5
Sometimes, there is an implicit assumption where you don't need to use a backslash. This is the case where the logical line has a starting parentheses, starting square brackets or a starting curly braces but not an ending one. This is called implicit line joining. You can see this in action when we write programs using lists in later lessons.
The Programming Process
One of the most difficult hurdles when you are just getting started is how to start a new program or tackle an exercise or lab assignment from the beginning. First, recognize that very few programmers immediately start to write code when they build their programs. They create them in stages. You should to. Here are some simple steps to try:
- Use pseudocode to design the program: sketch it out or write plain English to describe what you want the program to do. It is often most efficient to do this using comments within the source file itself.
- Fill in the pseudocode with real code: start using your programming tools to fill in the blanks.
- Fix any Syntax errors: You learned that syntax errors cause a program to not run at all. Try to run your program, then fix all of these.
- Test the program repeatedly: use different inputs – negative numbers, letters, floats, and integers. See what sticks and what doesn't work. Fix some of your code if you don't get expected results.
Example:
You need to create a program which can accept a user's name and age, and displays it on the screen.
Step 1: Use pseudocode to design the program
In this example, I have written my header, then begin to sketch out the program using comments as pseudocode. I kept it simple and in plain terms. I don't need to write a novel.
Step 2: Fill in the pseudocode with real code
Now I have filled in the blanks with code. For welcoming the user to the program, I used a print statement with a triple quote string. I created two variables to store the keyboard input received from the user for both the name and the age. I then returned the input back to the user with some extra remarks using the print statement.
Step 3: Fix any Syntax errors
Uh oh! I made a syntax mistake. It says an unexpected indent. This means I have an indentation problem. IDLE has highlighted a space in front of my variable called Name. This space shouldn't be here. I delete the space, correcting my indentation, and now I can run my program without a syntax error.
Step 4: Test
Now that I fixed my syntax error, my program runs. I put Heather in when prompted for the name and 25 when prompted for the age. Unfortunately, my program stopped running because of a runtime error. It says NameError: name 'name' is not defined. I look at my code and I see my problem. Variable names are case sensitive. I assigned the input received for the user's name to a variable called Name with an uppercase N, but then tried to display a variable called name with a lowercase N. These are two different variables and I never assigned any value to the lowercase version, which is why the error was thrown. I change Name to name and run it again:
The whole program ran without errors! I run it a few more times and test different values until I am satisfied that it runs the way it is supposed to.
This is a very simple example, but it shows the common steps used.
Putting it All Together
- Use a program header
- Use comments
- Name your variables well
- Use appropriate indentation (4 spaces is best)
- Understand the difference between a physical line and a logical line
- Create your programs in stages
Expressions, Operators, and Statements
Time for a little more lingo. All programs will contain a combination of expressions, operators, and statements.
Expressions
Most programs that you write will contain expressions. An expression is a combination of values, variables, and operators. A simple example of an expression is 2 + 3. When you type an expression at the prompt, the interpreter evaluates it, which means that it finds the value of the expression. In this case, the expression 2 + 3 evaluates to 5 (because 2 + 3 = 5).
However, a value all by itself is also considered an expression, and so is a variable, so the following are all legal expressions:
Expression | Result | Notes |
---|---|---|
42 | 42 | |
n | 17 | |
n + 25 | 42 |
In this example, n has the value 17 and n + 25 has the value 42 because 17 + 25 = 42. |
Operators
Operators are functionality that do something and can be represented by symbols such as + or by special keywords. Operators require some data to operate on and such data is called operands. In this case, 2 and 3 are the operands.
The following are expressions which contain an operator:
Expression | Result | Notes |
---|---|---|
2 + 3 | 5 |
We are performing addition in this example. The operator is the plus sign. |
3 * 5 | 15 |
We are performing multiplication in this example. The operator is the multiplication sign. |
Statements
A statement is a unit of code that has an effect, like creating a variable or displaying a value. Statements contain expressions. Expressions may contain one or more operators.
n = 17 print(n)
The first line is an assignment statement that gives a value to n. The second line is a print statement that displays the value of n.
When you type a statement, the interpreter executes it, which means that it does whatever the statement says. In general, statements don't have values – they perform actions.
Mathematical Operators
Here is a brief run through of the most common mathematical operators in Python. A special thing to note is that these operators can work on all data types – not just integers and floats. Strings, sequences, and objects can all use these mathematical operators.
+ (plus)
The plus + operator performs addition on two objects.
Expression | Result | Notes |
---|---|---|
3 + 5 | 8 |
Notice that the result is an integer. |
1.5 + 2.5 | 4.0 |
Notice that the result is a float. |
1 + 1.0 | 2.0 |
Notice that we are adding an integer and a float. The result is a float. |
'a' + 'b' | 'ab' |
– (minus)
The minus – operator gives the subtraction of one number from the other; if the first operand is absent it is assumed to be zero. Minus does not work with strings.
Expression | Result |
---|---|
-5.2 | -5.2 |
50 – 24 | 26 |
* (multiply)
The multiply operator gives the multiplication of the two numbers or returns the string repeated that many times.
Expression | Result |
---|---|
2 * 3 | 6 |
'la' * 3 | 'lalala' |
** (power)
The power operator performs an exponentiation; that is, it returns x to the power of y. Power does not work with strings.
Expression | Result | Notes |
---|---|---|
3 ** 4 | 81 |
This is the same as 34 which is the same as 3 * 3 * 3 * 3 |
4 ** 2 | 16 |
This is the same as 42 which is the same as 4 * 4 = 16 |
/ (divide)
The division / operator divides x by y. Python will always return a float. Divide does not work with strings.
Expression | Result | Notes |
---|---|---|
13 / 3 | 4.333333333333333 |
Note that this returns a float |
4 / 2 | 2.0 |
Note that even though 4 / 2 = 2, python returns a float and not an integer. |
0 / 5 | 0.0 |
Note that even though 0 / 5 = 0, python returns a float and not an integer. |
// (divide and floor)
The floor division operator, //, divides two numbers and rounds down to an integer. Divide and floor does not work with strings.
Expression | Result | Notes |
---|---|---|
13 // 3 | 4 |
Note that this returns an integer |
4 // 2 | 2 |
Note that this returns an integer |
0 // 5 | 0 |
Note that this returns an integer |
-13 // 5 | -3 |
Note that this returns an integer |
When would you want to use this? Suppose the run time of a movie is 105 minutes. You might want to know how long that is in hours. Conventional division returns a floating-point number:
Code | Output |
---|---|
minutes = 105 | none |
minutes = minutes / 60 | none |
print(minutes) | 1.75 |
But we don't normally write hours with decimal points. Floor division returns the integer number of hours, dropping the fraction part:
Code | Output |
---|---|
minutes = 105 | none |
hours = minutes // 60 | none |
print(hours) | 1 |
To get the remainder, you could subtract off one hour in minutes:
Code | Output |
---|---|
remainder = minutes – hours * 60 | none |
print(remainder) | 45 |
% (modulo)
The modulus operator % divides two numbers and returns the remainder.
Expression | Result | Notes |
---|---|---|
13 % 3 | 1 |
Note that this returns an integer |
-25.5 % 2.25 | 1.5 |
Note that this returns a float |
We can use the modulus operator % on our movie running time example.
Code | Output |
---|---|
remainder = minutes % 60 | none |
print(remainder) | 45 |
The modulus operator is more useful than it seems. For example, you can check whether one number is divisible by another – if x % y is zero, then x is divisible by y.
Also, you can extract the right-most digit or digits from a number. For example, x % 10 yields the right-most digit of x (in base 10). Similarly x % 100 yields the last two digits.
Assignment and Operation Shortcuts
It is common to run a math operation on a variable and then assign the result of the operation back to the variable, hence there is a shortcut for such expressions:
a = 2 a = a * 3
can be written as:
a = 2 a *= 3
Notice that variable = variable operation expression becomes variable operation= expression.
Other examples:
Long Code | Shortcut Code |
---|---|
a = a + 5 | a += 5 |
a = a – 2.25 | a -= 2.25 |
a = a * 4 | a *= 4 |
a = a/3 | a /= 3 |
Order of Operations
If you had an expression such as 2 + 3 * 4, is the addition done first or the multiplication?
When an expression contains more than one operator, the order of evaluation depends on the order of operations. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:
- Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it doesn't change the result.
- Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2 * 3**2 is 18, not 36.
- Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
- Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi. To divide by 2 π, you can use parentheses or write degrees / 2 / pi.
I don't work very hard to remember the precedence of operators. If I can't tell by looking at the expression, I use parentheses to make it obvious.
For example, 2 + (3 * 4) is definitely easier to understand than 2 + 3 * 4 which requires knowledge of the operator precedences. As with everything else, the parentheses should be used reasonably (do not overdo it) and should not be redundant, as in (2 + (3 * 4)).
There is an additional advantage to using parentheses – it helps us to change the order of evaluation. For example, if you want addition to be evaluated before multiplication in an expression, then you can write something like (2 + 3) * 4.
Operators are usually associated from left to right. This means that operators with the same precedence are evaluated in a left to right manner. For example, 2 + 3 + 4 is evaluated as (2 + 3) + 4.
Example: Calculating on a Rectangle
Type and run the following program:
length = 5 breadth = 2 area = length * breadth print('Area is', area) print('Perimeter is', 2 * (length + breadth))
Output:
Area is 10 Perimeter is 14
How It Works
Here's how this program works.
Code | Output | Notes |
---|---|---|
length = 5 | none |
First, we assign the literal constant value 5 to the variable length using th Our website has a team of professional writers who can help you write any of your homework. They will write your papers from scratch. We also have a team of editors just to make sure all papers are of HIGH QUALITY & PLAGIARISM FREE. To make an Order you only need to click Ask A Question and we will direct you to our Order Page at WriteDemy. Then fill Our Order Form with all your assignment instructions. Select your deadline and pay for your paper. You will get it few hours before your set deadline. Fill in all the assignment paper details that are required in the order form with the standard information being the page count, deadline, academic level and type of paper. It is advisable to have this information at hand so that you can quickly fill in the necessary information needed in the form for the essay writer to be immediately assigned to your writing project. Make payment for the custom essay order to enable us to assign a suitable writer to your order. Payments are made through Paypal on a secured billing page. Finally, sit back and relax. About WridemyWe are a professional paper writing website. If you have searched a question and bumped into our website just know you are in the right place to get help in your coursework. We offer HIGH QUALITY & PLAGIARISM FREE Papers. How It WorksTo make an Order you only need to click on “Order Now” and we will direct you to our Order Page. Fill Our Order Form with all your assignment instructions. Select your deadline and pay for your paper. You will get it few hours before your set deadline. Are there Discounts?All new clients are eligible for 20% off in their first Order. Our payment method is safe and secure. Hire a tutor today CLICK HERE to make your first orderRelated TagsAcademic APA Writing College Course Discussion Management English Finance General Graduate History Information Justify Literature MLA |