Example #1
0
def fib2(n):  # Write fibonacci series upto n
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a + b
    return result

    import fibo
    fibo.fib(1000)
    fibo.fib2(100)
    fib = fibo.fib
Example #2
0
def test26(): # module
    import fibo  # lookup file 'fibo.py'
    print(fibo.fib(10))
    print(fibo.fib2(10))    
    print(dir(fibo))

    fibo._ver_ = 2.0

    '''
    print(fibo.__builtins__
        , fibo.__cached__
        , fibo.__doc__        
        , fibo.__file__        
        , fibo.__loader__        
        , fibo.__name__        
        , fibo.__package__        
        , fibo.__spec__
        )
    '''

    print(fibo.__name__,     fibo.__cached__, fibo.__doc__, fibo.__file__, fibo.__loader__, fibo.__package__)
    print(fibo.__spec__, fibo._ver_)

    import builtins

    print(dir(builtins))
Example #3
0
def test():
    """test"""
    number = int(input("Please enter an integer: "))

    if number < 0:
        number = 0
        print('Negative changed to zero')
    elif number == 0:
        print('Zero')
    elif number == 1:
        print('Single')
    else:
        print('More')

    words = ['cat', 'window', 'defenestrate']
    for word in words:
        print(word, len(word))

    for number in range(2, 10):
        for ximp in range(2, number):
            if number % ximp == 0:
                print(number, 'equals', ximp, '*', number / ximp)
                break
        else:
            print(number, 'is a prime number')

    fibo.fib(2000)

    f100 = fibo.fib2(100)
    print(f100)
Example #4
0
def test_fib_type():
    result_10 = fibo.fib2(10)
    expected_result = [0, 1, 1, 2, 3, 5, 8]
    assert type(result_10) == list


#test_fibo_10()
#test_fibo_0()
#test_fibo_10()
#result_10 = fibo.fib2(10)
#print(result_10)

#result_0 = fibo.fib2(0)
#print(result_0)
Example #5
0
    def mathStuff(self):
        print(math.sqrt(25))
        print(math.pi)

        # 2 radians = 114.59 degrees
        print(math.degrees(2))

        # 60 degrees = 1.04 radians
        print(math.radians(60))

        # Sine of 2 radians, Cosine of 0.5 radians, Tangent of 0.23 radians
        print(math.sin(2))
        print(math.cos(.5))
        print(math.tan(.23))

        print(math.factorial(4))

        # random int between 0 and 5
        print(random.randint(0,5))

        # random floating point number between 0 and 1
        print(random.random())

        # random number between 0 and 100
        print(random.random() * 100)

        List = [1,4,True,800,"python",27,"hello"]

        # random element from a set such a list is chosen
        print(random.choice(List))

        # returns number of seconds since Unix Epoch, Jan 1st 1970
        print(time.time())

        # Converts a number of seconds to a date object
        print(date.fromtimestamp(454554))

        # Using modules to do fib sequence, first writing then returning a list.
        fibo.fib(100)
        print(fibo.fib2(100))
Example #6
0
import fibo

fibo.fib(1000)

print fibo.fib2(100)

print fibo.__name__

Example #7
0
import fibo

print (fibo.fib(2000))




#enumerate returns each item as a tupell


for i, n in enumerate(fibo.fib2(1000)):


    print("{0}: {1}".format(i,n,))

    #The {0} and {1} are indexes of the enumerate values that i had place in the format method. {2} is going to print i



#take ninthe fibo number and divide it by the eigth
"""def nth_quot(n):
    fibos = []
    for i, x in enumerate(fibo.fib2(1000000000)):
        fibos.append(x)
    answer = fibos[n-1] / fibos[n-2]
    return answer

print (nth_quot(9))"""


def nth_quot2(n):
Example #8
0
# import fibo
#
# fibo.fib(100)
#
# print(fibo.fib2(100))

from fibo import fib,fib2

fib(100)

print(fib2(200))
Example #9
0
import sys
from fibo import fib, fib2

