Quick actions

cmd+k|ctrl+k

Navigation

Languages

20-May-2026 Self-Practice 7 (Overall)

Snippet info

Language

Python

Visibility

public

Author

michaelluiwaihung

Created

2026-05-20T06:38:22.077837Z

Updated

2026-06-03T01:51:31.687322Z

def checknum(passnum):
    try:
        a = float(passnum)
        return True, a
    except ValueError as msg:
        print("Must input a number. ", msg)
    except Exception as e:
        print(e)
        return False, None

def checkop(passop):
    if passop in ['+', '-', '*', '/']:
        return True
    else:
        print("wrong operator !")
        return False
    
def calc(x, y, z):
    if checknum(x)[0] and checknum(y)[0] and checkop(z):
    
        if z == '+':
            result = checknum(x)[1] + checknum(y)[1]
            return True, result
        elif z == '-':
            result = checknum(x)[1] - checknum(y)[1]
            return True, result
        elif z == '*':
             result = checknum(x)[1] * checknum(y)[1]
             return True, result
        elif z == '/':
            if y == 0: 
               print("Cannot divide by zero !")
               return False, None
            else:
               result = checknum(x)[1] / checknum(y)[1]
               return True, result
        else:
            print("Invalid Operator !")
            return False, None
    else:
        print("Invalid Expression !")
        return False, None
        
print("********************** calc ****************************")
InputStr = input("Input Expression : ")
l = list(InputStr.split(" "))
print(l)

while len(l) >= 3 and len(l) % 2:
    a = l[0]
    b = l[2]
    c = l[1]
    print (a)
    print (b)
    print (c)
    
    result1 = calc(a, b, c)[0]
    result2 = calc(a, b, c)[1]
    if result1 != False:
        del l[:2]
        l[0] = result2
    else:
        break
print('result : ', result2)
    

print("********************** calc ****************************")



print("*********************** String Modify ****************************")
a = "Abc def"
print(a)
print('UPPER', a.upper())
print('LOWER', a.lower())
print('TITLE', a.title())
print('CAPITAL', a.capitalize())
print(a)
print("*********************** String Modify ****************************")

#format numbers
price = 199949.99
tax = 0.08
name = "john"
age = 10

total = price * (1 + tax)

print(" ********************* String Handle - Not fstring *********************")
# case 1 place holder codes %s string, %d integer %f float %x hex
#print("Name : %s, Age : %s" % (name, age))
#print("Name : %s, Age : %d" % (name, age))
#print("Name : %s, Tax : %f" % (name, tax))
# case 2 convert data to str
print("Name : " + name +", Age : " + str(age) + ", Name again : " + name +", Tax = " + str(tax+1)) 
# case 3 str.format()
print("Name : {}, Age : {}, Name again : {}, Tax : {}".format(name, age, name, tax+1))
# case 4 named arguments
print("Name : {n}, Age : {a}, Name again : {n}, Tax : {m}".format(n=name, a=age, m=tax+1))
# eg.
print("Double {x}: {x} + {x} = {sum_x}".format(x=5, sum_x = 5 + 5))
print("********************* String Handle - Not fstring *********************")

print("********************* String Handle - fstring *********************")
print(f"Price : ${price:,.2f} | Tax : {tax:.1%} | Total: ${total:.2f}")
## f"{variable:[fill][align][width][.precision][type]}
print(f"{age:5d}")
print('1---5----01---5----0')
print(f"{'Name':<10}{'Age':>5}") # < left align, > right align ^ center
print(f"{name:$<10}{age:->5.2f}")
print(f"{name:<10}{age:->5.2f}")
print(f"{name:<10}{age:->5d}")
print(f"{name:<10}{age:->10.2f}")
print(f"{name:<<10s}{age:->10.2f}{' ':$<10}")
print(f"{'Apple':^10}")

print(f"{42:05}")
print(f"{42:0<5}")
print(f"{1234567:,}")
#print(f"{42:5b}")   # binary value
#print(f"{42:5o}")   # octal value
#print(f"{42:5x}")   # hex value
print("*********************** String Handle - fstring ****************************")

print("*********************** Truthy value or falsy value ****************************")
#print(True, False, type(True))
#print(False == 0)
#x = True and 2 and [1] and {0} and -1.0 and "hello" # truthy value
#print(x)
#y = False or 0 or [] or {} or None or 0.00 or ' '    # falsy value
#print(y)
#print(print(" "))
#==========================================
default_city = 'kw'
city = ''
city = city or print("please input city") or default_city
print(city)
print("*********************** Truthy value or falsy value ****************************")


print('**************** for (break) *************************')
for i in range(6):
    if i == 4:
        break
    for j in range(5):
        print(i,j)
print('**************** for (break) *************************')

print('**************** while (continue & Break) *************************')
x = 5
while x > 0:
#while True:
      print(x)
      if x == 4:
         x = x - 1
         continue
      print("hello")
      if x == 3:
         break
      x = x - 1
