def checknum(passnum):
try:
a = float(passnum)
return True, a
except TypeError as msg:
print(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)
result = calc(a, b, c)[1]
if result != False:
del l[:2]
l[0] = result
else:
break
print('result : ', result)
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 = 49.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))
# case 3 str.format()
print("Name : {}, Age : {}, Name again : {}, Tax : {}".format(name, age, name, tax))
# case 4 named arguments
print("Name : {n}, Age : {a}, Name again : {n}, Tax : {m}".format(n=name, a=age, m=tax))
# 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 *************************')
for i in range(6):
if i == 4:
break
for j in range(5):
print(i,j)
print('**************** for *************************')
print('**************** while *************************')
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('******* 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('******* 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}) #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()
d.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)
from math import pi, sqrt
print(pi, sqrt(9))
from math import pi
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)
print("*************************** Funciton call***************************")
x = 11
_x = 10
x_y = 20
def a():
print("dio's function a")
x = 1
_x = 10
def a():
print("tria's function a")