Variables, Expressions, and Statements

Similar documents
Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

Computing with Numbers Zelle - Chapter 3

My First Python Program

Stored (and reused) Steps

CPSC 217-T03/T08. Functions Ruting Zhou

STEAM Clown Productions. Python-Functions. Page 1

Conditional Execution

Chapter 2 Writing Simple Programs

ENGR 101 Engineering Design Workshop

Variables, expressions and statements

Getting Started with Python

SI Networked Computing: Storage, Communication, and Processing, Winter 2009

Fundamentals of Programming (Python) Getting Started with 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)

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

Variable and Data Type I

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

Variable and Data Type I

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

PROGRAMMING FUNDAMENTALS

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Programming with Python

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

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

Why Program? Computers want to be helpful... Programmers Anticipate Needs. Chapter 1. Computers are built for one purpose - to do things for us

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

Getting Started Values, Expressions, and Statements CS GMU

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

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

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

Jython. secondary. memory

UNIVERSITÀ DI PADOVA. < 2014 March >

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

Python for Informatics

Lessons on Python Numbers

Conditional Execution

CMSC 201 Computer Science I for Majors

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Review. Input, Processing and Output. Review. Review. Designing a Program. Typical Software Development cycle. Bonita Sharif

CSCE 110 Programming I

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

T H E I N T E R A C T I V E S H E L L

Strings. Chapter 6. Python for Everybody

Python: common syntax

Chapter 2 Input, Processing and Output. Hong Sun COSC 1436 Spring 2017 Jan 30, 2017

Algorithms and Programming I. Lecture#12 Spring 2015

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Algorithms and Data Structures

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

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

cs1114 REVIEW of details test closed laptop period

CS 112: Intro to Comp Prog

Decisions, Decisions. Testing, testing C H A P T E R 7

Python I. Some material adapted from Upenn cmpe391 slides and other sources

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

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

Not-So-Mini-Lecture 6. Modules & Scripts

C: How to Program. Week /Mar/05

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

Advanced Python. Executive Summary, Session 1

Basic Syntax - First Program 1

Python Unit

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

Unit 3. Operators. School of Science and Technology INTRODUCTION

Chapter 2 - Introduction to C Programming

Introduction to Python Code Quality

Python for Non-programmers

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

Built-in Types of Data

The float type and more on variables FEB 6 TH 2012

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

About Variables in Python F E B 1 1 T H

Expressions and Variables

CITS 4406 Problem Solving & Programming

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

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

Control Structures 1 / 17

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

Decision Structures Zelle - Chapter 7

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han

CS313D: ADVANCED PROGRAMMING LANGUAGE

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

And Parallelism. Parallelism in Prolog. OR Parallelism

MIT AITI Python Software Development

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

Python Programming Exercises 1

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Functions and Decomposition

Beyond Blocks: Python Session #1

Python. Objects. Geog 271 Geographic Data Analysis Fall 2010

Short, Unique and Mysterious

BASIC ELEMENTS OF A COMPUTER PROGRAM

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

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

Programming for Engineers Introduction to C

Chapter 2 Getting Started with Python

Chapter 2: Using Data

Transcription:

Variables, Expressions, and Statements Chapter 2 Python for Informatics: Exploring Information www.pythonlearn.com

