Download presentation
Presentation is loading. Please wait.
Published byShauna Henderson Modified over 9 years ago
1
Variables, Expressions, and Standard Functions
2
Topics Basic calculation Expressions, variables, and operator precedence Data types Input / Output Examples 2
3
A calculator We can use a computer as a calculator. Just type expressions into the Python Shell 3 Python Shell in Wing IDE
4
A calculator Try this. 4 >>> 10 * 5 50 >>> 1 + 2 + 3 + 4 10 >>> 1+2+3+4 10 >>> 1 * 4 + 5 ** 2 29 Type it into Python Shell The answer Spaces are irrelevant ** is for exponentiation
5
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
6
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 + 2 * (5*5) / 2
7
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. 7 10 * 5 operator operands
8
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, –. -3 +2 -5 * 7 8
9
Operators (2) Basic mathematical operators are shown in the table below 9 OperatorMeaningExamples + addition 3+5 - subtraction 4-2 * multiplicatio n 4.5*10 / divisionsee next page % modulosee next page ** exponentiati on 3**4
10
Division in Python There are two operators related to division 10 expressi on result 4/22.0 3/21.5 10/71.4286 3.0/21.5 10/7.01.4286 expressi on result 4%20 3%21 10%73 3.0%21.0 10%7.03.0 divisionmodulo – find the remainder
11
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 10 10.0 3-213.0-21.0 19*59519*5.298.8
12
ExpressionsValues 2 + 3 * 620 (2+3) *630 3/5*21.2 3*5.0/27.5 Quick test 12
13
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
14
3/5*2 Evaluation is usually done from left to right 14 ((3/5)*2) ( 0.6 *2)
15
Operator precedence But operators have different precedence, e.g., * or / have higher precedence over + or -. 15 2+3*6 2+(3*6)
16
This is just…. High-school math! 16
17
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
18
Try this (1) 18 2+5*6/3+(7-2*3) What is the result? 13.0
19
Try this (2) 19 2 ** 2 ** 3 What is the result? 2 8 = 256 2 ** (2 ** 3)
20
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
21
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
22
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/2.5 0.4 a
23
Variables can be "modified" (1) 23 a = 10 a * 5 b = 3 a + b a = 7 a + b a = b + 5 a a + b 50 13 10 8 11
24
Variables can be "modified" (2) 24 a = 10 a = a + 1 11
25
Variables can be "modified" (3) 25 x = 10 x = x * 2 20
26
Variables can be "modified" (4) 26 x = 10 x = x * 2 + 5 25
27
Working on Wing IDE 27 Shell or Console After you type commands or expressions, the Python Interpreter evaluates them and prints out the output
28
Typing programs in WingIDE 28 Editing area Any commands here are executed after you hit the "run" button.
29
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
30
Result 30 Empty Because the program does not have statements that output anything.
31
Printing We can use function print to display results 31
32
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
33
See the output after hitting "Run" 33
34
Function calls 34 print(10) Function name Arguments
35
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 = 10 25 print(25)print(25)
36
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 ?
37
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)
38
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
39
Suggestions Write programs for people to read At the very least, one of the audience is yourself. 39
40
Comments (#) To make a program easier to read, we can add comments to the program Everything after the # symbol is a comment. 40
41
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)
42
”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”
43
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
44
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
45
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
46
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
47
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.
48
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) 10 20 1020 This tells print to end this output with an empty string, instead of a new line.
49
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
50
Examples in the Python Shell >>> name = input() Somchai >>> print("Hello", name) Hello Somchai >>> a = input() 10 >>> b = input() 100 >>> print(a+b) 10100 50
51
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
52
????? How are we going to do calculations when we can only read strings from the user? 52
53
Conversion We can use function int, float, and str to convert between various data types 53 int("10") float("10") float(10) 10 10.0 int(10.6) 10
54
Type conversion 54 int("10")+10 float("10")+10 float(10)+int(5) 20 20.0 15.0 str(10)+str(5) 105
55
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
56
Conversion between float and int (2) 56 round(10.2) round(10.9) 10 11 We can also use function round that returns the closest integers. round(-10.1) -10
57
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)
58
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())
59
Nested function calls (2) This is how it works. 59 a = int(input()) input() int "12345" 12345 a = 12345 a
60
Two additional important functions 60 FunctionsReturn values abs(x) Returns the absolute value of x pow(x,y) Returns the value of x y
61
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.")
62
A prompt We can tell function input to display a prompt before reading input by providing a string argument to input 62 Enter X:100 110
63
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
64
Solution 64 a = float(input("Enter a: ")) t = float(input("Enter t: ")) print("Total distance =", a*t*t/2)
65
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.")
66
Volume Calculation Compute the volume of a cylinder 66 h h r r 2 x h
67
We can use 22/7 (which is quite inaccurate). We can use a closer estimation, in module math. 67 3.141592653589793
68
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) 3.141592653589793
69
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
70
Solution 70 import math r = float(input("Enter r: ")) h = float(input("Enter h: ")) print("Volume =", math.pi*r*r*h)
71
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
72
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)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.