1)产生随机数 import random def main(): number = random.randint(1,10) print 'The number is', number main() 结果:The number is 8
例2: import random def main(): for count in range(5): number = random.randint(1,100) print number main() 结果: 63 8 1 61 36
例3: import random def main(): again = 'y' while again=='y' or again=='Y': print 'Rolling the dice...' print 'Their values are:' print random.randint(1,6) print random.randint(1,6) again = raw_input('Roll them again? (y=yes): ') main()
2)函数返回值 使用return expression语句。 def main(): first_age = input('Enter your age:') second_age = input('Enter yoru best friend/'s age:') total = sum(first_age, second_age) print 'Together you are', total, 'years old.' def sum(num1,num2): result = num1+num2 return result main()
3)返回多个值 使用return expression1, expression2, etc. def get_name(): first = raw_input('Enter your first name:') last = raw_input('Enter your last name:') return first, last print get_name() 结果: Enter your first name:Mr. Enter your last name:Jack ('Mr.', 'Jack')
4)math模块 import math def main(): number = input('Enter a number: ') square_root = math.sqrt(number) print 'The square root of',number,'is',square_root main() 结果: Enter a number: 645 The square root of 645 is 25.3968501984