Variables, Expressions, and Standard Functions. Topics Basic calculation Expressions, variables, and operator precedence Data types Input / Output Examples.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 2 Simple C Programs.
Advertisements

Computer Programming w/ Eng. Applications
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Python November 14, Unit 7. Python Hello world, in class.
 2002 Prentice Hall. All rights reserved. 1 Intro: Java/Python Differences JavaPython Compiled: javac MyClass.java java MyClass Interpreted: python MyProgram.py.
Introduction to Python
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏
 2002 Prentice Hall. All rights reserved. 1 Chapter 2 – Introduction to Python Programming Outline 2.1 Introduction 2.2 First Program in Python: Printing.
Basic Input/Output and Variables Ethan Cerami New York
Basic Elements of C++ Chapter 2.
Guide to Programming with Python Chapter Two Basic data types, Variables, and Simple I/O: The Useless Trivia Program.
Introduction to MATLAB ENGR 1187 MATLAB 1. Programming In The Real World Programming is a powerful tool for solving problems in every day industry settings.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
Python Programming Fundamentals
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Introduction to Python
Fundamentals of Python: First Programs
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Functions and subroutines – Computer and Programming.
Unit 3: Java Data Types Math class and String class.
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
Input, Output, and Processing
Chapter 2: Using Data.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Variables, Expressions and Statements
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Introduction to Visual Basic Programming. Introduction Simple Program: Printing a Line of Text Another Simple Program: Adding Integers Memory Concepts.
Math, Data Types. Python Math Operations OperationOperator Addition + Subtraction – Multiplication * Division (floating point) / Division (integer) //
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
110 E-1 Variables, Constants and Calculations(2) Chapter 3: Operations on variables, scope of a variable, formatting data Doing Arithmetic.
D-1 University of Washington Computer Programming I Lecture 4: Arithmetic Expressions © 2000 UW CSE.
29 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
PYTHON VARIABLES : CHAPTER 2 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.
Introduction to Programming
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Part 1 Learning Objectives To understand that variables are a temporary named location to store data and that programmers work with different data types.
Variables, Operators, and Expressions
Fundamentals of Programming I Overview of Programming
Chapter Topics The Basics of a C++ Program Data Types
Topics Designing a Program Input, Processing, and Output
Expressions.
BIL 104E Introduction to Scientific and Engineering Computing
TMF1414 Introduction to Programming
Basic Elements of C++.
Variables, Expressions, and IO
Introduction to Programming
Basic Elements of C++ Chapter 2.
A First Book of ANSI C Fourth Edition
Reading Input from the Keyboard
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Variables, Data Types & Math
Computing in COBOL: The Arithmetic Verbs and Intrinsic Functions
CHAPTER 3: String And Numeric Data In Python
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Terminal-Based Programs
月夜憶舍弟 戍鼓斷人行,邊秋一雁聲。 露從今夜白,月是故鄉明。 有弟皆分散,無家問死生。 寄書長不達,況乃未休兵。 杜甫
Introduction to Python
Presentation transcript:

Variables, Expressions, and Standard Functions

Topics Basic calculation Expressions, variables, and operator precedence Data types Input / Output Examples 2

A calculator We can use a computer as a calculator. Just type expressions into the Python Shell 3 Python Shell in Wing IDE

A calculator Try this. 4 >>> 10 * 5 50 >>> >>> >>> 1 * ** 2 29 Type it into Python Shell The answer Spaces are irrelevant ** is for exponentiation

Expression What we have just typed into the Python Shell is called expressions. After the shell reads each expression, the shell evaluate it and reports the result. 5

Easy calculation An object moves with the starting speed of 10 m/s with an acceleration of 2 m/s 2. After 5 seconds, how far is the object from its starting position? 6 s = ut + at 2 /2 10 * * (5*5) / 2

Operators (1) In previous examples, we use many operators such as +, -, or /, to tell Python to perform various computations with the data. An operator tells Python what operation to perform with its operands * 5 operator operands

Operators (2) Operators can be  Binary operators that work with two operands, e.g., +, -, or *. 5 * 3 10 – 2 15*7  Unary operators that work with a single operand, e.g, – * 7 8

Operators (2) Basic mathematical operators are shown in the table below 9 OperatorMeaningExamples + addition subtraction 4-2 * multiplicatio n 4.5*10 / divisionsee next page % modulosee next page ** exponentiati on 3**4

Division in Python There are two operators related to division 10 expressi on result 4/22.0 3/ / / / expressi on result 4%20 3%21 10%73 3.0% % divisionmodulo – find the remainder

Numbers in Python There are two types for numbers in Python: integer (type int ) and floating points (type float ) 11 Integer expressi on ValueFloating- point expr. Values *59519*

