zl程序教程

您现在的位置是:首页 >  Python

当前栏目

Python的基础函数

2023-02-18 15:29:20 时间

print( )函数、input( )函数

Python 来打印 'Hello, world' 你会惊奇地发现Python是如此的简洁与优雅。

In [ ]
# 打印Hello, worldprint('Hello, world')
Hello, world
In [ ]
# input()函数:接受一个标准输入数据,返回为string类型name = input("请输入你的昵称:")
print("你好,"+ name + "!")
请输入你的昵称:你好,行远见大!

字符串:str( )、整型数:int( )、浮点数:float( )

  • 字符串:str( )、整型数:int( )、浮点数:float( ) 用法

  • 类型转换

In [ ]
# str()的作用:把一个数或任何其他类型转换成字符串name = input("请输入你的昵称:")# 其实在此处有name = str(name)的一个过程print("你好,"+ name + "!")
请输入你的昵称:你好,行远见大!
In [ ]
# 此处str()的作用:把数值变成了字符串a = str(input("输入一个数字:"))
print(a)
b = str(input("输入一个数字:"))
print(b)
print("打印两个数字相加:%s " % (a + "+" + b))
输入一个数字:3
输入一个数字:5
打印两个数字相加:3+5
In [ ]
# 此处int()的作用:把字符串变成了数值a = "5"b = int(a)# 去掉了双引号print(b)
5
In [ ]
# 此处int()的作用:浮点数变整数,直接把小数点后的内容去掉a = 3.222b = int(a)
print(b)
3
In [ ]
# 输入一个整数,如果输入小数则报错num = int(input("请输入一个整数:"))
print(num)
请输入一个整数:5
In [ ]
# 此处float()的作用:把整数转换成浮点数a = 10b = float(a)
print(b)
10.0
In [ ]
# 此处float()的作用:把字符串转换成浮点数a = "10"b = float(a)
print(b)
10.0
In [ ]
# 输入一个浮点数,如果输入整数则强制转换成浮点数num = float(input("请输入一个浮点数:"))
print(num)
请输入一个浮点数:3.2

type( )函数、isinstance( )函数

用以识别变量的类型

In [ ]
# type()函数a, b, c, d = 1, 2.0, "Hello, world", Trueprint(a, type(a), b, type(b), c, type(c), d, type(d))
1 <class 'int'> 2.0 <class 'float'> Hello, world <class 'str'> True <class 'bool'>
In [3]
# isinstance()函数print(isinstance("Hello, world", str))  # 返回Trueprint(isinstance("Hello, world", int))  # 返回Falseprint(isinstance(5,int))                # 返回Trueprint(isinstance(3.2, float))           # 返回Trueprint(isinstance(True, bool))           # 返回True
True
False
True
True
True

字符串格式化输出

格式化输出(formalized export)

符号描述
%c格式化字符及其ASCII码
%d格式化整数
%e格式化浮点数,用科学计数法
%f格式化浮点数字,可指定小数点后的精度
%g格式化浮点数字,根据值的大小采用%e或%f
%o格式化无符号八进制数
%s格式化字符串
%u格式化无符号整型
%x格式化无符号十六进制数(小写字母)
%X格式化无符号十六进制数(大写字母)
In [ ]
# 格式化输出数字age = 10print("我今年%d岁了" % age)

num = int(input("请输入一个整数:"))
print("数字是:%d !" % num)
我今年10岁了
请输入一个整数:数字是:10 !
In [ ]
# 格式化输出字符串print("我的名字是%s,我的国籍是%s。" % ("行远见大","中国"))
我的名字是行远见大,我的国籍是中国。

end函数、sep函数

改变打印间隔

In [ ]
# end函数print("hello",end="")     # end=""   不换行,直接链接下一句print("world",end="\t")   # end="\t" 中间空个Tabprint("next",end="\n")    # end="\n" 换行print("python")
helloworld	next
python
In [ ]
# sep函数print("www","baidu","com")
print("www","baidu","com",sep=".")
print("www","baidu","com",sep="\n")
www baidu com
www.baidu.com
www
baidu
com