if __name__ == '__main__':
    n = 50
    print("Fibonacci numbers up to ", n)
    fib(n)
    m = 30
    print("Fibonacci numbers up to ", m, " in a list")
    print(fib2(m))
Example #10
0
def test_fibo_3():
    result_0 = fibo.fib2(0)
    assert type(result_0) == list
Example #11
0
# -*- coding:utf-8 -*-

import builtins
import fibo

result1 = fibo.fib(1000)
result2 = fibo.fib2(100)
print(result1)
print(result2)
print(dir(fibo))
print(dir(builtins))

# rw file

#with open('workfile.txt') as f:
#    read_data = f.read()
f = open('workfile.txt')
for line in f:
    print(line, end='')
# Sobre modulos
print()
print(" Modulos")
print("-"*20)
print('\n'*2)


print("__name__: ", __name__)

import fibo
print("fib0.__name__ ", fibo.__name__)
 
print("fibo.fib(10000)", end='\t\t')
fibo.fib(10000)
print("fibo.fib2(10000) : ", fibo.fib2(10000))

# Se podria asigna un nombre local a la funcion
print()
myfib2 = fibo.fib2
print(myfib2(100))

# Cada modulo define su propio espacio de nombres

print("titulo:", fibo.titulo)
fibo.titulo= "Fibonnacci functions"
print("titulo:", fibo.titulo)

# Si importamos funciones concretas, se anyaden al espacio de nombres local.

from calcu import suma, resta, suma2
Example #13
0
#!/usr/bin/python

import fibo

fibo.fib(1000);
print fibo.fib2(1000);

# The dir function is used to find out what symbols a module defines.
print dir(fibo);
import fibo

fibo.fib(1000)
print 'done'

rFib100 = fibo.fib2(100)
print rFib100

if __name__ == '__main__':
    pass
Example #15
0
from fibo import fib, fib2
######################################
#
#     python modules
#
#
#   fibo 模块调用
#
#
#####################################

#fibo.fib(1000)
fib(1000)

# print "\n", fibo.fib2(1000)
print "\n", fib2(1000)

# fib = fibo.fib

fib = fib

fib(500)

# print "\n", fibo.__author__

# 6.1.1. Executing modules as scripts

# python fibo.py <arguments>

if __author__ == 'kyrin [email protected]':
    import fibo
Example #16
0
#!/usr/bin/python
import fibo

if __name__ == '__main__':
	fibo.fib(10)
	ls = fibo.fib2(10)
	print
	print ls
Example #17
0
import fibo
def fib(n):
	a,b = 0,1
	while b < n:
		print b
		a, b = b, a + b

def fib2(n):
	result = []
	a, b = 0, 1
	while b < n:
		result.append(b)
		a, b = b, a + b
	return result
# When you run this in terminal, at first import fibo module.
# or import text editor
fib = fibo.fib(20)
print  fibo.fib2(300)

 print fib

Example #18
0
'''
Created on 2020年2月22日
@author: Percy
@summary: 测试导入斐波那契数列模块
'''
'''
import fibo
fibo.fib(100)
#fibo.fib2(100)
'''
from fibo import fib2, fib
fib(100)
fib2(100)
'''
import using_name
'''
#print(fibo.__name__)
print(__name__)
Example #19
0
import fibo

fibo.fib(5)

print(fibo.fib2(4))
Example #20
0
__author__ = 'fnxuser'
import fibo
import sys
import builtins

fibo.fib(1000)
k = fibo.fib2(int(sys.argv[1]))
print("k is", k)
print(sys.platform)
print("####################\nsys.path")
for p in sys.path:
    print(p)
print("####################\ndir(sys)")
for d in dir(sys):
    print(d)
print("####################\nbuiltins")
for b in dir(builtins):
    print(b)
Example #21
0
from fibo import fib, fib2
import fibo2
print('fib:', end=' ')
fib(100)
print('fib2:', fib2(100))
Example #22
0
    def privmsg(self, user, channel, msg): # What happens when bot gets a message
        self.count = self.count + 1
        swag = user.split('!')
        user = user.split('!', 1)[0] # Turn user!ident@host into nickname
        print("%s:<%s> %s" % (channel, user, msg)) # Show the message in console
        capsIntact = msg
        if channel == self.nickname: # Check if it's a private message
            pm = 1 
        else:
            pm = 0
