Topic 2: Introduction to Programming

Similar documents
1/11/2010 Topic 2: Introduction to Programming 1 1

Expressions and Variables

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Exercise: Using Numbers

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

Variables, expressions and statements

Algorithms and Programming I. Lecture#12 Spring 2015

ENGR 101 Engineering Design Workshop

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Textbook. Topic 6: Functions. Motivation. What is a Function? What s a function? How can we use functions to write better software?

Introduction to TURING

>>> * *(25**0.16) *10*(25**0.16)

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

Hello, World and Variables

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Full file at

Arithmetic Expressions in C

Python Input, output and variables

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

CSC 120 Computer Science for the Sciences. Week 1 Lecture 2. UofT St. George January 11, 2016

C++ Programming: From Problem Analysis to Program Design, Third Edition

Visual C# Instructor s Manual Table of Contents

Objectives. In this chapter, you will:

Reserved Words and Identifiers

Starting with a great calculator... Variables. Comments. Topic 5: Introduction to Programming in Matlab CSSE, UWA

UNIT- 3 Introduction to C++

Text Input and Conditionals

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

Python for Analytics. Python Fundamentals RSI Chapters 1 and 2

Expressions. Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions. Grace Murray Hopper. Arithmetic Expressions.

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Introduction to Computer Science and Object-Oriented Programming

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

BASIC ELEMENTS OF A COMPUTER PROGRAM

Programming with Python

Typescript on LLVM Language Reference Manual

1/31/2017. Expressions are Used to Perform Calculations. ECE 120: Introduction to Computing. Five Arithmetic Operators on Numeric Types

Integer Representation. Variables. Real Representation. Integer Overflow/Underflow

BTE2313. Chapter 2: Introduction to C++ Programming

9/2/2016. Expressions are Used to Perform Calculations. ECE 120: Introduction to Computing. Five Arithmetic Operators on Numeric Types

Getting Started Values, Expressions, and Statements CS GMU

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Introduction to Python and Programming. 1. Python is Like a Calculator. You Type Expressions. Python Computes Their Values /2 2**3 3*4+5*6

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

Variables and data types

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Welcome to Python 3. Some history

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Getting Started with Python

Chapter 7 Arithmetic

Introduction to Python and programming. Ruth Anderson UW CSE 160 Winter 2017

Monty Python and the Holy Grail (1975) BBM 101. Introduction to Programming I. Lecture #03 Introduction to Python and Programming, Control Flow

CSI32 Object-Oriented Programming

Python Day 3 11/28/16

Chapter 2 Getting Started with Python

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Lecture 3. Input, Output and Data Types

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Variable and Data Type I

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

Chapter 2 Basic Elements of C++

Topic 7: Lists, Dictionaries and Strings

printf( Please enter another number: ); scanf( %d, &num2);

SSEA Computer Science: Track A. Dr. Cynthia Lee Lecturer in Computer Science Stanford

CS112 Lecture: Working with Numbers

1 Lexical Considerations

