#!/usr/bin/env python # -*- coding: UTF-8 -*- #file name: ray.py #2009-10-16, RayZ, demo cases/notes using python #第二行是用來寫中文註解 #this file can be execution if the first row has #!/usr/bin/env python. usage is #chomd 770 ray.py #./ray.py # or using $ python ray.py in command line (it is txt file) # look for Python's built in functions using Python command line # >>> import __builtin__ # >>> dir(__builtin__) def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while 1: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return 1 if ok in ('n', 'no', 'nop', 'nope'): return 0 retries = retries - 1 if retries < 0: raise IOError, 'refusenik user' print complaint def f91(a, l = []): l.append(a) return l def f92(a, l = None): if l is None: l = [] l.append(a) return l while 1: Title = "\n\ Example 10: 避開共用值\n\ Example 9: 6/49大樂透\n\ Example 8: function repeat\n\ Example 7: 質數for loop's else\n\ Example 6: range\n\ Example 5: 費氏數列\n\ Example 4: 字串\n\ Example 3: if\n\ Example 2: if\n\ Example 1: Hello\n\ 0:Quit\n\ Please enter a number: " setNo = int(raw_input(Title)) print "\n" if setNo == 10: print "function point", f91, f92 print "第一次呼叫 f91(5)=", f91(5), ",f92(1)=", f92(1) print "第二次呼叫 f91(6)=", f91(6), ",f92(2)=", f92(2) print "第三次呼叫 f91(7)=", f91(7), ",f92(3)=", f92(3) elif setNo == 9: import random l = [] for n in range(-1,5): # 5 - (-1) 個 l.append(random.randint(1,49)) print l elif setNo == 8: ask_ok('Do you really want to quit?') ask_ok('Ok, to overwrite the file?', 10) elif setNo == 7: for n in range(2, 10): for x in range(2, n): if n % x == 0: print n, 'equals', x, '*', n/x break else: # for's else, # special usage print n, 'is a prime number' elif setNo == 6: a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in range(0, len(a), 2): print i, a[i] elif setNo == 5: a, b = 0, 1 while b < 10: print b, a, b = b, a + b print "\n" elif setNo == 4: x = y = z = 0 print "x =";x print "x =",x word='Hel'+'p ' print word*5 elif setNo == 3: x = int(raw_input("Please enter a number: ")) if x<0: x = 0 print "Negative changed to zero" elif x==0: print "Zero" elif x==1: print "Single" else: print "More" elif setNo == 2: a = 5 b = 5.5 if b > a: print "b is more than a !\n" else: print "b is less than a !\n" elif setNo == 1: print "This is Python -- Hello.world!" print ("Hello.world!\n") elif setNo == 0: print "Quit Example" break else: print "Please enter a number(0~8)\n"
[參考]
[1] Python 教學文件
[2] 隨機數與隨機字符串
[3] PythonDOC
沒有留言:
張貼留言