else:
    print("normal exit of while")
print("after while")


i = 6
try:
    while i > -1:
        if i == 3:
            raise
        print(i)
        i = i - 1
except ValueError:
    print('Divide By Zero Error')
except:
    print("I stop the program")   
print('**************** while *************************')

print("**************** assertion error ******************")
''' assert expression
=> if not expression:
      raise AssertionError
      
assert exp1, exp2
=> if not exp1:
      raise AssertionError(exp2)
'''
def a():
    print("function a")
    return False
try:    #https://glot.io/snippets/hhrnbqy42s
    x = 1
    y = x + 1
    if y == 2:
        assert a(), 'assertion error'
except AssertionError as msg:
    print(msg)
print("**************** assertion error ******************")


print('******* list *********')
a = [1,2,3]
a[0] = 9
a.append(4)
print(a)
a.insert(2, 5)
print(a)
c = a[::]
d = a.copy()
print(c)
print(d)
del a[0]
print (a)
a.remove(2)
print (a)
print(1 in a)

print('count 4 and index 4', a.count(4), a.index(4))

a.sort(reverse=True) # change original list
print(a)
b = sorted(a, reverse=False)
print(a)
print(b)

name = ["john", "ann", "mary", "peter", ["ryan", 1], 2, 3, [True, 0,0,9, "hello"]]
print(name, id(name), type(name))
print(name[0], name[4])

a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
print(a[10], a[-4])
b=slice(0,7,1) # start, end-1, step
print(type(b))
print(a[b], a[0:7:1])
print(a[b], a[0:15:7])
print(a[-1:0:-4])
print(a[15:0:-4])
print('******* list *********')

print('******* tuple *********')
a = (1,2,3)
b = list(a)
print(b)
b.append(4)
b = tuple(b)
print(b)
c = b[::]
print(c)
print(1 in a)
e = sorted(b,reverse=True)
print('tuple a - original sort : ', b)
print('list b - after sort with reverse true : ', e)
print('******* tuple *********')


print('******* set *********')
a = {1,2,3}
print(a)
a.add(4)
print(a)
a.update({5,6})
print(a)
b = a.copy()
print(b)
print(1 in a)

d = {"name" : "john",
     "age": 10,
     "gender" : "male"
     }
del d["gender"]
print(d)
d["name"] = "peter"
print(d)
d["mame"] = "prince building"
print(d)
print(d.keys())
for i in d.keys():
    print(i)
print(d.values())
print(d.items())

test1 = [{'name':'peter', 'age':11}, {'name':'john','age':12}]
print(test1[1].get('name'))
print(test1[1].get('age'))
print(test1[1].get('xxx'))
print(test1[1].get('xxx', False))



print('******* set *********')

print("********************** ANOTHER ****************************")
print(len("1234  "))
print(f"{checknum('2')[1]:<20.2f}".strip() + ' abc')


a = {1,2,3}
b = {4,2,3}
c = a | b
c = a.union(b)
d = a & b
d = a.intersection(b)
e = a - b
e = a.difference(b)
f = a ^ b
print (c)
print (d)
print (e)
print (f)


a = '1234567'
print(list(a))
print([*a])
print({*a})    #unordered set
b = [*a]
print(b)

# Check Function call 
print("*************************** Funciton call***************************")
def a(x,y,z=1):
    result = x + y + z
    print(f"function a result : {result}")
    print("x:",x," y:",y," z:",z)
    print(f"x: {x}, y: {y}, z: {z}")
    return result
print(a(1,2))
result = a(y=4,z=5,x=6) + a(7,8,9)
print(result)
#print(globals())


x = 1
def a():
    print("hello a")
a()
# case 1 import module as label
import dio as d
import dio as c
print("aaaaaaaaaaaaaa")
d.a()
c.a()
print("aaaaaaaaaaaaaa")
print(x+ d.x + d._x)
# case 2 from module import *
from dio import * # x = 11 def a()
a()
print(x, x_y)
#print(_x)
#print(globals())
# case 3 from module import selected items
from tria import a, _x
a()
print(_x, x)


print("************* pi, sqrt(9) ***********************************")
from math import pi, sqrt
print(pi, sqrt(9))
print("************* pi, sqrt(9) ***********************************")

#x = 1  # global variable
#def a():
#    #global x
#    x = 2
#    #x = x + 10 # local variable
#    print(x)
#    print(type(x))
#a()
#print(x)
#print(pi)


def outer():
    value = 41    # local
    def getter():
        #global value
        a = value + 1
        #value = value + 1
        print('a is ' + str(a))
        return a
    return getter

value = 43
try:
    print("******************** print outer ************************")
    print(outer())
    print("******************** print outer ************************")
    print("******************** print outer return get_value ************************")
    get_value = outer()  # get the closure
    
    print(get_value())   # access value outside
    print(value)
    print("******************** print outer return get_value ************************")
except Exception as e:
    print("Error:", e)


print("*************************** Funciton call***************************")
INFO