computer science 101 introduction to programming

35
Computer Science Computer Science 101 101 Introduction to Introduction to Programming Programming

Upload: roxanne-wilkinson

Post on 24-Dec-2015

256 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Computer Science 101 Introduction to Programming

Computer Science Computer Science 101101

Introduction to ProgrammingIntroduction to Programming

Page 2: Computer Science 101 Introduction to Programming

What Is a Program?What Is a Program?

Usually, one or more algorithms Usually, one or more algorithms written in a programming language written in a programming language that can be translated to run on a that can be translated to run on a real machinereal machine

We sometimes call programs We sometimes call programs softwaresoftware

Page 3: Computer Science 101 Introduction to Programming

What Is a Programming What Is a Programming Language?Language?

A programming language is somewhat like a A programming language is somewhat like a natural language, but with a very limited set of natural language, but with a very limited set of statements and strict syntax rules.statements and strict syntax rules.

Has statements to implement sequential, Has statements to implement sequential, conditional and iterative processing - algorithmsconditional and iterative processing - algorithms

Examples: FORTRAN, COBOL, Lisp, Basic, Examples: FORTRAN, COBOL, Lisp, Basic, Pascal, C, CPascal, C, C++++, Java, C#, Python, …, Java, C#, Python, …

Page 4: Computer Science 101 Introduction to Programming

CompilerCompiler

A A compilercompiler is a program that is a program that converts a program written in a converts a program written in a programming language into a programming language into a program in the native language, program in the native language, called called machine languagemachine language, of the , of the machine that is to execute the machine that is to execute the program.program.

Page 5: Computer Science 101 Introduction to Programming

From Algorithms to HardwareFrom Algorithms to Hardware(with compiler)(with compiler)

Algorithm

Program

A real computer

Translate (by a human being)

Translate (by compiler program)

Page 6: Computer Science 101 Introduction to Programming

The Program Development The Program Development Process (Data Flow)Process (Data Flow)

Editor

Compiler

A real computer

Algorithm

Program in programming language

Program in machine’s language

Input Output

Page 7: Computer Science 101 Introduction to Programming

The Program Development The Program Development Process (Control Flow)Process (Control Flow)

Edit

Compile

Run

Syntax errors

Input Output

Runtime errors

Page 8: Computer Science 101 Introduction to Programming

Three kinds of errorsThree kinds of errors

Syntax error Syntax error : Some statement in the : Some statement in the program is not a legal statement in the program is not a legal statement in the language.language.

Runtime errorRuntime error : An error occurs while the : An error occurs while the program is executing, causing the program is executing, causing the program to terminate (divide by zero, program to terminate (divide by zero, etc.)etc.)

Logic error Logic error : The program executes to : The program executes to completion, but gives incorrect results.completion, but gives incorrect results.

Page 9: Computer Science 101 Introduction to Programming

InterpreterInterpreter

An alternative to a compiler is a An alternative to a compiler is a program called an program called an interpreterinterpreter. Rather . Rather than convert our program to the than convert our program to the language of the computer, the language of the computer, the interpreter takes our program one interpreter takes our program one statement at a time and executes a statement at a time and executes a corresponding set of machine corresponding set of machine instructions.instructions.

Page 10: Computer Science 101 Introduction to Programming

InterpreterInterpreter

Edit

InterpreterSyntax or runtime errors

Input

Output

Page 11: Computer Science 101 Introduction to Programming

PythonPython Python is a real-world, production language that is Python is a real-world, production language that is

freely available for most computers. freely available for most computers.

http:www.python.org If you want a copy of Python to use with this course, go If you want a copy of Python to use with this course, go

to to

http://code.google.com/p/mediacomp-jes/ . .

We are using JES (Jython Environment for Students) We are using JES (Jython Environment for Students) which has a lot of special multimedia functionality.which has a lot of special multimedia functionality.

Note: Our textbook covers a limited amount of Python. Note: Our textbook covers a limited amount of Python. There are many excellent online tutorials. For example, There are many excellent online tutorials. For example, see see

http://en.wikibooks.org/wiki/Non-Programmer's_Tutorial_for_Python/Contents

Page 12: Computer Science 101 Introduction to Programming

PythonPython

Python uses an interpreter. Not only can we write Python uses an interpreter. Not only can we write complete programs, we can work with the interpreter complete programs, we can work with the interpreter in a statement by statement mode enabling us to in a statement by statement mode enabling us to experiment quite easily.experiment quite easily.