ExpressionsValues * 620 (2+3) *630 3/5*21.2 3*5.0/27.5 Quick test 12

Integers v.s. Floating- points If you write a number without a "dot", it will be treated as an integer. Results  Every mathematical operation between integer and integer returns an integer, except for division.  Division returns floating-point numbers.  Any operations with floating-point numbers return floating-point numbers. 13

3/5*2 Evaluation is usually done from left to right 14 ((3/5)*2) ( 0.6 *2)

Operator precedence But operators have different precedence, e.g., * or / have higher precedence over + or *6 2+(3*6)

This is just…. High-school math! 16

Operator precedence Evaluation order is from left-to- right for operators with the same precedence, except **. 17 OperatorsExamples 1()(3+4) 2** (expo.)2**3 3-,+ (unary)-5, +10 4*,/,%3*4, 7%2 5-,+2+7, 3-4

Try this (1) *6/3+(7-2*3) What is the result? 13.0

Try this (2) 19 2 ** 2 ** 3 What is the result? 2 8 = ** (2 ** 3)

Reusing values A force of 2.5 newton pushes a rock with mass 1 kg to the left. Where is the rock after 1 second, 5 second and 15 second? 20 (1.0/2.5)*1*1/2 (1.0/2.5)*5*5/2 (1.0/2.5)*15*15/2 Redun dant

Variables We can use variables to refer to result from previous computation. 21 a*1*1/2 a*5*5/2 a*15*15/2 a = 1.0/2.5 a0.4

Variables A variable is used to refer to various data. Use "=" to assign a value to a variable. When we refer to that variable, we get the value that the variable is referring to. 22 a = 1.0/ a

Variables can be "modified" (1) 23 a = 10 a * 5 b = 3 a + b a = 7 a + b a = b + 5 a a + b

Variables can be "modified" (2) 24 a = 10 a = a

Variables can be "modified" (3) 25 x = 10 x = x * 2 20

Variables can be "modified" (4) 26 x = 10 x = x *

Working on Wing IDE 27 Shell or Console After you type commands or expressions, the Python Interpreter evaluates them and prints out the output

Typing programs in WingIDE 28 Editing area Any commands here are executed after you hit the "run" button.

A program A program is a sequence of commands (or statements) 29 a = 10 b = a + 5 a - b c = 12 b = a + c c = a*b a + b + c 1 + a - c Try to type this into Wing IDE

Result 30 Empty Because the program does not have statements that output anything.

Printing We can use function print to display results 31

A program A program is a sequence of commands (or statements) 32 a = 10 b = a + 5 print(a – b) c = 12 b = a + c c = a*b print(a + b + c) print(1 + a – c) Add "print" to display the value of the required expressions

See the output after hitting "Run" 33

Function calls 34 print(10) Function name Arguments

What's going on? The expressions on the parameter list are evaluated before sending the result to the function. 35 print(a + b * 2) 20 Assume that a = 5 b = print(25)print(25)

A simple calculation program We have the following coins  5 one-baht coins  7 ten-baht coins  2 twenty-baht notes  3 hundred-baht notes 36 sum1 = 1 * 5 sum10 = 10 * 7 sum20 = 20 * 2 sum100 = 100 * 3 sum = sum1+sum5+sum20+sum100 print(sum) How much money do we have ?

A simple program (2) Or we can even remove variable sum 37 sum1 = 1 * 5 sum10 = 10 * 7 sum20 = 20 * 2 sum100 = 100 * 3 print(sum1+sum5+sum20+sum100)

Meaningful names 38 a = 1 * 5 b = 10 * 7 c = 20 * 2 d = 100 * 3 e = a + b + c + d print(e) sum1 = 1 * 5 sum10 = 10 * 7 sum20 = 20 * 2 sum100 = 100 * 3 sum = sum1+sum5+sum20+sum100 print(sum) They perform the same task Which one is easier to understa nd? Compare these two programs

Suggestions Write programs for people to read  At the very least, one of the audience is yourself. 39

Comments (#) To make a program easier to read, we can add comments to the program Everything after the # symbol is a comment. 40

A program with comments 41 # this program calculates total money # from the amount of each type of coins or # bank notes that you have sum1 = 1 * 5 # value of 1-baht coins sum10 = 10 * 7 sum20 = 20 * 2 sum100 = 100 * 3 print(sum1+sum5+sum20+sum100)

”Hello Strings A computer can work with many types of data. A string is another data type which is very important. It is a type for texts or messages. Formally, a string is a sequence of characters. 42 ”Hello, world”

String constants We can either use single or double quotes to specify strings, e.g.,  ”Hello”  ’World’ However, the starting quotes and the ending quotes must match. We can also have special characters inside a string. They will start with backslash " \ ". 43

Examples (1) 44 print("hello") hello print('hello') hello print("I'm 9") I'm 9 print('I'm 9') ERROR print('I\'m 9') I'm 9 print("I\'m 9") I'm 9

