1/10 Python筆記(*數學運算*if-else*自定義函式def*):

數學運算:
3**2  = 3^2  = 9 ;#兩個星號就是次方
判斷條件:
If-else:
if(condition1):
    # If condition1 is true, then execute here.
elif(condition2):#   C語言中的else if
    # If condition2 is true, then execute here.
else:
    # If none of the condition is true, then execute here.
    #比較要注意的是 if,elif,else,後面接的不是括號,而是冒號:
    #coding的時候要縮排。

For example:
a = int(input("please input a : "));
#今天新學到可以利用a = int(input(“string”))來在一開始就給他一個data type
#如果沒有將資料轉型會噴bug
if (a>0):
    print("a is bigger than zero")
    # if condition1 is true, then execute here.
elif ( a == 0 ):  # C語言中的else if
    print (" a is equal to zero")
    # if condition2 is true, then execute here.
else:
    print (" a is less than zero")
# if none of the condition is true, then execute here.

Bmi program:

weight = float(input("please input your weight: "))
height = float(input("please input how tall you are: "))
height_meter = height / 100; #將身高除以100,才可得到公尺的結果
bmi = weight / (height_meter ** 2)
print("your bmi is : " + str(bmi) );
if( bmi <= 18.5):
    print("You are too thin! ");
elif( bmi >= 18.5 and bmi <= 24):
    print("You are normal ! ");
else:
    print("You are too fat ! ");
#在做完這個program後,學到兩件事,首先第一件事是在print 一個數字的時候,必須先將他的data type 改為str,像程式中第五行的部分,而這樣做只有在那一行會將型別改為string,而在下面程式碼執行時,他仍然是以一開始宣告的型態(float)為主在進行編譯,在if裡面,所謂的and (&&) or ( || ) ,在python裡面可以直接打 and“, or”,來進行編譯,實在是非常酷。

自定義函式:

  • 使用def關鍵字定義函式
    def
    函式名稱(參數1, 參數2):
  •     函式中執行的程式碼
  • Python不支援重載(Overload)#重載(Overload)就是同一個函式名稱,因為用了不同數量的變數,所以可以連續使用同一個名字,但做不同的事。



  • 輸入參數預設值
    def
    函式名稱(參數名稱=預設值):
def sayhi (name = "Toria”):#預設如果我沒有告訴你名字就是叫作Toria
    print ("hi " + name )
sayhi("Justin”);#印出Justin
sayhi();#印出Toria


  • 輸入多個不確定數量的參數
    def
    函式名稱(*參數):

def prt (*notsure):
    print (notsure);

hi = ('a','c','b',1,6,0,32.432423);

prt (hi)

這是結果:



留言

熱門文章