黑马程序员技术交流社区

标题: 分享一些python有趣的代码 [打印本页]

作者: LeeSsung    时间: 2018-5-21 18:43
标题: 分享一些python有趣的代码
1、导入模块命令为:
import 模块名称
例如 导入随机数模块
          import random  
后面的括号表示生成1-500之间的随机数
          rnd = random.randint(1,500)
在初学python的教程当中会经常使用import random来进行代码的编写,
所以大家可以好好的记录下来哦!!!

2、简单爬虫代码

很多人在提到python的时候就会想到爬虫,确实,python语言在做爬虫方面具有得天独厚的优势,python语言在代码编写上有较于其他语言的简单、快捷。如下简单的六行代码就可以爬取一些简单的数据。
import requests
from lxml import html
url='https://movie.douban.com/' #需要爬数据的网址
page=requests.Session().get(url)
tree=html.fromstring(page.text)
result=tree.xpath('//td[@class="title"]//a/text()')
是不是觉得python做爬虫很容易啊?

3、利用python来解决一些有趣的数学问题

  例1

题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
    程序分析:兔子的规律为数列1,1,2,3,5,8,13,21....
f1 = 1
f2 = 1for i in range(1,22):    print '%12ld %12ld' % (f1,f2),    if (i % 3) == 0:        print ''    f1 = f1 + f2    f2 = f1 + f2
以上运算结果为
1           1            2           3            5           8
          13          21           34          55           89         144
         233         377          610         987         1597        2584
        4181        6765        10946       17711        28657       46368
       75025      121393       196418      317811       514229      832040
     1346269     2178309      3524578     5702887      9227465    14930352
    24157817    39088169     63245986   102334155    165580141   267914296


3、编写input()和output()函数输入,输出5个学生的数据记录

student = []for i in range(5):    student.append(['','',[]]) def input_stu(stu):    for i in range(N):        stu[0] = raw_input('input student num:\n')        stu[1] = raw_input('input student name:\n')        for j in range(3):            stu[2].append(int(raw_input('score:\n'))) def output_stu(stu):    for i in range(N):        print '%-6s%-10s' % ( stu[0],stu[1] )        for j in range(3):            print '%-8d' % stu[2][j] if __name__ == '__main__':    input_stu(student)    print student    output_stu(student)


输出结果
input student num:2
input student name:
aaa
score:89
score:98
score:67
input student num:
bbb
input student name:
ccc
score:87
score:45
score:68
input student num:
ddd
input student name:
eee
score:56
score:78
score:56[['2', 'aaa', [89, 98, 67]], ['bbb', 'ccc', [87, 45, 68]], ['ddd', 'eee', [56, 78, 56]], ['', '', []], ['', '', []]]2     aaa       89      98      67      
bbb   ccc       87      45      68      
ddd   eee       56      78      56   
  








欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2