开始学习python

2018-08-03  本文已影响17人  潘帅次元

来源

老早就听说有python这种语言,这是知道很流行,而且,爬虫非常好写。作为曾今在爬虫中深受其害的本帅来说。是由必要研究一下python这操作。

开始学习

python™
进入start开始学习。
bala bala 一些必要前奏

然后就到了MovingToPythonFromOtherLanguages,看了下介绍文章,其实没看完。

得到信息

Python indexes and slices for a six-element list.
Indexes enumerate the elements, slices enumerate the spaces between the elements.

Index from rear:    -6  -5  -4  -3  -2  -1      a=[0,1,2,3,4,5]    a[1:]==[1,2,3,4,5]
Index from front:    0   1   2   3   4   5      len(a)==6          a[:5]==[0,1,2,3,4]
                   +---+---+---+---+---+---+    a[0]==0            a[:-2]==[0,1,2,3]
                   | a | b | c | d | e | f |    a[5]==5            a[1:2]==[1]
                   +---+---+---+---+---+---+    a[-1]==5           a[1:-1]==[1,2,3,4]
Slice from front:  :   1   2   3   4   5   :    a[-2]==4
Slice from rear:   :  -5  -4  -3  -2  -1   :
                                                b=a[:]
                                                b==[0,1,2,3,4,5] (shallow copy of a)

两个查阅目录
Python 2.4 Quick Reference
Python Module Index

python特点

编写特点

下载须知

选择对应操作系统以及系统的寻址方式:
web-based installer 是需要通过联网完成安装的
executable installer 是可执行文件(*.exe)方式安装
embeddable zip file 嵌入式版本,可以集成到其它应用中。
上面3种途径,如果有网络,选择web-based;
我的windows64版,所以选择了Windows x86-64 web-based installer

运行简单代码

把含有python.exe文件的路径添加到环境变量中。
写好如下代码:

## world.py
print("hello, world!")

## cal.py
print('Interest Calculator:')
amount = float(input('Principal amount ?'))
roi = float(input('Rate of Interest ?'))
years = int(input('Duration (no. of years) ?'))
total = (amount * pow(1 + (roi / 100) , years))
interest = total - amount
print('\nInterest = %0.2f' %interest)

控制台运行

PS D:\git\pythonTest> python .\world.py
hello, world!

PS D:\git\pythonTest> python .\cal.py
Interest Calculator:
Principal amount ?11
Rate of Interest ?0.1
Duration (no. of years) ?2

Interest = 0.02

基础学习

自动化程序,批量修改,跨平台支持,解释型语言

传参

脚本的名称以及参数都通过sys模块以字符串列表形式放在argv参数中,使用时需要导入sys模块。

_

在python 里面表示上一次的结果
在python中缩进来表示代码块indentation is Python’s way of grouping statements.

语句

 while a < 100:
   a = a + 100

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...

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

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
/**
range(5, 10)
   5, 6, 7, 8, 9

range(0, 10, 3)
   0, 3, 6, 9

range(-10, -100, -30)
  -10, -40, -70
*/


>>> print(range(10))
range(0, 10)

>>> list(range(5))
[0, 1, 2, 3, 4]

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print("Found an even number", num)
...         continue
...     print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

pass Statements

>>> while True:
...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
...

Defining Functions

方法传递方式为引用传递,不是值传递。

>>> def fib(n):    # write Fibonacci series up to n
...     """Print a Fibonacci series up to n."""
...     a, b = 0, 1
...     while a < n:
...         print(a, end=' ')
...         a, b = b, a+b
...     print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597


def ask_ok(prompt, retries=4, reminder='Please try again!'):
    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 ValueError('invalid user response')
        print(reminder)


i = 5

def f(arg=i):
    print(arg)

i = 6
f()
5


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

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


def cheeseshop(kind, *arguments, **keywords): # (*name must occur before **name.)
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])

Lambda Expressions

>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

编码格式 Intermezzo: Coding Style


上一篇 下一篇

猜你喜欢

热点阅读