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

Similar documents
Expressions in JavaScript. Jerry Cain CS 106AJ October 2, 2017

The float type and more on variables FEB 6 TH 2012

Guido van Rossum (1956 )

Python Programming Exercises 1

Programming Lecture 3

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

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

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

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

Introduction to Computers. Laboratory Manual. Experiment #3. Elementary Programming, II

Arithmetic. 2.2.l Basic Arithmetic Operations. 2.2 Arithmetic 37

Full file at

CSCE 120: Learning To Code

Hello, World and Variables

Built-in Types of Data

Functions and Libraries Once upon a time...

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

Downloaded from Chapter 2. Functions

VARIABLES & ASSIGNMENTS

Introduction to Computer Programming for Non-Majors

L-System Fractal Generator: Language Reference Manual

Outline. Data and Operations. Data Types. Integral Types

CSI31 Lecture 5. Topics: 3.1 Numeric Data Types 3.2 Using the Math Library 3.3 Accumulating Results: Factorial

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Operators and Expressions:

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

Introduction to Computer Programming for Non-Majors

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

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

Topic 2: Introduction to Programming

Arithmetic and IO. 25 August 2017

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

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

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

Subroutines I Computers and Programming

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

COMP Primitive and Class Types. Yi Hong May 14, 2015

Python Programming: An Introduction to Computer Science

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Introduction to Computer Programming for Non-Majors

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

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

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

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Introduction to Engineering gii

Python. Objects. Geog 271 Geographic Data Analysis Fall 2010

Introduction to Programming

Chapter 2 Working with Data Types and Operators

Primitive Data Types: Intro

Python Numbers. Learning Outcomes 9/19/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17

Introduction to Computer Science and Object-Oriented Programming

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

ENGR 101 Engineering Design Workshop

Programming for Engineers Introduction to C

9 Using Equation Networks

Chapter Two PROGRAMMING WITH NUMBERS AND STRINGS

C Programs: Simple Statements and Expressions

Variables, expressions and statements

Introduction to Programming

Arithmetic Operations

Chapter 2. Outline. Simple C++ Programs

Methods CSC 121 Fall 2014 Howard Rosenthal

CS 115 Lecture 4. More Python; testing software. Neil Moore

Algorithms and Programming I. Lecture#12 Spring 2015

9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?

Lecture 2: Python Arithmetic

Mat 2170 Week 6. Methods. Week 6. Mat 2170 Week 6. Jargon. Info Hiding. Math Lib. Lab 6. Exercises. Methods. Spring 2014

Full file at

Lecture 1. Types, Expressions, & Variables

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

write vs. writeln Prompting as Page Loads Today s Goals CSCI 2910 Client/Server-Side Programming Intermediate File vs. HTML Output

Introduction to Programming, Aug-Dec 2008

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

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

ADD Identifier-1 TO Identifier-2 Literal-1. ADD Identifier-1. GIVING Identifier-2 Literal-1

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Expressions and Casting

CS177 Python Programming. Recitation 2 - Computing with Numbers

XQ: An XML Query Language Language Reference Manual

IT 374 C# and Applications/ IT695 C# Data Structures

