Python学习笔记(04)

第六章 输入与输出

1.标准输出函数print()

(1)格式:print(*objects,sep=’’,end=’\n’,file=sys.stdout)

(2)参数:

<1> *objects:标识一次输出多个对象,输出多个对象需要使用逗号作为间隔符

<2> sep:间隔符,默认为一个空格

<3> end:用什么来结尾,默认\n,可替换

<4> file:需要写入的文件名

(3)例:

print(1,2,3,4,5)
#print(1 2 3 4 5)报错
print(1,2,3,4,5,sep='')
print('hello world')
print('www.baidu.com')
print('www.','baidu.','com',sep='')
for i in range(100):
    print(i,end='  ')
    if(i%10==0):   # 逢10换行
        print()
print()
str='hello'
print(str*2)
print(2*str) #*表示复制几份
print(str+'world')   # + 表示连接
# 在d:新建test文件
fp=open(r'd:\test.txt','w')  #r 去掉转义字符的功能
#  打开文件,写入
print('我爱你',file=fp)
fp.close()   # 关闭文件

(4)格式化输出

<1> 无符号八进制%o,无符号十六进制%x,无符号%u,整数%d

num1 = 10
num2 = 20
print('八进制输出:0o%o,0o%o'%(num1,num2))
print('十六进制输出:0x%X,0x%X'%(num1,num2))
print('%u'%(-10))
print('%d'%(-10))
#  python3中 %U 等同于 %d

 <2> %f:显示小数后6位,第7位四舍五入

print('%f'%12.21224242)

<3> %e:科学计数法表示方式

print('%e'%123.1234567890)

<4> %g:在保留6位有效数字的前提下,使用小数方式,否则使用科学计数法表示

<5> %s:字符串

print('%s'%'china')

(5)带有控制功能的格式化输出

<1> %md:表示实处m位宽度的十进制整数,m为最小宽度(默认右对齐),若小于m列这左起补空格,大于m列原样输出

a=1234
b=678
print('%5d'%a)
print('%2d'%b)
print('%05d'%a)  #左起补空格改为左起补0
print('%-5d%d'%(a,b))  # - 默认右对齐改为默认左对齐
print('%-05d%d'%(a,b))  #无效

<2> %m.nf:表示输出float型数据,m为总宽度(包含小数位),n为小数位,小于n表示小数位不够右起补0,大于n位则在n+1位进行四舍五入,m若省略则值同n。

num=1234.12345
print('%10.4f'%num)
print('%9.2f'%num)
print('%.2f'%num)  # 常用四舍五入显示算法,只做显示,原值不变
str='hello'
print('%10.3s'%str)  # 字符串截取2位,右对齐补空格

2.输入

(1)格式:变量名=input('提示文字’)

(2)返回值:字符串

(3)PS:input()函数返回值一律为字符串类型,可以使用int()和float()函数进行强制类型转换

3.图形化程序设计

(1)Turtle是Python内嵌的绘制 线、圆以及其他形状(包括)文本的 图形模块。

 

(2)程序实例:

<1> 例1:画出一个三角形

import turtle as t

t.pensize(10)
t.color('red')
t.right(60)
t.forward(100)
t.right(120)
t.forward(100)
t.right(120)
t.forward(100)
t.done()

<2> 画出一个五角星

import turtle as t

t.pensize(5)  # 笔的粗度
t.color('red')
t.right(72)
t.forward(100)
t.right(144)
t.forward(100)
t.right(144)
t.forward(100)
t.right(144)
t.forward(100)
t.right(144)
t.forward(100)
t.right(144)
t.done()

<3> 绘制奥运五环

import turtle as t

t.pensize(6)
t.color('blue')
t.penup()
t.goto(-110, -25)
t.pendown()
t.circle(45)

t.penup()
t.color('black')
t.goto(0, -25)
t.pendown()
t.circle(45)

t.penup()
t.color('red')
t.goto(110, -25)
t.pendown()
t.circle(45)

t.penup()
t.color('yellow')
t.goto(-55, -75)
t.pendown()
t.circle(45)

t.penup()
t.color('green')
t.goto(55, -75)
t.pendown()
t.circle(45)
t.done()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雨天_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值