#            append(channel, user, msg)
            
        msg = msg.lower()
        if swag[1].lower() in self.opersh or channel.lower() == "#dino": # if the user is in the oper list
            admin = 1 
        else: 
            admin = 0
        
        if channel == "#thegrammarnaziboners":
            tstchan = 1
        else:
            tstchan = 0
            
        insult_ = True
        fibo_ = True
        choose_ = True
        dict_ = True
        wiki_ = True
        tz_ = True
        wz_ = True
        rule_ = True
        convert_ = True
        flist = {'insult': insult_, 'fibo': fibo_, 'choose': choose_, 'dict': dict_, 'wiki': wiki_, 'wz': wz_,  'tz': tz_, 'rule': rule_, 'convert': convert_}

        
        if msg.startswith("~die"): 
            try:
                if admin == 1:                    
                    if user.lower() in self.azi:
                        print "Killed by %s" % user
                        reactor.stop()
                    else:
                        self.notice(user, "Not amused")
                        print("%s attempted to kill me!")
            except:
                self.notice(user, "You are not authorized to perform this command.")
                print("%s attempted to kill me!" % user)
        elif msg.startswith("~set ") and swag.lower() == "*****@*****.**":
#            self.sendLine("MODE %s +B %s" % (self.nickname, self.nickname))
            self.mode(self.nickname, True, 'B', limit=None, user=self.nickname, mask=None)
        elif msg.startswith("~stop") and admin == 1:
            self.quit()
        elif msg.startswith("~id") and (admin == 1 or user.lower == "Kojiro"):
            self.msg("Nickserv", "identify hamsterbot %s" % self.password)
        elif msg.startswith("~ghost ") and admin == 1:
            msg = msg.split()
            self.msg("Nickserv", "ghost %s swagonball" % msg[1])
        elif msg.startswith("~donut") and admin == 1:
            msg = msg.split(' ') 
            try:
                if msg[1].isdigit(): #hopefully if i use a number it'll join that chan
                    i = int(msg[1]) 
                    chan = self.chanlist[i]
                    self.join(chan) #why doesnt this work nvm it does
                elif msg[1] == "joinall" or msg[1] == "all":
                    for item in self.chanlist:
                         self.join(item)
                else:
                    self.join(msg[1])
            except:
                if admin != 1:
                    self.notice(user, "You are not authorized to perform this command.")
                else:
                    self.say(channel, "-_-")
        elif msg.startswith("~bye"): 
            try:
                if admin == 1:
                    self.part(channel)
            except:
                self.notice(user, "You are not authorized to perform 	this command.")
                print("%s attempted to use command ~bye." % user)
        elif msg.startswith("~nick"): 
            try:
                if admin == 1:
                    msg = msg.split(' ')
                    self.setNick(msg[1])
            except:
                self.notice(user, "You are not authorized to perform this command.")
                print("%s tried to change my nick" % user)
        elif msg.startswith("~toggle ") and admin == 1:
            msg = msg.split()
            if len(msg) == 3:
                if flist.has_key(msg[1]):
                    funct = msg[1].strip()
                    if msg[2].strip() == "on" or msg[2] == '1':
                        flist[funct] = True
                    elif msg[2].strip() == 'off' or msg[2] == '0':
                        flist[funct] = False             
                    elif msg[2] == 'not':
                        flist[funct] = not flist[funct]
                    else:
                        self.notice(user, "Values accepted: on/off or 1/0")
                else:
                    self.notice(user, "No function found with that name or function may not be switched on/off")
            elif len(msg) == 2:
                if msg[1] == 'help':
                    self.notice(user, "The following functions may be switched on/off: insult, choose, convert, dict, fibo, rule, tz, wz, wiki")
                elif msg[1] == 'is_on':
                    is_on = []
                    for key, value in flist.iteritems():                    
                        if value == True:
                            is_on.append(key)
                    self.notice(user, "The following functions are on: %r" % is_on)
            else:
                self.notice(user, "Toggle takes 2 arguments. Do ~toggle help for functions that may be toggled on/off")
                
        elif msg.startswith("~say ") and admin == 1:
            msg = msg[5:]
            self.say(channel, msg)
        elif msg.startswith("~note ") and (swag[1].lower()=="*****@*****.**"):
            msg = msg[6:]