Examples (2) 45 print("123") 123 print(123) 123 print("12" + "3") 123 print(12 + 3) 15 print("12" + '3') 123 print("12" + 3) ERROR

A slightly better program 46 sum1 = 1 * 5 sum10 = 10 * 7 sum20 = 20 * 2 sum100 = 100 * 3 sum = sum1+sum5+sum20+sum100 print("The total is",sum) The total is 415

A slightly even better program 47 sum1 = 1 * 5 sum10 = 10 * 7 sum20 = 20 * 2 sum100 = 100 * 3 sum = sum1+sum5+sum20+sum100 print("The total is",sum,"bath.") The total is 415 bath.

Sidenote: printing and new lines We can display data using function print. It will always add a new line at the end. If we want to avoid the new line, we can add an additional option "end" to print. 48 print(10) print(20) print(10,end='') print(20) This tells print to end this output with an empty string, instead of a new line.

Reading inputs We can use function input to read data from the user input The function returns a string that the user types into the shell. 49

Examples in the Python Shell >>> name = input() Somchai >>> print("Hello", name) Hello Somchai >>> a = input() 10 >>> b = input() 100 >>> print(a+b)

Remarks Consider this statement print(a+b) Since both variables a and b are strings from function input. When we add two strings, we only get the concatenation of them. 51

????? How are we going to do calculations when we can only read strings from the user? 52

Conversion We can use function int, float, and str to convert between various data types 53 int("10") float("10") float(10) int(10.6) 10

Type conversion 54 int("10")+10 float("10")+10 float(10)+int(5) str(10)+str(5) 105

Conversion between float and int (1) 55 int(10.2) int(10.9) 10 Always return the integers without the fractional parts. int(-10.1) -10

Conversion between float and int (2) 56 round(10.2) round(10.9) We can also use function round that returns the closest integers. round(-10.1) -10

Adding two numbers 57 # This program adds two numbers astr = input() a = int(astr) bstr = input() b = int(bstr) print("The result is",a+b)

Nested function calls (1) Consider this part of the program We use variable astr to refer to an input string. We then convert it to an integer and assign the result to variable a. We can avoid using variable astr: 58 astr = input() a = int(astr) a = int(input())

Nested function calls (2) This is how it works. 59 a = int(input()) input() int "12345" a = a

Two additional important functions 60 FunctionsReturn values abs(x) Returns the absolute value of x pow(x,y) Returns the value of x y

Money calculation (improved) 61 # This program calculates total amount # of money from numbers of bank notes p1 = int(input()) sum1 = 1 * p1 p5 = int(input()) sum5 = 10 * p5 p20 = int(input()) sum20 = 20 * p20 p100 = int(input()) sum100 = 100 * p100 sum = sum1+sum5+sum20+sum100 print("The total is",sum,"bath.")

A prompt We can tell function input to display a prompt before reading input by providing a string argument to input 62 Enter X:

Thinking corner An object, initially sitting still, starts moving with an acceleration of a m/s 2 for t seconds. Write a program that reads the acceleration and the duration and computes the displacement. 63

Solution 64 a = float(input("Enter a: ")) t = float(input("Enter t: ")) print("Total distance =", a*t*t/2)

Thinking corner 65 Enter length in inch: 320 It is 26 feet, 8 inch. x = int(input("Enter length in inch")) xf = int(x/12) xi = x – xf * 12 print("It is", xf, "feet,",xf,"inch.")

Volume Calculation Compute the volume of a cylinder 66 h h r  r 2 x h

 We can use 22/7 (which is quite inaccurate). We can use a closer estimation, in module math

The math module In Python, functions are categorized into various groups, called modules. To use functions from a module, we have to declare that by using the import statement. Then all functions can be referred to by prefixing with the module name. 68 import math print("Pi is", math.pi) import math print("Pi is", math.pi)

Thinking corner Write a program that reads r and h and compute the volume of a cylinder. 69 h h r  r 2 x h

Solution 70 import math r = float(input("Enter r: ")) h = float(input("Enter h: ")) print("Volume =", math.pi*r*r*h)

Important functions in math module 71 FunctionsGoals fabs(x) The absolute value of x sin(x), cos(x), tan(x) Trigonometric functions of x (the angles are specified in radian) pi Constant Pi e Constant e log(x),log10(x) Natural logarithm, logarithm base 10 exp(x) The value of e x sqrt(x) Square root of x

Another example Projection 72 t f import math # radian angles fy = f * math.sin(t) fx = f * math.cos(t) # don't forget to import math # recall that the angle must be in radian r = t * math.pi/180 fy = f * math.sin(r) fx = f * math.cos(r)