Week9ProgrammingPart1-PythonIntroFall2018.pdf

PROGRAMMING Part 1: Introduction to Python using JES Environment

PROGRAMMING: PART 1

• What is a computer program?

A self-contained set of instruction used to operate a computer to produce a

specific result: AKA software.

PROGRAMMING: PART 1

• Software Development Procedure:

• 3 Steps:

• Design and Development

• Documentation

• Maintenance

Design and

Develop Document Maintenance

PROGRAMMING: PART 1 • Design and Development

• Starts with Program Requirement

• Step 1: Analyze the Problem (10%)

• Determine Input

• Determine Output

• Step 2: Develop a Solution (20%)

• Develop the processing that is necessary

• Develop the set of steps required to take input to output; develop the algorithm.

• Step 3: Write the Program (Code the Solution) (20%)

• Write the solution from Step 2 in a programming language.

• Step 4: Test and Correct the Program (50%)

• Running the program with all possible conditions of execution

• Finding an error, or bug, then you must correct the bug.

PROGRAMMING PART 1

Design and Development

Discover a

programming need

Analyze the

problem

(Determine input

and output)

Write the code (Use

a specific

language)

Test and Correct

the Program

(Debug)

Start

End

Develop a

solutions (input,

process, output

steps)

A

A

PROGRAMMING: PART 1

• Algorithm: Step-by-step sequence of instructions that must terminate

• Describes how data (input) is to be processed to produce the desired result (output)

• Programming starts when you develop an algorithm

• Program request: Example: Find the sum of the numbers from 1 to 100

• Ask: Is more than one Algorithm needed?

• What is the first input?

• Is there a first and second output?

• Is a Second and Third Algorithm (Set of steps) needed?

• Produce the pseudocode: English-like description of the steps

• Refine the steps into smaller and smaller steps

• Develop a Flowchart

PROGRAMMING: PART 1

• 1st – Flowchart, then

• Translate pseudocode into an actual programming language.

• Different languages are designed to work better for certain problems. Choose your language carefully.

• Sometimes you do not have a choice and must adapt the limitation of the language to your needs.

PROGRAMMING: PART 1

• High Level Languages

• Resembles written languages

• Example: Results = firstNumber + secondNum

• Example of High Level Languages: C/C++, Java, Visual Basic, etc.

• 2 Methods of preparing for execution:

• Interpreted: Each program statement is translated just prior to execution by an interpreter.

• Compiled: Complete program is translated into machine language by a compiler.

PROGRAMMING: PART 1

• C++ is a hybrid procedural and object-oriented language;

• C was procedural, the “++” adds object-orientation

• Focus on the procedural aspects first • Procedure = how to do something;

• Procedural programs use 4 basic constructs: • Sequence of statements

• Selection (decision or branching): must be a true/false (yes/no) answer

• Repetition (looping)

• Subprogram

• Examples procedural language? • COBOL, Fortran, C

PROGRAMMING: PART 1

• Python • Easy to learn • Powerful • Programming Language • Has efficient high-level data structure and a simple but effective approach to

object-oriented programming. • Can be freely obtained from: https://www.python.org/ • The Python interpreter is easily extended with new functions and data types

implemented in C or C++ (or other languages callable from C). • Well suited for GUI application and simple games. • You can download if for free. • IDLE is part of the download.

https://docs.python.org/3/tutorial/

LOG ONTO A COMPUTER

PROGRAMMING PART 1

• The lab computers have Python with IDLE.

• Open IDLE On your computer. (In the search box, type IDLE)

PROGRAMMING: PART 1

IDLE has two main window types:

The Shell Window (<C> means to use the Control Key) Can view Last Restart (by Scrolling)

Can restart the Shell

Can Interrupt execution

<C> –c interrupts executing command

<C> – d Sends end-of-file; closes window if typed at a >>> prompt

<Alt> -/ (Expand Word) is also useful to reduce typing

Command History