Python is especially good for our purposes in that it Python is especially good for our purposes in that it does not have a lot of “overhead” before getting does not have a lot of “overhead” before getting started.started.

It is easy to jump in and experiment with Python in an It is easy to jump in and experiment with Python in an interactive fashion.interactive fashion.

Page 13: Computer Science 101 Introduction to Programming

Language terminologyLanguage terminology

Syntax:Syntax: The formal rules for legal The formal rules for legal statements in the language.statements in the language.

Semantics:Semantics: The meaning of the The meaning of the statements - what happens when the statements - what happens when the statement is executed.statement is executed.

Page 14: Computer Science 101 Introduction to Programming

Three major control Three major control constructs constructs

of programmingof programming(Execution flow of instructions)(Execution flow of instructions)

Sequential:Sequential: Simply do steps one after Simply do steps one after the other in order they are listed.the other in order they are listed.

Conditional:Conditional: Decide which statement Decide which statement to do next based on some true/false to do next based on some true/false test.test.

Iterative:Iterative: A set of statements is A set of statements is repeated over and over until some repeated over and over until some condition is met.condition is met.

Page 15: Computer Science 101 Introduction to Programming

Sequential OperationsSequential Operations“Atomic”“Atomic”

InputInput ComputationComputation OutputOutput

Page 16: Computer Science 101 Introduction to Programming

The Big PlanThe Big Plan

We want to get some experience of programming We want to get some experience of programming simple algorithms in a real programming language. simple algorithms in a real programming language. This gives us an understanding of how software is This gives us an understanding of how software is written and allows us to test our algorithms to see if written and allows us to test our algorithms to see if they work.they work.

We’ll first work with programs where the variables We’ll first work with programs where the variables have numbers as values.have numbers as values.

Later we’ll work with programs dealing with Later we’ll work with programs dealing with pictures and sound.pictures and sound.

In lab we’ll work with some simple statements and In lab we’ll work with some simple statements and small programs.small programs.

Page 17: Computer Science 101 Introduction to Programming

The Basic PatternThe Basic Pattern

Most of our programs will use the Most of our programs will use the basic pattern ofbasic pattern of

• Get some user inputGet some user input

• Perform some algorithm on the inputPerform some algorithm on the input

• Provide results as outputProvide results as output

Page 18: Computer Science 101 Introduction to Programming

IdentifiersIdentifiers

IdentifiersIdentifiers are names of various program are names of various program elements in the code that uniquely identify elements in the code that uniquely identify the elements. They are the names of the elements. They are the names of things like variables or functions to be things like variables or functions to be performed. They're specified by the performed. They're specified by the programmer and should have names that programmer and should have names that indicate their purpose.indicate their purpose.

In Python, identifiers In Python, identifiers • Are made of letters, digits and underscoresAre made of letters, digits and underscores• Must begin with a letter or an underscoreMust begin with a letter or an underscore• Examples: temperature, myPayrate, score2Examples: temperature, myPayrate, score2

Page 19: Computer Science 101 Introduction to Programming

KeywordsKeywords

KeywordsKeywords are reserved words that are reserved words that have special meaning in the Python have special meaning in the Python language. Because they are language. Because they are reserved, they can not be used as reserved, they can not be used as identifiers. Examples of keywords are identifiers. Examples of keywords are ifif, , whilewhile, , classclass, , importimport. .

Page 20: Computer Science 101 Introduction to Programming

Variables in PythonVariables in Python

A variable hasA variable has

• A name – identifierA name – identifier

• A data type - int, float, str, etc.A data type - int, float, str, etc.

• Storage space sufficient for the type.Storage space sufficient for the type.

Page 21: Computer Science 101 Introduction to Programming

Numeric Data TypesNumeric Data Types

intintThis type is for whole numbers, This type is for whole numbers,

positive or negative. Examples: 23, -positive or negative. Examples: 23, -17561756

floatfloatThis type is for numbers with This type is for numbers with

possible fraction parts. Examples: possible fraction parts. Examples: 23.0, -14.56123.0, -14.561

Page 22: Computer Science 101 Introduction to Programming

Integer operatorsInteger operators The operations for integers are:The operations for integers are:

+ + for additionfor addition - - for subtractionfor subtraction * * for multiplicationfor multiplication / / for integer division: The result of for integer division: The result of