cast int( x float( x str( x hex( int string int oct( int string int bin( int string int chr( int int ord( ch

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

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

CPS122 Lecture: From Python to Java

CHAPTER 3: CORE PROGRAMMING ELEMENTS

DaMPL. Language Reference Manual. Henrique Grando

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

Introduction to Programming with RAPTOR

Numbers In, Numbers Out

Reserved Words and Identifiers

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

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

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

3.1. Chapter 3: The cin Object. Expressions and Interactivity

Here n is a variable name. The value of that variable is 176.

The C++ Language. Arizona State University 1

Operators Functions Order of Operations Mixed Mode Arithmetic VOID Data. Syntax and type conventions Using the Script window interface

Introduction to Programming

Transcription:

Eric Roberts Handout #3 CSCI 121 January 30, 2019 Expressions Grace Murray Hopper Expressions Eric Roberts CSCI 121 January 30, 2018 Grace Hopper was one of the pioneers of modern computing, working with Howard Aiken at Harvard on the Mark I. Hopper developed the COBOL programming language and its first compiler, which translated human-readable programs into machine code. To honor her many contributions, the Anita Borg Institute hosts the annual Grace Hopper Celebration of Women in Computing, with 20,000 women in attendance. Grace Murray Hopper (1906 1992) Data Types To a large extent, computers are used to process data that can take many forms. The diversity of possible data values gives rise to the notion of a data type, which defines the common characteristics of data values that have a particular form or purpose. In computer science, each data type is defined by a domain, which is the set of values that belong to that type, and a set of operations, which shows how the values in that domain can be manipulated. Python includes three data types for numbers: the data type int for integers or whole numbers, the data type float for floating-point numbers containing a decimal point, and the data type complex for complex numbers, which are beyond the scope of this course. Arithmetic Expressions Like most languages, Python specifies computation in the form of an arithmetic expression, which consists of terms joined together by operators. Each term in an arithmetic expression is one of the following: An explicit numeric value, such as 2 or 3.14159265 A variable name that serves as a placeholder for a value A function call that computes a value An expression enclosed in parentheses The operators include the conventional ones from arithmetic, along with a few that are somewhat less familiar: + Addition Subtraction * Multiplication / Division (exact) // Quotient (floor division) % Remainder ** Exponentiation Division and Remainder Python has three operators that involve division: The / operator computes the exact result of division, so that the expression 6 / 4 has the value 1.5. Applying the / operator always produces a floating-point value. The // operator implements floor division, which is the result of exact division rounded down to the next smaller integer. The expression 6 // 4 produces the value 1, and -6 // 4 produces the value 2. The % operator implements what mathematicians call the mod operator. The reader describes this operator in detail, but it is easiest to think of as computing the remainder, at least for positive values. For example, 6 % 4 produces the value 2. The % operator turns out to be useful in a surprising number of programming applications and is well worth a bit of study. Using the IDLE Interpreter The easiest way to get a sense of how arithmetic expressions work is to enter them into the IDLE interpreter: IDLE >>> 2 + 2 4 >>> 342-173 169 >>> 12345679 * 63 777777777 >>> 9 * 9 * 9 + 10 * 10 * 10 1729 >>>

2 Variables The simplest terms that appear in expressions are constant literals and variables. A variable is a placeholder for a value that can be updated as the program runs. A variable in Python is most easily envisioned as a box capable of storing a value answer Each variable has the following attributes: A name, which enables you to tell the variables apart. A value, which represents the current contents of the variable. 42 The name of a variable is fixed; the value changes whenever you assign a new value to the variable. Assignment Statements In Python, you create a variable simply by assigning it a value in an assignment statement, which has the general form: variable = expression The effect of an assignment statement is to compute the value of the expression on the right side of the equal sign and assign that value to the variable that appears on the left. Thus, the assignment statement total = total + value adds together the current values of the variables total and value and then stores that sum back in the variable total. When you assign a new value to a variable, the old value of that variable is lost. Naming Conventions In Python, names uses for variables, functions, and classes are called identifiers. Identifier names are composed of letters, digits, and underscores and cannot begin with a digit. Programmers use a variety of different conventions to mark word boundaries in an identifier: Snake case uses underscores, as in number_of_students. Camel case embeds uppercase, as in numberofstudents. CSCI 121 and its textbook use the following conventions: Variable and function names use camel case and begin with a lowercase letter. Constant names are written entirely in uppercase and use the underscore character, as in MAX_HEADROOM. Class names and function names designed to be run as programs use camel case and begin with an uppercase letter. Precedence If an expression contains more than one operator, Python uses precedence rules to determine the evaluation order. The arithmetic operators have the following relative precedence: ** unary - * / // % + - highest lowest Thus, Python evaluates the ** operator first, then the unary operator, then the operators *, /, //, and %, and finally the operators + and -. If two operators of the same precedence compete, Python evaluates them from left to right, except for the ** operator. Parentheses may be used to change the order of operations. Exercise: Precedence Evaluation What is the value of the expression at the bottom of the screen? Shorthand Assignments Assignment statements often adjust the existing value of a variable by modifying its current value, as in balance = balance + deposit Such statements are so common that Python allows you to shorten this expression to balance += deposit The general form of a shorthand assignment is variable op= expression 1 * 2 * 3 + ( 4 + 5) % 6 * ( 7 + 8) - 9 where op is any of Python s binary operators. The effect of this statement is the same as variable = variable op (expression)

3 Multiple Assignment Python supports multiple assignment, in which the left side of an assignment consists of a list of variables and the right side consists of a list of values, as in the statement x, y, z = 5, 12, 13 which sets x to 5, y to 12, and z to 13. All the values on the right side are computed before any assignments are performed. For example, the statement a, b = b, a exchanges the values of the variables a and b. Functions A function is a sequence of statements that has been collected together and given a name, which makes it possible to invoke the complete set of statements simply by supplying the name. A function typically takes information from its caller in the form of arguments, perform some computation involving the values of the arguments, and then returns a result to the caller, which continues from the point of the call. This notion that functions exist to manipulate information and return results makes functions in programming similar to functions in mathematics, which is the historical reason for the name. Functions in Mathematics The graph at the right shows the values of the function f (x) = x 2 5 Plugging in a value for x allows you to compute the value of f (x), as follows: f (0) = 0 2 5 = 5 f (1) = 1 2 5 = 4 f (2) = 2 2 5 = 1 f (3) = 3 2 5 = 4 The Python version of f (x) is def f(x): return x**2 5 Built-In Functions To make programming easier, all modern languages include collections of predefined functions. The built-in functions that operate on numeric data appear in the following table: abs(x) The absolute value of x max(x, y,...) The largest of the arguments min(x, y,...) The smallest of the arguments round(x) The value of x rounded to the nearest integer int(x) The value of x truncated to an integer float(x) The value of x converted to floating-point Importing Library Functions In addition to the built-in functions, Python offers a larger set of resources, which are organized into collections called libraries. Before you can use a library function, you must import that library in one of two ways. The most common strategy is to use an import statement to acquire access to that library s facilities without specifying any particular functions. For example, the statement import math indicates that your program will use resources from the math library. When you do, you must use the fully qualified name, which includes the library name, as in math.sqrt. You can also use the from-import statement to gain access to specific functions without having to include the library name. Useful Definitions in the math Library math.pi The mathematical constant π math.e The mathematical constant e math.sqrt(x) The square root of x math.floor(x) Rounds x down to the nearest integer math.ceil(x) Rounds x up to the nearest integer math.log(x) The natural logarithm of x math.log10(x) The common (base 10) logarithm of x math.exp(x) The inverse logarithm (e x ) math.sin(θ ) The sine of θ, measured in radians math.cos(θ ) The cosine of θ, measured in radians math.atan(x) The principal arctangent of x math.atan2(y, x) The arctangent of y / x math.degrees(θ ) Converts from radians to degrees math.radians(θ ) Converts from degrees to radians

4 Writing Your Own Functions The general form of a function definition is def name(parameter list): statements in the function body where name is the name of the function, and parameter list is a list of variables used to hold the values of each argument. You can return a value from a function by including a return statement, which is usually written as return expression where expression is an expression that specifies the value you want to return. Examples of Simple Functions The following function converts Fahrenheit temperatures to their Celsius equivalent: def ftoc(f): return 5 / 9 * (f 32) The following function computes the volume of a cylinder of radius r and height h. def cylindervolume(r, h): return math.pi * r**2 * h Nonnumeric Data The arithmetic expressions in the early sections of Chapter 1 enable you to perform numeric computation. Much of the excitement of modern computing, however, lies in the ability of computers to work with other types of data, such as characters, images, sounds, and video. As you will learn in Chapter 6, all of these data types are represented inside the machine as sequences of binary digits, or bits. When you are getting started with programming, it is more important to think about data in a more abstract way in which you focus on the conceptual values rather than the underlying representation. The String Type One of the most important data types in any programming language is the string type. The domain of the string type is all sequences of characters. In Python, you create a string simply by including that sequence of characters inside quotation marks, as in "Eric". The set of operations that can be applied to strings is large, but you don t need to know the entire set. In fact, for the first five chapters in the text, the only string operation you need to know is concatenation, as described on the next slide. You will learn about other operations in Chapter 6. All values including numbers, strings, graphical objects, and values of many other types can be assigned to variables, passed as arguments to functions, and returned as results. Concatenation One of the most useful operations available for strings is concatenation, which consists of combining two strings end to end with no intervening characters. Concatenation is built into Python using the + operator. For example, the expression "ABC" + "DEF" returns the string "ABCDEF". If you use + with numeric operands, it signifies addition. If the operands are strings, Python interprets + as concatenation. To concatenate strings and other types, you need to use the built-in function str to convert values to strings before joining them together, as in "Catch" + str(-22) "Catch-22" Built-In Functions for Strings Python includes the following built-in functions that operate on string values: len(s) The number of characters in s str(x) The value of x converted to a string int(s) The string s interpreted as an integer float(s) The string s interpreted as floating-point print(...) Prints the arguments separated by spaces input(prompt) Reads a string from the user

5 Running Command-Line Programs Although it is possible to import programs into IDLE and run them there, most Python programs are created as text files and then invoked from the command line. Python programs specify what happens when the program is run from the command line using the following lines at the end of the program file: if name == " main ": function() where function is the name of the function that runs the main program. Patterned lines of this sort are often called boilerplate. In general, it is more important to memorize boilerplate than to understand it. The AddTwoIntegers Program # File: AddTwoIntegers.py """ This program adds two integers entered by the user. """ def AddTwoIntegers(): print("this program adds two integers.") n1 = int(input("enter n1? ")) n2 = int(input("enter n2? ")) sum = n1 + n2 print("the sum is", sum) # Startup code if name == " main ": AddTwoIntegers()