Title: Variables, Expressions, and Standard Functions
1Variables, Expressions, and Standard Functions
2Topics
- Basic calculation
- Expressions, variables, and operator precedence
- Data types
- Input / Output
- Examples
3A calculator
- We can use a computer as a calculator.
- Just type expressions into the Python Shell
Python Shell in Wing IDE
4A calculator
Type it into Python Shell
gtgtgt 10 5 50 gtgtgt 1 2 3 4 10 gtgtgt
1234 10 gtgtgt 1 4 5 2 29
The answer
Spaces are irrelevant
is for exponentiation
5Expression
- 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.
6Easy calculation
- An object moves with the starting speed of 10 m/s
with an acceleration of 2 m/s2. After 5 seconds,
how far is the object from its starting position?
s ut at2/2
10 5 2 (55) / 2
7Operators (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.
operands
10 5
operator
8Operators (2)
- Operators can be
- Binary operators that work with two operands,
e.g., , -, or .5 3 10 2
157 - Unary operators that work with a single operand,
e.g, .-3 2 -5 7
9Operators (2)
- Basic mathematical operators are shown in the
table below
Operator Meaning Examples
addition 35
- subtraction 4-2
multiplication 4.510
/ division see next page
modulo see next page
exponentiation 34
10Division in Python
- There are two operators related to division
division
modulo find the remainder
expression result
4/2 2.0
3/2 1.5
10/7 4286
3.0/2 1.5
10/7.0 1.4286
expression result
42 0
32 1
107 3
3.02 1.0
107.0 3.0
11Numbers in Python
- There are two types for numbers in Python
integer (type int) and floating points (type
float)
Integer expression Value Floating-point expr. Values
10 10 10.0 10.0
3-2 1 3.0-2 1.0
195 95 195.2 98.8
12Quick test
Expressions Values
2 3 6 20
(23) 6 30
3/52 1.2
35.0/2 7.5
13Integers 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.
143/52
- Evaluation is usually done from left to right
((3/5)2)
( 0.6 2)
15Operator precedence
- But operators have different precedence, e.g.,
or / have higher precedence over or -.
236
2(36)
16This is just.
17Operator precedence
Operators Examples
1 () (34)
2 (expo.) 23
3 -, (unary) -5, 10
4 ,/, 34, 72
5 -, 27, 3-4
- Evaluation order is from left-to-right for
operators with the same precedence, except .
18Try this (1)
256/3(7-23)
What is the result?
13.0
19Try this (2)
2 2 3
What is the result?
2 (2 3)
28 256
20Reusing 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?
(1.0/2.5)11/2
Redundant
(1.0/2.5)55/2
(1.0/2.5)1515/2
21Variables
- We can use variables to refer to result from
previous computation.
a 1.0/2.5
a11/2
a55/2
a1515/2
22Variables
a 1.0/2.5
0.4
- 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.
23Variables can be "modified" (1)
a 10a 5b 3a ba 7a ba b
5aa b
50
13
10
8
11
24Variables can be "modified" (2)
a 10a a 1
11
25Variables can be "modified" (3)
x 10x x 2
20
26Variables can be "modified" (4)
x 10x x 2 5
25
27Working on Wing IDE
Shell or Console After you type commands or
expressions, the Python Interpreter evaluates
them and prints out the output
28Typing programs in WingIDE
Editing area Any commands here are executed after
you hit the "run" button.
29A program
- A program is a sequence of commands (or
statements)
a 10b a 5a - bc 12b a cc aba
b c1 a - c
Try totype this intoWing IDE
30Result
Empty
- Because the program does not have statements that
output anything.
31Printing
- We can use function
- print
- to display results
32A program
- A program is a sequence of commands (or
statements)
Add"print"to display the valueof the required
expressions
a 10b a 5print(a b)c 12b a cc
abprint(a b c)print(1 a c)
33See the output after hitting "Run"
34Function calls
print(10)
Function name
Arguments
35What's going on?
print(a b 2)
20
Assume that a 5 b 10
25
print(25)
- The expressions on the parameter list are
evaluated before sending the result to the
function.
36A simple calculation program
- We have the following coins
- 5 one-baht coins
- 7 ten-baht coins
- 2 twenty-baht notes
- 3 hundred-baht notes
How muchmoney do wehave ?
sum1 1 5sum10 10 7sum20 20 2sum100
100 3sum sum1sum5sum20sum100print(sum)
37A simple program (2)
- Or we can even remove variable sum
sum1 1 5sum10 10 7sum20 20 2sum100
100 3print(sum1sum5sum20sum100)
38Meaningful names
Comparethese twoprograms
a 1 5b 10 7c 20 2d 100 3e a
b c dprint(e)
Theyperform thesame task
sum1 1 5sum10 10 7sum20 20 2sum100
100 3sum sum1sum5sum20sum100print(sum)
Which oneis easier to understand?
39Suggestions
- Write programs for people to read
- At the very least, one of the audience is
yourself.
40Comments ()
- To make a program easier to read, we can add
comments to the program - Everything after the symbol is a comment.
41A program with comments
this program calculates total money from the
amount of each type of coins or bank notes that
you havesum1 1 5 value of 1-baht
coinssum10 10 7sum20 20 2sum100 100
3print(sum1sum5sum20sum100)
42Strings
- 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.
Hello
Hello, world
43String 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 " \ ".
44Examples (1)
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
45Examples (2)
print("123")
123
print(123)
123
print("12" "3")
123
print(12 3)
15
print("12" '3')
123
print("12" 3)
ERROR
46A slightly better program
sum1 1 5sum10 10 7sum20 20 2sum100
100 3sum sum1sum5sum20sum100print("The
total is",sum)
The total is 415
47A slightly even better program
sum1 1 5sum10 10 7sum20 20 2sum100
100 3sum sum1sum5sum20sum100print("The
total is",sum,"bath.")
The total is 415 bath.
48Sidenote 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.
print(10)print(20)print(10,end'')print(20)
10201020
This tells print to end this output with an empty
string, instead of a new line.
49Reading 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.
50Examples in the Python Shell
- gtgtgt name input()
- Somchai
- gtgtgt print("Hello", name)
- Hello Somchai
- gtgtgt a input()
- 10
- gtgtgt b input()
- 100
- gtgtgt print(ab)
- 10100
51Remarks
- Consider this statement
- print(ab)
- Since both variables a and b are strings from
function input. When we add two strings, we only
get the concatenation of them.
52?????
- How are we going to do calculations when we can
only read strings from the user?
53Conversion
- We can use function int, float, and str to
convert between various data types
int("10")
10
float("10")
10.0
float(10)
10.0
int(10.6)
10
54Type conversion
int("10")10
20
float("10")10
20.0
float(10)int(5)
15.0
str(10)str(5)
105
55Conversion between float and int (1)
int(10.2)
10
int(10.9)
10
int(-10.1)
-10
Always return the integers without the fractional
parts.
56Conversion between float and int (2)
We can also use function round that returns the
closest integers.
round(10.2)
10
round(10.9)
11
round(-10.1)
-10
57Adding two numbers
This program adds two numbersastr input()a
int(astr)bstr input()b int(bstr)print("Th
e result is",ab)
58Nested 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
astr input()a int(astr)
a int(input())
59Nested function calls (2)
a int(input())
input()
"12345"
int
12345
a 12345
60Two additional important functions
Functions Return values
abs(x) Returns the absolute value of x
pow(x,y) Returns the value of xy
61Money calculation (improved)
This program calculates total amount of money
from numbers of bank notesp1 int(input())sum1
1 p1p5 int(input())sum5 10 p5p20
int(input())sum20 20 p20p100
int(input())sum100 100 p100sum
sum1sum5sum20sum100print("The total
is",sum,"bath.")
62A prompt
- We can tell function input to display a prompt
before reading input by providing a string
argument to input
x int(input("Enter X "))print(x10)
Enter X
100
110
63Thinking corner
- An object, initially sitting still, starts moving
with an acceleration of a m/s2 for t seconds. - Write a program that reads the acceleration and
the duration and computes the displacement.
64Solution
a float(input("Enter a "))t
float(input("Enter t "))print("Total distance
", att/2)
65Thinking corner
Enter length in inch 320It is 26 feet, 8 inch.
x int(input("Enter length in inch"))xf
int(x/12)xi x xf 12print("It is", xf,
"feet,",xf,"inch.")
66Volume Calculation
- Compute the volume of a cylinder
r
?r2 x h
h
67?
- We can use 22/7 (which is quite inaccurate).
- We can use a closer estimation, in module math.
3.141592653589793
68The 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.
import math print("Pi is", math.pi)
3.141592653589793
69Thinking corner
- Write a program that reads r and h and compute
the volume of a cylinder.
r
?r2 x h
h
70Solution
import mathr float(input("Enter r "))h
float(input("Enter h "))print("Volume ",
math.pirrh)
71Important functions in math module
Functions Goals
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 ex
sqrt(x) Square root of x
72Another example
don't forget to import math recall that the
angle must be in radianr t math.pi/180fy
f math.sin(r)fx f math.cos(r)
import math radian anglesfy f
math.sin(t)fx f math.cos(t)