Fundamentals: Expressions and Assignment

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

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

Lecture 1. Types, Expressions, & Variables

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

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

Variables, expressions and statements

CSci 1113, Fall 2015 Lab Exercise 4 (Week 5): Write Your Own Functions. User Defined Functions

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

L-System Fractal Generator: Language Reference Manual

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

6.1 Evaluate Roots and Rational Exponents

from scratch A primer for scientists working with Next-Generation- Sequencing data Chapter 1 Text output and manipulation

Solving Equations with Inverse Operations

ENGG1811 Computing for Engineers Week 1 Introduction to Programming and Python

Learning the Language - V

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

Lecture 3. Input, Output and Data Types

Chapter 17. Fundamental Concepts Expressed in JavaScript

GridLang: Grid Based Game Development Language Language Reference Manual. Programming Language and Translators - Spring 2017 Prof.

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

Python Programming Exercises 1

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

ENGR 101 Engineering Design Workshop

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

Episode 1 Using the Interpreter

BASIC ELEMENTS OF A COMPUTER PROGRAM

9. Elementary Algebraic and Transcendental Scalar Functions

CS 102 Lab 3 Fall 2012

CS 1110, LAB 1: EXPRESSIONS AND ASSIGNMENTS First Name: Last Name: NetID:

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

Built-in Types of Data

MIT AITI Python Software Development

Basic types and definitions. Chapter 3 of Thompson

9 Using Equation Networks

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

Lecture 2: Variables & Assignments

The Very Basics of the R Interpreter

CSE 115. Introduction to Computer Science I

Computational Programming with Python

Lexical Considerations

Transform data - Compute Variables

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

Getting started with Java

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

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

Mini-Lesson 1. Section 1.1: Order of Operations PEMDAS

SPARK-PL: Introduction

Topic 1: Introduction

Language Reference Manual

Section we will not cover section 2.11 feel free to read it on your own

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

Math 10- Chapter 2 Review

Is the statement sufficient? If both x and y are odd, is xy odd? 1) xy 2 < 0. Odds & Evens. Positives & Negatives. Answer: Yes, xy is odd

Math 1 Variable Manipulation Part 2 Exponents & Roots

Jim Lambers ENERGY 211 / CME 211 Autumn Quarter Programming Project 4

Lexical Considerations

Ex: If you use a program to record sales, you will want to remember data:

CSE 101 Introduction to Computers Development / Tutorial / Lab Environment Setup

Expressions and Variables

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Text Input and Conditionals

Introduction to TURING

Long (LONGMATH) variables may be used the same as short variables. The syntax is the same. A few limitations apply (see below).

UNIT- 3 Introduction to C++

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

Advanced Algorithms and Computational Models (module A)

Math 171 Proficiency Packet on Integers

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

Types, lists & functions

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

Multiply Decimals Multiply # s, Ignore Decimals, Count # of Decimals, Place in Product from right counting in to left

Python for Astronomers. Week 1- Basic Python

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

Unit 3. Operators. School of Science and Technology INTRODUCTION

Downloaded from Chapter 2. Functions

Arithmetic Expressions in C

COMS W4115 Programming Languages & Translators GIRAPHE. Language Reference Manual

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

Chapter 1 An Introduction to Computer Science. INVITATION TO Computer Science 1

Introduction to Programming

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

1 Lexical Considerations

Number System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

Lecture 3 Operators MIT AITI

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

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

Getting Started Values, Expressions, and Statements CS GMU

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

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

Announcements for this Lecture

Laboratory Exercise #0

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

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

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Chapter 2: Using Data

3.1 Using Exponents to Describe Numbers

( 3) ( 4 ) 1. Exponents and Radicals ( ) ( xy) 1. MATH 102 College Algebra. still holds when m = n, we are led to the result

Transcription:

Fundamentals: Expressions and Assignment A typical Python program is made up of one or more statements, which are executed, or run, by a Python console (also known as a shell) for their side effects e.g, to input some data, write to a file, display values, etc. There are many kinds of Python statements. But the most fundamental is assignment. An assignment has the following form, where var denotes a variable and exp denotes an expression: var = exp (Read as: var is assigned exp or var gets exp.) To execute the assignment, the console first evaluates exp and creates an object 1 to represent the value of exp. The console then associates the name var with this object. After executing the assignment, var can be used in other expressions to stand for this value. Every object has a type. The type determines how the value is represented in memory and how it can be used in a program. You can find the type of the object using Python s type function e.g., evaluating the expression type( 1.5 ) returns the value float. This exercise explores these concepts in more detail. It also requires you to experiment in the console and to load and run a Python program. Part (a): (Expressions and types) A literal is an expression that stands for a fixed value. The table below illustrates four kinds of literals, their types, and the values that they stand for. Literal Type Value 18-10000 int The integers 18 and 10,000 3.5-3e-4 float The decimal numbers 3.5 and 0.0003 'THIS IS AN EX-PARROT!!' "No, 'e's uh,... resting." """I never! Yes you did!""" str str str The sequence of 22 characters between the single quotes (including spaces and punctuation) The sequence of 24 characters between the double quotes (including spaces and punctuation) The sequence of 21 characters between the triple quotes (including spaces, punctuation, and the new-line character ) True False bool The Boolean values true and false 1 An object is essentially a representation in computer memory of a real-world value, such as an integer or a real number.

Once a variable has been assigned a value, the variable stands for the value that was last assigned to it. This value determines the variable s type. For example, the assignment x = 5 associates the variable x with the value 5. After the console executes this assignment, executing the expression x returns a 5; moreover, after this assignment, executing the expression type(x) returns int. The console displays the value returned when it evaluates an expression. So typing x followed by enter displays a 5 and typing type(x) followed by enter displays int. Operators and functions are applied to other expressions, called arguments, to form more complex expressions. For example, after the assignment x = 5, evaluating x + 2 returns 7, i.e., the value produced by adding the values of the arguments, x and 2. With a partner, bring up Spyder. Press the Variable explorer tab in the top right pane and the ipython console tab in the bottom right pane. Follow the instructions below; if you or your partner has any questions, put a pink sticky note on your monitor. 1. In the console, enter 1.5e3. Q: Why doesn t the console display the value exactly as you entered it? 2. Enter a float containing at least 20 significant digits, e.g., 1500000000000000000000.0. Q: What rule do you think the console uses to determine how to display a float value? 3. Enter a floating-point number that differs from the one in step 2 only in the least significant digit, e.g, 1500000000000000000000.8. Q: What do these experiments in the console tell you about floating-point values? 4. Enter the identifier x. Q: Why does the console display an error? 5. Enter the assignment x = 1.5e3. Q: Why doesn t the console display anything? Q: What side effect did executing the assignment produce and how does Spyder show this side effect? Q: What will the console display if you now enter x? Q: What will the console display if you now enter type(x)?

6. Next enter the multi-assignment: x, y, z = 60.0, 23.5, 0.0 Q: What side effect occurred and how does Spyder show this side effect? Q: In the expression x * z, what is the operator and what are the arguments? Operator: Arguments: Q: What will the console display if you now enter x * z? Q: What will the console display if you now enter type(x * z)? 7. In this step, you will practice creating a program file using Spyder and running it in the console. First, find the name of the working directory in the text box in the tool bar at the top of the Spyder workspace. Press the folder icon to the right of this text box. Navigate to your Desktop or Documents folder and create a folder for the CTL and then, within that, create a folder for week 1. Then press the Open button. 8. From the navigation menu at the top of the Spyder workspace, select File => New File This will create a new Untitled sheet in the editor it (left pane) with some boilerplate comments in. Next, select File => Save as, enter a name for the file (e.g., firstprogram), and press the Save button. This saves the contents of the editor sheet in a file with the name you entered and a.py extension in the folder you selected in step 7. Also, now, every time you execute the program, Spyder will first save it to this file. Next, copy the following multi-assignments into this editor sheet (below the comments). x, y, z = 0.0, 23.5, 0.0 a, b = 8, 19 s, t = 'ta', 'da' The editor sheet should now contain a 3-line program containing 7 assignments. Q: What will the console display if you now enter the expression x into the console? Is this what you expected? Q: Based on that experiment, what do you think the console will display if you enter the expression a into the console? Try it.