14/5 is 214/5 is 2 % % for remainder: The result of 14 % 5 is 4for remainder: The result of 14 % 5 is 4

*, /, % take precedence over +, -*, /, % take precedence over +, - x + y * z will do y*z firstx + y * z will do y*z first

Use parentheses to dictate order you want.Use parentheses to dictate order you want. (x+y) * z will do x+y first.(x+y) * z will do x+y first.

Page 23: Computer Science 101 Introduction to Programming

Integer ExpressionsInteger Expressions

Integer expressions are formed usingInteger expressions are formed using

• Integer ConstantsInteger Constants

• Integer VariablesInteger Variables

• Integer OperatorsInteger Operators

• ParenthesesParentheses

Page 24: Computer Science 101 Introduction to Programming

Python Assignment Python Assignment StatementsStatements

In Python, = is called the In Python, = is called the assignment assignment operatoroperator and an and an assignment statementassignment statement has has the formthe form

<variable> = <expression> <variable> = <expression>

HereHere• <variable> would be replaced by an actual <variable> would be replaced by an actual

variablevariable• <expression> would be replaced by an <expression> would be replaced by an

expressionexpression

Python:Python: age = 19 age = 19

Page 25: Computer Science 101 Introduction to Programming

Python Assignment StatementPython Assignment Statement

Syntax:Syntax: <variable> = <expression> <variable> = <expression>• Note that variable is on leftNote that variable is on left

Semantics:Semantics:

Compute value of expressionCompute value of expression

Store this as new value of the variableStore this as new value of the variable

Example:Example: Pay = PayRate * Hours Pay = PayRate * Hours

Payrate

10

Hours

40

Pay

400

Page 26: Computer Science 101 Introduction to Programming

Assignment ExampleAssignment Example

BeforeX

3

Z

12

Y

5

AfterX

3

Z

11

Y

5

ExecuteZ = X * 3 + Z / Y

Page 27: Computer Science 101 Introduction to Programming

Python SessionPython Session

Page 28: Computer Science 101 Introduction to Programming

Python SessionPython Session

Page 29: Computer Science 101 Introduction to Programming

What about floats?What about floats?

When computing with floats, / will When computing with floats, / will indicate regular division with indicate regular division with fractional results.fractional results.

Constants will have a decimal Constants will have a decimal point.point.

14.0/5.0 will give 2.8 while 14/5 14.0/5.0 will give 2.8 while 14/5 gives 2.gives 2.

Page 30: Computer Science 101 Introduction to Programming

CommentsComments

Often we want to put some Often we want to put some documentation in our program. documentation in our program. These are comments for explanation, These are comments for explanation, but not executed by the computer.but not executed by the computer.

If we have # anywhere on a line, If we have # anywhere on a line, everything following this on the line everything following this on the line is a comment – ignoredis a comment – ignored

Page 31: Computer Science 101 Introduction to Programming

Numerical InputNumerical Input To get numerical input from the user, we use an To get numerical input from the user, we use an

assignment statement of the formassignment statement of the form

<variable> = input(<prompt>)<variable> = input(<prompt>)

HereHere• <prompt> would be replaced by a prompt for the user <prompt> would be replaced by a prompt for the user

inside quotation marksinside quotation marks• If there is no prompt, the parentheses are still neededIf there is no prompt, the parentheses are still needed

SemanticsSemantics• The prompt will be displayedThe prompt will be displayed• User enters numberUser enters number• Value entered is stored as the value of the variableValue entered is stored as the value of the variable

Page 32: Computer Science 101 Introduction to Programming

Print StatementPrint Statement

For output we use statements of the formFor output we use statements of the form

print <expression>print <expression>

SemanticsSemantics• Value of expression is computedValue of expression is computed• This value is displayedThis value is displayed

Several expressions can be printed – Several expressions can be printed – separate them by commasseparate them by commas

Page 33: Computer Science 101 Introduction to Programming

Example - Fahrenheit to Example - Fahrenheit to CentigradeCentigrade

We want to convert a Fahrenheit We want to convert a Fahrenheit temperature to Centigrade.temperature to Centigrade.

The formula is C = (F -32) x 5/9The formula is C = (F -32) x 5/9

We use type float for the We use type float for the temperatures.temperatures.

Page 34: Computer Science 101 Introduction to Programming

Python SessionPython Session

Page 35: Computer Science 101 Introduction to Programming