#           bs.notes(str(msg))
            self.notice(user, notes(str(msg)))
        elif msg.startswith(":prefixes "):
            msg = msg[10:]
            self.say(channel, whattodo(msg, user))
            
        elif msg.startswith(".insult ") and insult_ == True:
            msg = msg.split(' ')
            #nick = msg[1]                
            try:
                if msg[1].lower() in self.azi:
                    self.say(channel, random.choice(azi_insults))
                elif msg[1].lower() == "?roulette":
                    self.say(channel, "%s, %s" % (user, random.choice(insults)))
                else:
                    insult = "%s, %s" % (msg[1], random.choice(insults))
                    self.say(channel, insult)
            except IndexError:
                self.say(channel, random.choice(insults))
        elif msg.startswith(".inslut") and flist['insult'] == True:
            msg = msg.split(' ')
            insult = "%s, %s" % (user, random.choice(insults))
            self.say(channel, insult)
        elif msg.startswith(".halp") or msg.startswith(".help"):
            try:
                if admin == 1:
                    self.notice(user, "Commands: .help, .insult <user>, .fibo, .convert <conversion> <numbers>, .gay, .rule <1-47>, .choose <option1, option2,...>, .dict <query>")
                    self.notice(user, "Restricted commands: ~die, ~bye, ~donut <channel>, ~nick <newnick>")
            except:
                    self.notice(user, "Commands: .help, .about, .insult <user>, .fibo, .convert <conversion> <numbers>")
#       elif msg.startswith("~~"):
#           msg = msg.strip("~~")
#           exec(msg)
        elif msg.startswith(".choose ") and flist['choose'] == True:
            msg = msg[8:]
#           re.sub("or*", '', msg)
            
            msg = msg.split(",")
            msg = random.choice(msg)
            words = msg.split(' ')
            if words[0] == 'or' and len(words) > 1:
                msg = msg.replace('or ','')
            self.msg(channel, "%s: %s" % (user, msg.strip()))
#        elif msg.startswith(".last"):
#            msg = msg[5:]
#            list = last(channel, msg)
#            for item in list:
#                self.msg(user, item)
        elif msg.startswith(".wiki ") and flist['wiki'] == True: #broken wikipedia feature
            msg = msg[6:]
            msg = msg.replace(' ', '_')
            self.msg(channel, str(wiki(str(msg))))
        elif msg.startswith(".dict ") and flist['dict'] == True: #dictionary feature
 #           msg = capsIntact
            msg = msg[6:]
            self.msg(channel, dict(msg))
        elif msg.startswith(".tz ") and flist['tz'] == True: #timezone feature
            msg = msg[4:]
            self.msg(channel, tz(msg))
        elif msg.startswith(".wz ") and flist['wz'] == True: #weatherbot feature
            msg = msg[4:]
            self.msg(channel, wz(msg))
        elif msg.startswith(".gay"):
            self.msg(channel, "%s: http://blog.okcupid.com/index.php/gay-sex-vs-straight-sex" % user)
        elif msg.startswith(".rule ") and flist['rule'] == True:
            msg = msg.split()
            self.msg(channel, rules((msg[1].strip())))
        elif msg.startswith(".fibo") and flist['fibo'] == True: 
            msg = msg.split(' ')
            num = msg[1]
            i = fib2(int(num))
            self.msg(channel, str(i))
        elif msg.startswith(".convert") and flist['convert'] == True: 
            msg = msg.split(' ')
            if convert(msg).startswith('S') or convert(msg).startswith('N'):
                if '::' in convert(msg):
                    resp = convert(msg).split('::')
                    self.notice(user, resp[0])
                    self.notice(user, resp[1])
                else:
                    self.notice(user, convert(msg))
            elif pm == 1:
                self.notice(user, convert(msg))
            else:
                self.msg(channel, convert(msg))
