Posted: February 26th, 2023

Scripting

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 x

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

About this Book

<h

2

>

Expressio

n

s

,

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

2

n

7

42

In this example, n has the value

and n + 25 has the value 42 because 17 + 25 = 42.

Result Notes
4 42 1
n + 25 17

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

+ 2.5
4.

3 + 5 8

Notice that the result is an integer.

1.5 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 2

6

* (multiply)

The multiply operator gives the multiplication of the two numbers or returns the string repeated that many times.

Expression
Result

6

2 * 3
‘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

2.0

13 / 3 4.333333333333333

Note that this returns a float

4 / 2

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

4

2

Note that this returns an integer

0

Note that this returns an integer

Note that this returns an integer

13 // 3

Note that this returns an integer

4 // 2
0 // 5
-13 // 5 -3

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:

none

Code Output
minutes = 105 none
minutes = minutes / 60
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

none

1

hours = minutes // 60
print(hours)

To get the remainder, you could subtract off one hour in minutes:

Code
Output

none

remainder = minutes – hours * 60
print(remainder) 45

% (modulo)

The modulus operator % divides two numbers and returns the remainder.

Expression
Result
Notes

1

Note that this returns an integer

1.5

Note that this returns a float

13 % 3
-25.5 % 2.25

We can use the modulus operator % on our movie running time example.

Code
Output

none

print(remainder)
45

remainder = minutes % 60

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

breadth = 2
none

area = length * breadth
none

print(‘Area is’, area)
Area is 10

print(‘Perimeter is’, 2 * (length + breadth))
Perimeter is 14

First, we assign the literal constant value 5 to the variable length using the assignment operator (=).

Next, we assign the literal constant value 2 to the variable breadth using the assignment operator (=).

We use these to calculate the area and perimeter of the rectangle with the help of expressions. We store the result of the expression length * breadth in the variable area

Next, we print the value of area using the print statement.

Finally, we directly use the value of the expression 2 * (length + breadth) in the print function to display the perimeter of the rectangle.

Notice how Python pretty-prints the output. Even though we have not specified a space between ‘Area is’ and the variable area, Python puts it for us so that we get a clean nice output and the program is much more readable this way (since we don’t need to worry about spacing in the strings we use for output). This is an example of how Python makes life easy for the programmer.

Getting Input from the Keyboard

There will be situations where your program has to interact with the user. For example, you would want to take information from the user and then display some results back. We can achieve this using the input() function and print function respectively.

The built-in function, input, stops the program and waits for the user to type something. When the user presses Return or Enter, the program resumes and input returns what the user typed as a string.

Look at the following example:

my_name = input(‘

What is your name?

‘)

print(my_name)

When we execute this code, the interpreter will prompt us for our name and allow us to enter whatever we like.

Code
Output
Notes

my_name = input(‘What is your name?’)
What is your name?

–  to the variable my_name and continues.

Heather

When this code is executed, the program displays the input statement’s prompt string, in this case What is your name? and waits for the user to provide some input. The program pauses until the Enter or Return key is pressed. Then the program assigns the input received from the user – in this case the string

Heather
print(‘Hi,’, my_name)

Now that the program has received input from the user, we display the string Hi, followed by the value of my_name – Heather – using the print statement.

Notice that the input received from the user – in this case the string Heather – is right up against the prompt What is your name? This is rather ugly. You can make it look nice by either adding a space at the end of the prompt:

Or you can cause the input to be entered on a new line by using a special sequence \n. As you should recall, the sequence \n at the end of the prompt represents a newline and causes a line break.

Converting Input to Integers and Floats

Also notice that everything which is entered by the user has a type of string. Even numbers. If you need to use the user’s input to perform a mathematical calculation, you will need to convert the string to either an integer or to a float before you perform the calculation. To do this, you use the statements int() and float().

Code
Output
Notes

none

none

my_age = input(‘What is your age?’)
my_age = int(my_age)

Get the user’s age. It is automatically a string, even if the user types a number.

Convert the the my_age variable to an integer using int().

Now you can perform mathematical calculations on the number.

cost = input(‘Enter the cost’)
cost = float(cost)

Get the cost of an item. It is automatically a string, even if the user types a number.

Convert the the cost variable to a float using float().

Now you can perform mathematical calculations on the number.

However if the user types something other than a valid number, you will get an error if you use int() or float().

>>> age = input(‘How old are you?’)
How old are you?
too old
>>> int(age)
ValueError: invalid literal for int() with base 10

We will see how to handle this kind of error later. But this is something to keep in mind – users will unintentionally mess up your programs and it is important to plan for it.

Converting Integers and Floats to Strings

There may come a time when you need to convert an integer or float to a string. To do this, you use the str() statement:.

Code
Output
Notes

none

my_age = 20
my_age = str(my_age)
print(type(my_age))

Assign the integer 20 to the variable my_age.

Convert the the my_age variable to a string using str().

cost = 19.25
cost = str(cost)
print(type(cost))

Assign the float 19.25 to the variable cost.

Convert the the cost variable to a string using str().

Debugging, Part 2

Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. It is useful to distinguish between them in order to track them down more quickly.

Syntax error:

“Syntax” refers to the structure of a program and the rules about that structure. For example, parentheses have to come in matching pairs, so (1 + 2) is legal, but 8) is a syntax error.

If there is a syntax error anywhere in your program, Python displays an error message and quits, and you will not be able to run the program. During the first few weeks of your programming career, you might spend a lot of time tracking down syntax errors. As you gain experience, you will make fewer errors and find them faster.

Runtime error:

The second type of error is a runtime error, so called because the error does not appear until after the program has started running. These errors are also called exceptions because they usually indicate that something exceptional (and bad) has happened.

In the previous section, you saw that a ValueError was thrown when we tried to convert the string old to an integer. This is an example of a runtime error.

Semantic error:

The third type of error is “semantic”, which means related to meaning. If there is a semantic error in your program, it will run without generating error messages, but it will not do the right thing. It will do something else. Specifically, it will do what you told it to do.

Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing.

About this Book

Scripting :
This week’s Lab is:

1. We are baking brownies!  We have a recipe which calls for the following ingredients:

. 0.5 cups butter

. 2 eggs

. 1 teaspoon vanilla

. 1 cup sugar

. 0.5 cups flour

. 0.5 cups cocoa powder

. 0.25 teaspoons baking powder

. 0.25 teaspoons salt

The ingredients in this recipe will make 9 brownies. Write a program which asks the user how many brownies they wish to bake, then displays the adjusted recipe with the correct amounts for making that number of brownies. Don’t worry about converting teaspoons to cups (etc) – just display the amounts in their original measurements.

You are to:

1. Work through this Lab 
on your own (no peer help on this one!)

2. Submit your own completed Lab file(s) here (click the link above)

3. Leverage as many tools, functions and methods as covered in this lessons reading!

Expert paper writers are just a few clicks away

Place an order in 3 easy steps. Takes less than 5 mins.

Calculate the price of your order

You will get a personal manager and a discount.
We'll send you the first draft for approval by at
Total price:
$0.00