python从0到1--01.python中的输入/输出(基础篇),,1.print()函


1.print()函数输出

在python中,使用print()函数可以将结果输出到标准控制台上。

print()函数的基本语法:print(输出内容);例如

a = 100b = 5print(9)print(a)print(a*b)print("hello")

使用print函数,不但可以将输出内容到屏幕,还可以输出到指定文件。例如,将一个字符串“要么出众,要么出局”输出到“d:\mr.txt",代码如下:

fp =  open(r‘d:\mr.txt‘,‘a+‘)print("要么出众,要么出局",file=fp)fp.close

执行上面的代码后,将在d:\ 目录下生成一个名称为mr.txt文件,该文件的内容为文字“要么出众,要么出局”。

当然 print函数还可以输出日期,但是要先调用datetime模块,例如:

import datetimeprint(‘当前年份:‘ +str(datetime.datetime.now().year))print("当前日期时间:" +datetime.datetime.now().strftime(‘%Y-%m-%d %H:%M:%S‘))

2.input()函数输入

在python中,只用内置函数input可以接受用户的键盘输入。input()函数基本用法如下:

variable = input("提示文字")

其中variable为保存输入结果的变量,双引号的文字用户提示要输入的内容。例如:

1 tip = input("请输入文字:")

在python3.x中,无论输入的是数字还是自发都将被作为字符串读取。

如果想要输入是指,需要把接收到的字符串进行类型转换,例如:

num = int(input("请输入您的幸运数字:"))

练习1:

根据输入的年份计算年龄大小。

import datetimeimyear = input("请输入您的出生年份:")nowyear = datetime.datetime.now().yearage = nowyear - int(imyear)print("您的年龄为:" +str(age ) + "岁")

python从0到1--01.python中的输入/输出(基础篇)

评论关闭