In [2]:
>>> x = int(input("please input number"))


please input number42

In [3]:
>>> if x < 0:
...     x = 0
...     print("Negative changed to zero")
... elif x == 0:
...     print("Zero")
... elif x == 1:
...     print("Single")
... else: 
...     print('More')
...


More

In [4]:
>>> words = ['Cat','Dog','Windows']
>>> for w in words :
        print(w, len(w))


Cat 3
Dog 3
Windows 7

In [5]:
>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words


Out[5]:
['Windows', 'Cat', 'Dog', 'Windows']

In [6]:
>>> for i in range(10):
        print(i,end=",")


0,1,2,3,4,5,6,7,8,9,

In [13]:
>>> a = ['Mary','had','a','big','apple']
... for i in range(len(a)):
            print(i,a[i])


0 Mary
1 had
2 a
3 big
4 apple

In [14]:
>>> list(range(5))


Out[14]:
[0, 1, 2, 3, 4]

In [18]:
>>> for n in range(2,10):
        for x in range(2,n):
            if n % x == 0:
                print(n,'quals',x,'*',n//x)
                break
        else:
            print(n,'是一个质数')


2 是一个质数
3 是一个质数
4 quals 2 * 2
5 是一个质数
6 quals 2 * 3
7 是一个质数
8 quals 2 * 4
9 quals 3 * 3

In [25]:
>>> for n in range(2,10):
        if n % 2 == 0:
            print(n,'is an even number')
            continue
        print(n, 'is an odd number')


2 is an even number
3 is an odd number
4 is an even number
5 is an odd number
6 is an even number
7 is an odd number
8 is an even number
9 is an odd number

In [ ]:
>>> while True:
...    pass

In [9]:
>>> def fib(n):
    a, b = 0, 1
    while a < n:
        print(a,end=' ')
        a, b = b, a+b
    print()
>>> fib(2000)


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 

In [10]:
>>> f = fib
>>> f(200)


0 1 1 2 3 5 8 13 21 34 55 89 144 

In [11]:
>>> print(fib(0))


None

In [14]:
>>> def fib2(n):
    a, b= 0, 1
    result = []
    while a < n:
        result.append(a)
        a, b =b, a+b
    return result
>>> f100 = fib2(100)
>>> f100


Out[14]:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

In [24]:
>>> def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise OSError('uncooperative user')
        print(complaint)

In [28]:
>>> i = 5
... def f(arg=i):
        print(arg)
>>> i = 6
>>> f()


5

In [32]:
def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))


[1]
[1, 2]
[1, 2, 3]

In [37]:
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print('If you put', voltage, 'volts through it')
    print('--Lovely prumpt, the', type)
    print("--It's", state, '!' )

In [40]:
parrot(1000)
parrot(voltage=1000)
parrot(voltage=100000, action='vooooom')
parrot(action='voooooom', voltage=1000000)
parrot('a million', 'bereft of life', 'jump')
parrot('a thousand', state = 'pushing up the daisies')


-- This parrot wouldn't voom If you put 1000 volts through it
--Lovely prumpt, the Norwegian Blue
--It's a stiff !
-- This parrot wouldn't voom If you put 1000 volts through it
--Lovely prumpt, the Norwegian Blue
--It's a stiff !
-- This parrot wouldn't vooooom If you put 100000 volts through it
--Lovely prumpt, the Norwegian Blue
--It's a stiff !
-- This parrot wouldn't voooooom If you put 1000000 volts through it
--Lovely prumpt, the Norwegian Blue
--It's a stiff !
-- This parrot wouldn't jump If you put a million volts through it
--Lovely prumpt, the Norwegian Blue
--It's bereft of life !
-- This parrot wouldn't voom If you put a thousand volts through it
--Lovely prumpt, the Norwegian Blue
--It's pushing up the daisies !

In [45]:
>>> def function(a):
...     pass
...
>>> function(0, a=0)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-45-2346fc3947e2> in <module>()
      2     pass
      3 
----> 4 function(0, a=0)

TypeError: function() got multiple values for argument 'a'

In [55]:
def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    keys = sorted(keywords.keys())
    for kw in keys:
        print(kw, ":", keywords[kw])

In [58]:
cheeseshop('Limburger', "It's very runny, sir!", 
           "It's really very, VERY runny, sir!",
            shopkeeper = "Mike colin",
            client = "John kees",
            sketch = "Cheeseshop Sketch")


-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir!
It's really very, VERY runny, sir!
----------------------------------------
client : John kees
shopkeeper : Mike colin
sketch : Cheeseshop Sketch

In [59]:
def write_mutiple_items(file, separator, *args):
    file.write(separator.join(args))

In [62]:
>>> def concat(*args, sep='/'):
...     return sep.join(args)
...
>>> concat('earth','mars','moons')


Out[62]:
'earth/mars/moons'

In [65]:
>>> concat('earth','mars','moon', sep='.')


Out[65]:
'earth.mars.moon'

In [67]:
>>> list(range(4,9))


Out[67]:
[4, 5, 6, 7, 8]

In [71]:
>>> args = [3,9]
>>> list(range(*args))


Out[71]:
[3, 4, 5, 6, 7, 8]

In [73]:
>>> def parrot(voltage, state='a stiff', action='voom'):
...     print("-- This parrot wouldn't", action, end=' ')
...     print("if you put", voltage, "volts through it.", end=' ')
...     print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)


-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

In [76]:
>>> def make_incrementor(n):
...    return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
>>> f(1)


Out[76]:
43

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


Out[77]:
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

In [81]:
>>> def my_function():
...     """Do nothing, but document it.
...     fadsfdf
...     No, really, it doesn't do anything.
...     """
...     pass
...
>>> print(my_function.__doc__)


Do nothing, but document it.
    fadsfdf
    No, really, it doesn't do anything.
    

In [82]:
>>> def f(ham: str, eggs: str = 'eggs') -> str:
...     print("Annotations:", f.__annotations__)
...     print("Arguments:", ham, eggs)
...     return ham + ' and ' + eggs
...
>>> f('spam')


Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
Out[82]:
'spam and eggs'