2015年6月29日 星期一

Python筆記:基本語法

Arithmetic

print int(3.14159)              #3
print type(3), type(3.14159)    #int float
print float(3)                  #3.0

#floating point number have around 15 decimal digits of accuracy
print 3.1415926535897932384626433832795028841971     #3.14159265359

#If one operand is a decimal (float), the answer is decimal
print 1.0 / 3, 5.0 / 2.0        #0.333333333333 2.5

Variables

命名方式為字母或是“_”
Dynamic
#The ones digit of a number
num = 49
tens = num // 10
ones = num % 10
print tens, ones
print 10 * tens + ones, num

Function

def triangle_area(base, height):     
    area = (1.0 / 2) * base * height 
    return area                      

a1 = triangle_area(3, 8)
print a1
def hello():
    print "Hello, world!"

hello()      
h = hello()  
print h 
Python modules - extra functions implemented outside basic Python.
import math         #access to standard math functions, e.g; trig
print math.pi   #3.14159265359

Conditions

#Return True if year is a leap year, false otherwise
def is_leap_year(year):
    if (year % 400) == 0:
        return True
    elif (year % 100) == 0:
        return False
    elif (year % 4) == 0:
        return True
    else:
        return False

year = 2012
leap_year = is_leap_year(year)
    
if leap_year:
    print year, "is a leap year"
else:
    print year, "is not a leap year"



沒有留言:

張貼留言