Example #23
0
def test_fibo_0():
    result_0 = fibo.fib2(0)
    expected_result = []
    assert result_0 == expected_result
Example #24
0
def test_fibo_5():
    result = fibo.fib2(5)
    expected_result = [0, 1, 1, 2, 3]
    assert result == expected_result
Example #25
0
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 19 15:36:58 2018

@author: shurastogi
"""

import fibo

if __name__ == "__main__":
    print("inside main")
    fibo.fib2(1000)
else:
    print("not in main")
Example #26
0
        print(b)
        a,b=b,a+b
def fib2(n): #return fibonacci series up to n
    result = []
    a,b = 0,1
    while b<n:
        result.append(b)
        a,b=b,a+b
    return result
"""
import fibo  #Nhập module

fibo.fib(200)
fi = fibo.fib  # Có thể gán vào một tên cục bộ
fi(500)
print(list(fibo.fib2(100)))

###6.1 Bàn thêm về module
# Module có thể nhập các module khác.Thông thường ta hay để tất cả các lệnh import ở đầu một module
# Cách khác: có thể lấy tùy chọn method từ một module.
print("-" * 50)
from fibo import fib, fib2

fib(50)

#hoặc nhập tất cả method trừ method bắt đầu bằng dấu gạch chân (_)
from fibo import *

fib(10)

###6.1.1 Đường dẫn tìm module
Example #27
0
def test27(): # module 2
    from fibo import fib, fib2
    print(fib(10))
    print(fib2(10))    
Example #28
0
    pass
    # utils.showMsg(os.uname())

print("System path:")
for p in sys.path:
    print(p)

s1, s2, s3 = '', 'Trondheim', 'Hammer Dance'
non_null = s1 or s2 or s3
print(non_null)

a = 4
b = 5
c = 5
print(a < b == c)
print(a and (not b) and c)

print((1, 2, 3) < (1, 2, 4))
print([1, 4, 3] < [1, 2, 4])

print('Pascal' < 'Python')

fibo.fib(10)
x = fibo.fib2(10)
y = fibo.fib2(20)
print(x, y)
print(fibo.__name__)

# Show defined vars and modules members
# print(dir())
Example #29
0
import fibo
fibo.fib(30)
fibo.fib2(60)
from fibo import fib, fib2

array = []
a = fib(100)
b = fib2(200)
print("array append list:", array.append(a))
import sys
import builtins
fibo_function = []
fibo_function.append(dir(builtins))


def Display_Array(Array_var):
    for i in Array_var:
        print("array[]:", i)


Display_Array(fibo_function)
print("dir functions:\n", fibo_function, end=" ")
print("\nfunctions of sys:\n", dir(sys), end=" ")
print("\nfunctions of builtins:\n", dir(builtins), end=" ")
Example #30
0
#!/usr/bin/env python

from fibo import fib

print fib(1000)

from fibo import fib2

print fib2(1000)
Example #31
0
#! /usr/bin/python


from fibo import fib, fib2


print (fib(100))
print (fib2(100))
 def testFibo(self):
     rFib100 = fibo.fib2(100)
     self.assertEquals([1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89], rFib100)
Example #33
0
# 导入一个模块
import support
support.print_func("Bob")

import fibo
fibo.fib(10)
print(fibo.fib2(10))

# 内置的函数 dir() 可以找到模块内定义的所有名称。
print(dir(fibo))

# 导入一个模块的所有名字(变量和方法),但不包括由单一下划线(_)开头的名字
from fibo import *
fib(10)
print(fib2(10))

# 按需求导入一个模块的某几个名字(变量和方法)
from fibo import fib, fib2
fib(10)
print(fib2(10))

# 每个模块都有一个__name__属性,当其值是'__main__'时,表明该模块自身在运行,否则是被引入
if __name__ == '__main__':
    print('程序本身在运行')
else:
    print('我来自另一个模块')

# 导入一个包及其子包
import package
package.sub_package_a.module_a.func_a()
package.sub_package_b.module_b.func_b()
Example #34
0
# coding: utf-8
import fibo

