jas0nhuang

猴子學Python - Business Computing in Python (week 4)

Conditionals

  1. Nested if-else

    if XXX:
    if YYY:
    statement A
    else:
    statement B
    else:
    statement C
  2. Avoid potential inconsistency
    Don’t repeat, don’t copy paste your code.
    Eliminate redundancy!

  3. Ternary if operator

    min = a if a <= c else c
    • parentheses are helpful. They make the code more readable.
      min = (a if (a <= c) else c)
  4. else if = elif

    if XXX:
    elif YYY:
    else:
  5. Logical operators

    • ‘and’, ‘or’, ‘not’
    • operators have precedence rule, but don’t memorize it. Just use PARENTHESES!
    • conditions must be complete at both sides.
    • ‘not’ is a unary operator.

Iterations(loop)

  1. ‘while’

    • an ‘if’ that repeats
    • use ‘loop counters’ to keep track of/update the loop. Self assignment are useful (+=)
    • logical error may create infinite loops
  2. ‘break’ and ‘continue’

    • ‘break’ will exit the loop immediately.
    • ‘continue’ will skip the statements in the loop and recheck the looping condition.
    • ‘break’ gives a loop multiple exits, it sometimes makes the code harder to read.
  3. ‘for’

    • for variable in list
      variable: the loop counter
      list: variables that will be traersed.
    • how to create list?
    • range() function
  4. biggest difference between ‘while’ and ‘for’
    the statement after ‘while’ is a condition but the statement after ‘for’ is just a counter assignment

  5. Nested loops

    • helpful for multi-dimentional cases.
    • print(xxxxxxx , end = “ “) the end is used to add anything you want at the end of the printed Chars without adding a new line.

Precision

1. useing 'math' module

2. most decimal fractional numbers can only be approximated!!

3. use imprecise comparisons but can't 100% solve the problem.

Exercise

Newsvendor problem

c = int(input("perchase cost"))
r = int(input("price"))
N = int(input("needs")) + 1
q = int(input("perchase ammount"))

totalprof = 0
totalpercentage = 0
if q == 0:
print("nothing!")

else:
for j in range(0, q + 1):
if j < q:
pi = input("probability")
totalpercentage += pi
else:
pi = 100 - totalpercentage
print(totalpercentage)
print(pi)
profit = (r * j - q * c) * pi
totalprof += profit
print(profit)
print(totalprof)

print(totalprof)