<Alt> –p Retrieves previous command matching what you have typed. On OSX use C –p

<Alt> –n Retrieves next. On OS X use C –n

Return - while on any previous command retrieves that command.

IDLE information: https://docs.python.org/2/library/idle.html

PROGRAMMING: PART 1

The second window type:

The Editor Window

Can:

1. Open or wake up the Python Shell Window.

2. Check the syntax of the module currently open in the Editor Window.

3. IDLE will prompt you to save if the program has not been saved.

4. IF there is a syntax error, the approximate location is indicated in the Editor window.

5. Has the “Run Module”

Will do the Check Module.

If no error, restart the shell to clean the environment, then execute the module.

Output is displayed in the SHELL Window (NOT the Editor Window. You need to use the

commands print or write to see results) You can then view the results of your execution.

PROGRAMMING: PART 1

• In the shell window type the following floating points:

• 188.0/73.0

• Press <Enter>

• In the shell window type the following integers:

• 73+188

• press <Enter>

• In the shell window type the following integers:

• 188/73

• Press <Enter>

**You are in the Shell Window ----- This is In an Execution Mode

PROGRAMMING: PART 1

• Notice that Python determines the type of number integer versus real number (floating point) by context

• If you use an integer, Python will provide you with an integer.

• If you divide using “/”, the result will be a floating point.

• If you use a decimal value, Python will provide a decimal value (floating point).

PROGRAMMING: PART 1

• In the Shell Window type:

• X=73

• Press <Enter>

• In the Shell Window type:

• Y=188

• Press <Enter>

• In the Shell Window type:

• X+Y • Press <Enter>

The “=“ assigns a value to a variable.

