条件、循环、函数定义、字符串操作练习

1、注意标准库的两种导入与使用方式,建议大家采用<库名>.<函数名>的方式。

2、对前面的代码进行优化,用for,while,if,def实现:

a.用循环画五角星

import turtle
for i in range(5):
turtle.forward(200)
turtle.right(144)

b.用循环画同心圆

import turtle
turtle.color('blue')
for i in range(4):
    turtle.up()
    turtle.goto(0,-40*(i+1))
    turtle.down()
    turtle.circle(40*(i+1))

c.用while循环画太阳花

from turtle import *
color('red','yellow')
begin_fill()
while True:
    forward(250)
    left(170)
    if abs(pos())<1:
        break
end_fill()
done()

 d、用函数定义画五个五角星

import turtle
turtle.setup(600,400,0,0)
turtle.bgcolor("red")
turtle.color("yellow")
turtle.fillcolor("yellow")
def z_goto(x,y):
    turtle.up()
    turtle.goto(x,y)
    turtle.down()
def z_draw(m,n):
    turtle.begin_fill()
    for i in range(5):
        turtle.forward(m)
        turtle.left(n)
    turtle.end_fill()
    
z_goto(-270,120)
z_draw(100,-144)

z_goto(-140,150)
turtle.left(10)
z_draw(30,144)

z_goto(-100,110)
turtle.right(18)
z_draw(30,144)

z_goto(-100,60)
turtle.left(10)
z_draw(30,-144)

z_goto(-135,10)
turtle.left(10)
z_draw(30,144)

 e、用函数定义画钻石花瓣的太阳花

import turtle
turtle.color("yellow")
turtle.fillcolor("red")
turtle.begin_fill()
def draw(t):
   t.fd(80)
   t.right(45)
   t.fd(80)
   t.right(135)
for i in range(36):
    draw(turtle)
    draw(turtle)
    turtle.left(10)
turtle.end_fill()

3、字符串操作

a、输入学号,识别年级、专业、序号

sid=input("学号:")
g=sid[2:4]
p=sid[4:8]
t=sid[-2:]
print("年级:{}级".format(g))
if p=="0611":
  print("专业:网络工程")
print("序号:{}".format(t))

b、输入1-7的数字,输出对应的“星期几”

s = "星期一星期二星期三星期四星期五星期六星期日"
i = int(eval(input("请输入1-7的数字:")))
if(i>7):
  print("输入的数字为无效数字")
print(s[3*(i-1):3*i])

c、识别身份证号中的省市区、年龄、性别

mport time
provinces = {
11:'北京市',
12:'天津市',
13:'河北省',
14:'山西省',
15:'内蒙古自治区',
21:'辽宁省',
22:'吉林省',
23:'黑龙江省',
31:'上海市',
32:'江苏省',
33:'浙江省',
34:'安徽省',
35:'福建省',
36:'江西省',
37:'山东省',
41:'河南省',
42:'湖北省',
43:'湖南省',
44:'广东省',
45:'广西壮族自治区',
46:'海南省',
50:'重庆市',
51:'四川省',
52:'贵州省',
53:'云南省',
54:'西藏自治区',
61:'陕西省',
62:'甘肃省',
63:'青海省',
64:'宁夏回族自治区',
65:'新疆维吾尔自治区',
71:'台湾省',
81:'香港特别行政区',
91:'澳门特别行政区'
}
def decide(cardID):
province=cardID[0:2]
birthdayYear=cardID[6:10]
localYear=time.strftime('%Y')
age=int(localYear)-int(birthdayYear)
sex=cardID[16:17]
print("省份为:", provinces.get(int(province)))
print("年龄为:{}".format(age))
if int(sex)%2==0:
print("性别:女")
else:
print("性别,男")
cardID=input("请输入身份证号:")
decide(cardID)

d、用字符串操作生成python文档各库的网址(起始网址在这里https://docs.python.org/3.6/library/index.html)

x="https://docs.python.org/3.6/library/index"
y=".html"
add=x+y
print(add)

 

posted @ 2017-09-14 21:28  405陈素欣  阅读(187)  评论(0编辑  收藏  举报