Transcript tutorial5x
CS 116 Tutorial 5
Introduction to Python
Review Basic Python
Python is a series of statements
def f(p1, p2,…pn):
Statement1
x = 5
To make constants: name = value
Statement2
if x > p1:
x = p1 + p2
Statement3
return x Using return causes the function
…
produce something
All code written after the return
else:
on the same indentation line will
Statementn
return p3 not be executed.
Indentation
is
extremely
Review Basic Python
Useful functions:
◦ +, -, *, /, //, %, **
◦ and, or, not, <, >, <=, >=, ==, !=
◦ Math module; use dir(math) to see list
Conditions:
◦ if : to start a condition
◦ elif : to continue a condition
◦ else : to execute something if all other
conditions are not true (not necessary)
Review Python Design Recipe
No type Char or Sym
New type: Float
Examples are comments in the form:
# fn_name(p1, p2, … pn) => result
Tests:
◦ Make sure to download check.py and put
the file in the same folder as your assignment
questions
check.expect(“name”,
fn_name(p1,…pn), result)
1. Write a Python function create_acct_num
that consumes a 3-digit number and produces
the corresponding 4-digit number, in which the
new last digit is remainder when the sum of the
digits of the original number is divided by 7.
• For example,
create_account_number(778) =>
7781
because 7 + 7 + 8 = 22 and 22/7 has remainder
1
2. Write a Python function shipping_charges that
calculates cost of shipping boxes.
The function consumes:
- a handling charge,
- the cost per kg for shipping,
- the weight per box (assumed the same for all boxes), and
- the number of boxes to ship.
The function adds in 13% tax, and returns the total cost.
shipping_charges(handling, charge_per_kg, weight_per_box,
num_boxes)
For example,
Shipping_charges(10, 0.25, 10, 5) => 25.425
Note that the value produced may not stored exactly. So, your
test should not check for an exact value, but rather should
check that your answer is very close to the expected value.
3. Write the accumulatively recursive version of
factorial, paying close attention to when you need to
use return.
4. If you are given three sticks, you may or may not be
able to arrange them in a triangle.
If any of the three lengths is greater than the sum of the
other two, then you cannot form a triangle. Otherwise,
you can. If the sum of two lengths equals the third, they
form what is called a "degenerate triangle.”
Write a function is_triangle that consumes three
positive integers (s1, s2, and s3) representing the
lengths of three sticks and produces one of the
following:
"No triangle exists" if no triangle can be built
with the three sticks
"Degenerate triangle exists" if only a
degenerate triangle exists for sticks of these lengths
"Triangle exists" if a triangle can be made from
the sticks