Constants Fixed values such as numbers, letters, and strings are called constants because their value does not change Numeric constants are as you expect String constants use single quotes (') or double quotes (") >>> print 123 123 >>> print 98.6 98.6 >>> print 'Hello world' Hello world

Variables A variable is a named place in the memory where a programmer can store data and later retrieve the data using the variable name Programmers get to choose the names of the variables You can change the contents of a variable in a later statement x = 12.2 y = 14 x y 12.2 14

Variables A variable is a named place in the memory where a programmer can store data and later retrieve the data using the variable name Programmers get to choose the names of the variables You can change the contents of a variable in a later statement x = 12.2 y = 14 x 12.2 100 x = 100 y 14

Python Variable Name Rules 1.Must start with a letter or underscore _ 2.Must consist of letters and numbers and underscores 3.Case Sensitive Good: spam eggs spam23 _speed Bad: 23spam #sign var.12 Different: spam Spam SPAM

Reserved Words You cannot use reserved words as variable names / identifiers and del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in print as with

Sentences or Lines x = 2 x = x + 2 print x Assignment statement Assignment with expression Print statement Variable Operator Constant Reserved Word

Assignment Statements We assign a value to a variable using the assignment statement (=) An assignment statement consists of an expression on the right-hand side and a variable to store the result x = 3.9 * x * ( 1 - x )

A variable is a memory location used to store a value (0.6) x 0.6 0.6 0.6 x = 3.9 * x * ( 1 - x ) 0.4 The right side is an expression. Once the expression is evaluated, the result is placed in (assigned to) x. 0.936

A variable is a memory location used to store a value. The value stored in a variable can be updated by replacing the old value (0.6) with a new value (0.93). x 0.6 0.93 x = 3.9 * x * ( 1 - x ) The right side is an expression. Once the expression is evaluated, the result is placed in (assigned to) the variable on the left side (i.e., x). 0.93

Numeric Expressions Because of the lack of mathematical symbols on computer keyboards - we use computer-speak to express the classic math operations Asterisk is multiplication Exponentiation (raise to a power) looks different from in math. Operator Operation + Addition - Subtraction * Multiplication / Division ** Power % Remainder

Numeric Expressions >>> xx = 2 >>> xx = xx + 2 >>> print xx 4 >>> yy = 440 * 12 >>> print yy 5280 >>> zz = yy / 1000 >>> print zz 5 >>> jj = 23 >>> kk = jj % 5 >>> print kk 3 >>> print 4 ** 3 64 5 23 20 4 R 3 3 Operator Operation + Addition - Subtraction * Multiplication / Division ** Power % Remainder

Order of Evaluation When we string operators together - Python must know which one to do first This is called operator precedence Which operator takes precedence over the others? x = 1 + 2 * 3-4 / 5 ** 6

Operator Precedence Rules Highest precedence rule to lowest precedence rule: > Parenthesis are always respected > Exponentiation (raise to a power) > Multiplication, Division, and Remainder > Addition and Subtraction Parenthesis Power Multiplication Addition Left to Right > Left to right

>>> x = 1 + 2 ** 3 / 4 * 5 >>> print x 11 >>> Parenthesis Power Multiplication Addition Left to Right 1 + 2 ** 3 / 4 * 5 1 + 8 / 4 * 5 1 + 2 * 5 1 + 10 11

Operator Precedence Remember the rules top to bottom When writing code - use parenthesis Parenthesis Power Multiplication Addition Left to Right When writing code - keep mathematical expressions simple enough that they are easy to understand Break long series of mathematical operations up to make them more clear Exam Question: x = 1 + 2 * 3-4 / 5

Python Integer Division is Weird! Integer division truncates Floating point division produces floating point numbers >>> print 10 / 2 5 >>> print 9 / 2 4 >>> print 99 / 100 0 >>> print 10.0 / 2.0 5.0 >>> print 99.0 / 100.0 0.99 This changes in Python 3.0

Mixing Integer and Floating When you perform an operation where one operand is an integer and the other operand is a floating point, the result is a floating point The integer is converted to a floating point before the operation >>> print 99 / 100 0 >>> print 99 / 100.0 0.99 >>> print 99.0 / 100 0.99 >>> print 1 + 2 * 3 / 4.0-5 -2.5 >>>

What does Type Mean? In Python variables, literals and constants have a type Python knows the difference between an integer number and a string For example + means addition if something is a number and concatenate if something is a string >>> ddd = 1 + 4 >>> print ddd 5 >>> eee = 'hello ' + 'there' >>> print eee hello there concatenate = put together

Type Matters Python knows what type everything is Some operations are prohibited You cannot add 1 to a string We can ask Python what type something is by using the type() function >>> eee = 'hello ' + 'there' >>> eee = eee + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects >>> type(eee) <type 'str'> >>> type('hello') <type 'str'> >>> type(1) <type 'int'> >>>

Several Types of Numbers Numbers have two main types > Integers are whole numbers: -14, -2, 0, 1, 100, 401233 > Floating Point Numbers have decimal parts: -2.5, 0.0, 98.6, 14.0 There are other number types - they are variations on float and integer >>> xx = 1 >>> type (xx) <type 'int'> >>> temp = 98.6 >>> type(temp) <type 'float'> >>> type(1) <type 'int'> >>> type(1.0) <type 'float'> >>>

Type Conversions When you put an integer and floating point in an expression, the integer is implicitly converted to a float You can control this with the built-in functions int() and float() >>> print float(99) / 100 0.99 >>> i = 42 >>> type(i) <type 'int'> >>> f = float(i) >>> print f 42.0 >>> type(f) <type 'float'> >>> print 1 + 2 * float(3) / 4-5 -2.5 >>>

String Conversions You can also use int() and float() to convert between strings and integers You will get an error if the string does not contain numeric characters >>> sval = '123' >>> type(sval) <type 'str'> >>> print sval + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' >>> ival = int(sval) >>> type(ival) <type 'int'> >>> print ival + 1 124 >>> nsv = 'hello bob' >>> niv = int(nsv) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int()

User Input We can instruct Python to pause and read data from the user using the raw_input() function The raw_input() function returns a string nam = raw_input('who are you?') print 'Welcome', nam Who are you? Chuck Welcome Chuck

Converting User Input If we want to read a number from the user, we must convert it from a string to a number using a type conversion function Later we will deal with bad input data inp = raw_input('europe floor?') usf = int(inp) + 1 print 'US floor', usf Europe floor? 0 US floor 1

Comments in Python Anything after a # is ignored by Python Why comment? > Describe what is going to happen in a sequence of code > Document who wrote the code or other ancillary information > Turn off a line of code - perhaps temporarily

# Get the name of the file and open it name = raw_input('enter file:') handle = open(name, 'r') text = handle.read() words = text.split() # Count word frequency counts = dict() for word in words: counts[word] = counts.get(word,0) + 1 # Find the most common word bigcount = None bigword = None for word,count in counts.items(): if bigcount is None or count > bigcount: bigword = word bigcount = count # All done print bigword, bigcount

String Operations Some operators apply to strings > + implies concatenation > * implies multiple concatenation Python knows when it is dealing with a string or a number and behaves appropriately >>> print 'abc' + '123 abc123 >>> print 'Hi' * 5 HiHiHiHiHi >>>

Mnemonic Variable Names Since we programmers are given a choice in how we choose our variable names, there is a bit of best practice We name variables to help us remember what we intend to store in them ( mnemonic = memory aid ) This can confuse beginning students because well-named variables often sound so good that they must be keywords http://en.wikipedia.org/wiki/mnemonic

x1q3z9ocd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd print x1q3p9afd What is this bit of code doing?

x1q3z9ocd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd print x1q3p9afd a = 35.0 b = 12.50 c = a * b print c What are these bits of code doing?

x1q3z9ocd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ocd * x1q3z9afd print x1q3p9afd a = 35.0 b = 12.50 c = a * b print c What are these bits of code doing? hours = 35.0 rate = 12.50 pay = hours * rate print pay

Exercise Write a program to prompt the user for hours and rate per hour to compute gross pay. Enter Hours: 35 Enter Rate: 2.75 Pay: 96.25

Summary Type Reserved words Variables (mnemonic) Operators Integer Division Conversion between types User input Comments (#) Operator precedence

Acknowledgements / Contributions These slides are Copyright 2010- Charles R. Severance (www.dr-chuck.com) of the University of Michigan School of Information and open.umich.edu and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials.... Initial Development: Charles Severance, University of Michigan School of Information Insert new Contributors and Translators here