sum = 0

a = fibo.fib2(4000000)
for i in a:
     if i % 2 == 0:
         sum += i

		 
sum

Example #35
0
a                                  # unique letters in a
a - b                              # letters in a but not in b
a | b                              # letters in either a or b
a & b                              # letters in both a and b
a ^ b                              # letters in a or b but not both
#%%

###############################################################################
# Chapter 6. Modules

#%%
# change the current working dir
# import os
# os.chdir("~/project-hg/python/phinarypython")
import fibo
fibo.fib2(100)
fibo.__name__
#%%

###
# 6.1. More on Modules
###
#%%
from fibo import fib
fib(500)
#%%
# Reload a module after changes
#%%
import imp; imp.reload(fibo)
#%%
Example #36
0
#!/usr/bin/env python3

# import fibo: Python looks for fibo.py in every directory of sys.path
# sys.path is initialised with these locations:
#     Current directory
#     PYTHONPATH
#     installation-dependent default
import fibo

print(dir(fibo))
fibo.fib(1000)
x = fibo.fib2(400)
print(x)
Example #37
0
#Module in Python
#把定义放在文件中,为了一些脚本或者交互式的解释器实例使用,这个文件被称为模块
#模块是一个包含你自定义的函数和变量的文件,后缀名是.py
import sys
print("command line args is :");
for i in sys.argv:
        print(i);

print("Python path is ", sys.path);

import fibo

fibo.fib(100);#fib(100) will lead to an error, using mudule name prefix
print(fibo.fib2(100));

#module name ===> fibo.__name__
print("fibo module name is ", fibo.__name__);

#if you use a module frequently, just assign a variable intead of fibo.fib
wtf = fibo.fib2;
print("wtf(100) is :", wtf(100));

#模块除了方法定义以外可以包括可执行的代码,这些代码一般用来初始化这个模块
#这些代码在第一次导入时才会被执行,每一个模块都有各自独立的符号表,在模块内部为所有的函数当做全局
#符号表来使用

from fibo import fib, fib2#这种方式把所有的名字都导入进来
print("from fibo import fib, fib2");
fib(100);

#__name__属性
Example #38
0
import fibo
print("-----------------------")
fibo.fib(500)
print("-----------------------")
r = fibo.fib2(100)
print(r)
Example #39
0
def main():
    # 사용방법: 모듈명, 함수명
    val = fibo.fib2(10)
    print(val)
Example #40
0
#!/usr/bin/python3
# Filename: test_fib.py

from fibo import fib, fib2

fib(10)
result = fib2(10)
print(result)

for num in result:
    print(num)

for num in result:
    print(num, end=' ')
import fibo

fibo.fib(1000)

fibList = fibo.fib2(100)
print " "

print fibList

# can assign the function name to a variable to make it easier to call
f = fibo.fib2
print f(100)


# find out the names that a module defines
print dir(fibo)
# -*- coding: utf-8 -*-
"""
Created on Mon Feb  5 13:57:49 2018

@author: AnthonyN
"""

import fibo  # Import library

fibo.fib(1000)  # To access the fib function in the fibo module
fibo.fib2(100)  # To access the fib2 function in the fibo module
fibo.__name__

fib = fibo.fib  # assign a local name for a function
fib(500)
Example #43
0
import fibo

list1 = []
fibo.fib(200)
list1 = fibo.fib2(10)
print list1
Example #44
0
def test_fib_type():
    result = fibo.fib2(0)

    assert type(result) == list
Example #45
0
def test_fibo_10():
    result_10 = fibo.fib2(10)
    expected_result = [0, 1, 1, 2, 3, 5, 8]
    assert result_10 == expected_result
Example #46
0
import fibo

print("#######################################")
fibo.fib(1000)
print(fibo.fib2(500))

print(fibo.__name__)

fib = fibo.fib
fib(100)
Example #47
0
import fibo

#fibo.fib(1000)
print ''

from fibo import fib, fib2

fib(500)
print ''
fib2(500)

Example #48
0
'''
Created on 2013/4/8

@author: kim.hsiao
'''