Computer Components. Software{ User Programs. Operating System. Hardware

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Chapter Two PROGRAMMING WITH NUMBERS AND STRINGS

Language Reference Manual simplicity

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

Introduction to Python

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

The C++ Language. Arizona State University 1

Fundamentals of Programming (Python) Getting Started with Programming

CHAPTER 3 BASIC INSTRUCTION OF C++

PROGRAMMING FUNDAMENTALS

Transcription:

Topic 2: Introduction to Programming 1

Textbook Strongly Recommended Exercises The Python Workbook: 12, 13, 23, and 28 Recommended Exercises The Python Workbook: 5, 7, 15, 21, 22 and 31 Recommended Reading Starting Out with Python (2 nd, 3 rd, or 4 th Edition) Section 1.5 Chapter 2 2

Computer Programming Gain necessary knowledge of the problem domain Analyze the problem, breaking it into pieces Repeat as necessary Synthesize a solution Run the program Validate program results Correct problems that are identified 3

Programming Languages Many programming languages available Offer different features Each has its own strengths and weaknesses Common features Allow us to control the behaviour of a computer Defined syntactic and semantic rules 4

Human Languages Levels of Abstraction High Level Programming Languages Low Level Programming Languages Machine Language 5

Python A high-level general purpose programming language Reasonably simple, easy to learn Reasonably easy to find and fix program errors Available for many platforms Powerful enough to solve interesting problems Used in industry 6

Programming Computer programs are stored in source files Human readable / editable Can also be understood by a computer typically have the extension.py Once the file is created, it is run using the python interpreter python myfile.py 7

A First Python Program Write a Python program that converts a pressure from kilopascals into atmospheres pounds per square inch millimetres of mercury 8

A First Python Program What steps can we follow to reach this goal? 9

Variable A named location in memory Holds a value The programmer can Variables read the value of a variable without changing / destroying the value change the value of the variable change the type of information stored in the variable 10

Variable names Variable Names should be meaningful must begin with a letter or an underscore may contain a mixture of letters, numbers and underscores must not be a reserved word shouldn t be a name already commonly used for another purpose shouldn t be in all caps 11

Assignment A variable is created and given a value using an assignment statement The variable that gets a value appears to the left of the assignment operator An arbitrarily complex expression appears to the right of the assignment operator Expression may include other variables 12

Getting Input Python includes a library of functions that perform useful tasks Our program can use these functions A function is called by using its name The function name is always followed by round brackets May include values inside the brackets that are used by the function Function result can be stored in a variable 13

Getting Input The input() function reads characters typed by the user as text It normally appears on the right side of an assignment statement name = input() If we want to treat the characters read by the user as a number, we must perform a conversion num = float(input()) 14

Use a print statement Generating Output It s another function Can print numbers, text, variables, Multiple items can be printed Separate each item with a comma 15

In a file named pressure.py: The Code 16

Running the Program CPU can only execute machine language instructions Can t execute programming language statements directly Options: Compile the program into machine language instructions Use a Virtual Machine that reads your program and performs the tasks required to run it 17

Comments Provide information to someone reading your code Completely ignored by the computer Should explain how or why Should add value A comment that says something that is immediately obvious from reading the code is not particularly useful 18

Magic Numbers Magic Number: An unnamed and/or poorly documented numeric constant without obvious meaning Should be avoided Program is difficult to understand Errors are difficult to detect If the value changes, it may need to be changed in many places 19

What Does this Program Do? x = float(input()) y = 32.0 + x * 9.0/5.0 print(y) What s wrong with this program? 20

Expressions Python supports arbitrarily complex mathematical expressions Integers / Floating Point Numbers / Parentheses Operators +: addition -: subtraction *: multiplication /: division //: integer division %: remainder **: exponentiation 21

Precedence The order of evaluation is determined by operator precedence () -x, x ** y x * y, x / y, x % y, x // y x + y, x - y = Evaluation is left to right at each level 22

Example 23

Math Functions Many additional math functions are available Located in the math library Import the math library Precede the name of the function with math. Examples: math.sqrt(x) math.floor(x) math.ceil(x) math.cos(x) 24

Three categories of errors: Syntax Errors Runtime Errors Logic Errors Types of Errors 25

Syntax Errors Identified as code is loaded No statements are executed Create Source File somefile.py python somefile.py Error 26

Runtime Errors Identified as the program runs Program does not complete successfully Create Source File somefile.py python somefile.py Error partial output 27

Logic Errors Program runs to completion, but generates incorrect results Create Source File somefile.py python somefile.py program output 28

Variables hold values Each value has a type Integer Float Boolean String Data Types 29

Data Types Some operations are only well defined for certain types 1 + 2 = Hello + World = 1 + Hello = 2 + 4 = 1 / 3 = 2.0 / 4 = 30

Type Conversions Python permits you to convert from one type to another "1.0" / "3.0" = float("1.0") / float("3.0") = float("asdf") = Other type conversions: int, bool, str 31

Example Consider getting a loan for a sports car Want to compare payments for different Amount borrowed Interest rate (percentage per year) Amortization period Write a program that reads the amount borrowed, interest rate and amortization period Displays monthly payment and total borrowing cost 32

Example Useful Equation: P = i A / (1 (1 + i) -N ) P: Payment amount i: Interest rate per payment period as a decimal value 5% should be 0.05, but the user will enter 5 A: Amount borrowed N: Total number of payments 33

Example 34

Formatting Output Sometimes print doesn t display things the way we would like print(1 / 3.0) gives 0.333333333333 What if we want 0.33? What if we want to center the result on the line? What if we want to right-justify the result? 35

Formatting Numbers The % operator can be used to format numbers Format specifier to its left A string that controls how the value will be formatted Expression that evaluates to a number on its right Example: %.2f % 3.14159265 36

A string Format Specifiers Format starts with a % Number(s) and optional decimal point control formatting Letter indicates type f to format floating point numbers d to format an integer in decimal format x to format an integer in hexadecimal format 37

Programming Wrapping Up Process of converting an algorithm to a form that can be executed by a computer A program Uses variables to hold values Evaluates expressions Calls functions to get input, perform mathematical operations Calls the print function to generate output 38

Where Are We Going What kinds of data can a computer manipulate? How does the computer represent data? Programs we can write are limited What if we want different behaviour depending on a value entered by the user? What if we want to perform a task several times? 39