PROGRAMMING: PART 1 • Now you will write the instructions as a program in the Editor Window (Has

“Run” module.”

• Start programming by using the def command to create a new function called “JustToAdd”.

Note: Python is based on indentions! After the def

command, the next three lines MUST be indented

(just use the tab key), or an error will result!

Load the program (it will ask you to save it, save it with

the extension “.py”, for example “prog1.py”). To Load:

Go to File then Load Program.

Once loaded (See command area), execute the

function we created, type JustToAdd() in the command

area. What is displayed?

Print function will cause the result to be printed on the

screen.

def JustToAdd():

x=73

y=188

print(x+y)

JustToAdd()

PROGRAMMING: PART 1

You can also call the function within the program itself. This should be done to “run” the program.

Try it!

This is done in the

Editor Window (Has

run module)

def JustToAdd():

x=73

y=188

print(x+y)

JustToAdd()

PROGRAMMING: PART 1

Program file name rules: It is very useful to stick to some rules regarding the file names of Python programs.

Otherwise some things might go wrong unexpectedly. These don't matter as much for programs,

but you can have weird problems if you don't follow them for module names.

1. Always save the program with the extension *.py. Do not put another dot anywhere else in

the file name.

2. Only use standard characters for file names: letters, numbers, dash (-) and underscore (_).

3. White space (" ") should not be used at all (use underscores instead).

4. Do not use anything other than a letter (particularly no numbers!) at the beginning of a file

name.

5. Do not use "non-English" characters (such as å, ɓ, ç, ð, é, õ, ü) in your file names—or,

even better, do not use them at all when programming.

https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/Intro#Creating_and_Running_Programs

NEW PROGRAM: TEMPERATURE CONVERSION

Start

Fahrenheit (f) =

73.0

Celsius = (f-

32)*5/9

Print Celsius

value on

screen

End

**Problem: Convert 73 degrees Fahrenheit into Celsius

PROGRAMMING: PART 1

Now actually code the program. (Create a new program.) This program converts a temperature of 73 degrees Fahrenheit (F) to Celsius (C ).

Save it and execute it as you did in the previous problem.

Be careful with your syntax!

def FtoC():

F=73.0

C=(F-32)*5/9

print(c)

FtoC()

INPUT A VALUE

• To allow users of the program to input numerical values to the program, you must use a programming statement.

• In Python, you will use the command: input

• A statement can be added to the command so users know what to enter.

• Also, to print a sentence with your output, you must use the command print. This command also uses variables for the results.

NEW PROGRAM: TEMPERATURE CONVERSION

Start

Celsius = (f-

32)*5/9

Print Celsius

value on

screen

End

**Problem: Input a temperature in Fahrenheit and convert into Celsius

Input a

Fahrenheit

value

PROGRAMMING: PART 1 • Try this program solution:

Save and execute this.

*Note: The statement %.02f is a statement that formats the number in the display

(It has nothing to do with the variable F.)

PROGRAMMING: PART 1

Strings • Can be expressed in several ways.

• Single quotes

• Example: ‘spam and eggs’

• Double quotes

• Example: “spam and eggs”

• The output string is enclosed in quotes and special characters are escaped with backslashes (If you want a quote included in the string.)

• Example: ‘\”Why not?\”, he said’

PROGRAMMING: PART 1

• Draw a simple flowchart on a piece of paper, then

• Write a program to convert from Celsius to Fahrenheit

• Note:

The formula is: F=(C*9/5)+32

NEW PROGRAM: TEMPERATURE CONVERSION

Start

Fahrenheit

Formula

F=(C*9/5)+32

Print the

Fahrenheit

value on

screen

End

**Problem: Input a temperature in Fahrenheit and convert into Celsius

Input a

Celsius value

NOW, YOU CODE THE SOLUTION

• Code the solution. Use the previous program as an example.

• Run your program and ensure it works.

• Enter several different Celsius Values.

• Enter 0 and make sure the Fahrenheit value is 0

• Save the program with “______.py”

• Submit the “____________.py” program into Blackboard under Week 9 “Celsius Program”.

UFO EMERGENCY PROBLEM

• You have been contacted by a man who wants a UFO emergency program. He wants to be able to choose one item from a menu on the screen. Below is what he has in mind:

• He wants three choices, numbered from 1 to 3:

• If the UFO has landed in his yard, he wants the response to say, “Send wife to check it out”

• If the UFO has blown up his house, he wants the response to say, “Aliens hostel, go fishing to enjoy the last day of life”

• If the UFO has beamed him aboard, he wants the response to say, “Fein symptoms of infectious disease”.

• Last, if he tries to choose a number not on the menu, he wants the program to say, “Not a valid response”.

UFO EMERGENCY PROBLEM

Start

Input nature

of

emergency

2?

1?

3?

Output:

Send wife to

check it out

Module 1

Module 2

Module 3

Output: Aliens

hostel, go

fishing to

enjoy the last

day of life

Output: Fein

symptoms of

infectious

disease

End

Yes

Yes

Yes

No

No

No

PROGRAMMING: PART 1

Using “IF”, “ELSEIF” (elif) and “ELSE” statements in Python.

Try the this program:

Remove “\n” and test it.

What does the “\n” do?

How many times do you

have to run this program to

see each possible output?

Trying each branch of the

else-if conditional

execution would be

required to fully test the

program. **DO NOT create a second line for N=input(“What is the nature……). I had to

do that to fit the line on the PowerPoint!

PROGRAMMING: PART 1

• Assignment:

• Use what you learned from the in-class examples and create a new program.

• Create a temperature conversion program that asks users if they want to convert from C to F, or from F to C. (A menu is needed, like the UFO program.) To do this, your program will need to use the “C to F” and the “F to C” functions you created last week. (You can find them in the PowerPoint for Week 9.)

• Create a new function that asks for user input (Celsius or Fahrenheit) and executes the appropriate math function based on that input. This part should appear to be a menu choice. Then, be sure the user can enter a numerical value for Celsius or Fahrenheit as input. (Remember the UFO Emergency functions as examples!)

DO YOUR WEEK 9 HOMEWORK