9. To run (i.e., execute) the program, press the big green arrow in the toolbar. Q: What affect does running this program have? Q: What will the console display if you now enter a * b? 10. To correctly form expressions that use functions and operators, you need to know the Python typing rules. Typing rules indicate how many and what types of arguments a function or operator can be applied to and the types of the values it returns. In this step, you will experiment in the console to discover some typing rules for a few useful Python operators and functions. To keep it simple, we will consider only three types: int, float, and str Some examples to get you started: The result of step 6 suggests that multiplying two float values returns a float value. This is expressed as the typing rule: float * float -> float Similarly, the result of step 9 suggests that multiplying two int values returns an int. In other words, it suggests the typing rule: int * int -> int In contrast, entering s * s into the console produces a error (try it), expressed by the rule: str * str -> ERROR Beside each expression below, finish the typing rule suggested by entering the expression into the console: a * x int * float -> x * a float * int -> b * s int * str -> t * a str * int -> x * s float * str -> t * s str * str ->

11. Other important operators are shown in the following table. Finish the typing rules for each. (You can check by running experiments in the console.) Start Operator Rules -v +y v + w v w v / w v ** w v // w v % w negative positive addition subtraction division power quotient remainder -int -> -float -> -str -> int + int -> int + float -> int + str -> float + float -> float + int -> float + str -> str + str -> str + int -> str + float -> int + int -> int + float -> int + str -> float + float -> float + int -> float + str -> str + str -> str + int -> str + float -> int + int -> int + float -> int + str -> float + float -> float + int -> float + str -> str + str -> str + int -> str + float ->

Part (b): To correctly form expressions that contain many operators, you need to know the precedence of operators and how operators associate. The following table shows the precedence of the Python operators that we ve used so far, from highest (power) to lowest (addition and subtraction): Operator x**y x, +x x*y, x/y, x//y, x%y x+y, x-y Description power negative and positive multiplication, division, quotient, and remainder addition and subtraction Most Python operators at the same precedence level associate from left to right. The one exception is the power operator, **, which associates from right to left. For example: 1 3 * 2 + 7 = 1 6 + 7 = 5 + 7 = 2 5 3 1 = 2 1 = 1 2 ** 3 ** 2 = 2**9 = 512 Assume the following assignments were previously entered in the console: A = 2 and B = 3 Fill in the table with the value of each expression (do these on paper!). Expression Value Expression Value A + B // 2 (A + B) // 2 - B - A + 2 * A (- (B - A) + 2 ) * A B * A / A * B B * A / (A * B) 10 ** B ** A * -0.5 (10 ** B) ** (A * -0.5) After filling in the table, download the file precedence.py from this week s Artifacts section on the CTL website; put it in the same folder that you navigated to in Step 7 of Part a. (Press the link in the Artifacts section and then select File => Save page as in your browser and navigate to the folder). Open the file in Spyder (use File => Open ). Run it to check your answers.

Part (c): You can also use functions in forming expressions. To call a function, you enter the function name and then any arguments (function inputs) enclosed in parentheses and separated by commas. For example, executing help(round) calls the built-in help function on the argument round. Enter help(round) into the console. Based on what it displays and additional experiments, try to answer the following questions. 1. What is round? 2. How many arguments are needed to call round? 3. What is 1/3 to 2 digits of accuracy? 4. What is the square root of 2 to 4 digits of accuracy? (Hint: Recall that the square root of a number n is the same as n raised to the ½ power.) 5. What integer is closest to the cube root of 755? For each type, Python provides a type constructor, which is a function for creating values of that type; the type constructor name is the same as the type name. Test this out in the console by executing expressions such as the following. int(2.9999e2) float(3 * 75) float(2.9999e2) str(3) str(2.9999e2) str(3/10**15) Run some tests to determine answers to the following questions: 1. When does the int function create an int from a string (str) argument and when does it produce an error? 2. When does the float function create a float from a string (str) argument and when does it produce an error?