# it's a file for fibo testing

import fibo  # import fibo which name is fibo.py

print fibo.fib(1000)  # import from fibo.py and execute the module within

print fibo.fib2(100)  # import from fibo.py and execute its module within

print fibo.__name__  # show the module name
Example #49
0
# -*- coding: utf-8 -*-

# file name import
import fibo

# method import
print(fibo.fib(1000))

# module name
print(fibo.__name__)

# method import
from fibo import fib, fib2
# from fibo import *
# from fibo import fib as fibonacci
print(fib(1000))
print(fib2(1000))
Example #50
0
def main():
    print (fibo.fib2(10))
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 11 13:00:56 2020

@author: demir
"""

import fibo
import sys

fibo.fib(5)

print(fibo.fib2(4))

print("filename:")
print(sys.argv[0])

print(
    fibo.fib2(int(sys.argv[1]))
)  # to give arg on Spyder, use Ctrl+F6 and select "Command Line Options". Fill the box next to it. !It takes as STRING!
Example #52
0
#!/usr/bin/env python

import fibo

fibo.fib(5)
print fibo.fib2(10)
Example #53
0
import fibo
fibo.fib(1000)
print(fibo.fib2(100))
print(fibo.__name__)
# 导入模块的其他方式
from fibo import *  #  * 导入模块的全部关键字
fib(500)
print(fib2(1000))

import fibo as fib  # 导入模块里的fib关键字
fib.fib(500)

from fibo import fib as fibonacci  # 导入fib关键字,用fibonacci代替
fibonacci(500)
Example #54
0
def cheeseshop(kind, *arguments, **keywords): # *arg : tuple    **arg : dict
cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper='Michael Palin',
           client="John Cleese",
           sketch="Cheese Shop Sketch")
arg1=[1,2,3]
arg2={1:2, 2:3, 3:4}
cheeseshop(1, *arg1, **arg2)

pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])

def my_function():
    """Do nothing, but document it.

    No, really, it doesn't do anything.
    """
    pass

print my_function.__doc__

#= input output ================================================
# print
str()
repr()
for x in range(1, 11):
    print repr(x).rjust(2), repr(x*x).rjust(3),
    # Note trailing comma on previous line
    print repr(x*x*x).rjust(4)
for x in range(1,11):
    print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)

>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'

print 'We are the {} who say "{}!"'.format('knights', 'Ni')
print 'The value of PI is approximately %5.3f.' % math.pi


# file
f = open('workfile', 'w')
f.read(size)
f.read()
f.readline()
for line in f:
    print line,
list(f)
f.readlines()

f.write('This is a test\n')
value = ('the answer', 42)
s = str(value)
f.write(s)

f = open('workfile', 'r+')
f.write('0123456789abcdef')
f.seek(5)     # Go to the 6th byte in the file
f.read(1)
f.seek(-3, 2) # Go to the 3rd byte before the end
f.read(1)
f.close()

with open('workfile', 'r') as f:
    read_data = f.read()
f.closed

# json
>>> json.dumps([1, 'simple', 'list'])
'[1, "simple", "list"]'
#= exception ================================================
import sys
try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise
else:
    f.close()

try:
    this_fails()
except ZeroDivisionError as detail:
    print 'Handling run-time error:', detail

class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)
try:
    raise MyError(2*2)
except MyError as e:
    print 'My exception occurred, value:', e.value

def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print "division by zero!"
    else:
        print "result is", result
    finally:
        print "executing finally clause"
#= statements ================================================
>>> x = int(raw_input("Please enter an integer: "))
sys.argv[1:]
#= module ================================================
import fibo
fibo.fib(1000)
fibo.fib2(100)
fibo.__name__
fib = fibo.fib
fib(500)
from fibo import fib, fib2
from fibo import *
fib(500)

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

print sys.path
print dir(fibo)
print dir(sys)
print dir()
print dir(__builtin__)
#= package ================================================
sound/                          Top-level package
      __init__.py               Initialize the sound package
      formats/                  Subpackage for file format conversions
              __init__.py
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              ...