Python3基础之(二)print() 功能

版权声明:本文为博主原创文章,转载请注明出处! https://blog.csdn.net/PoGeN1/article/details/84064769

一、print 字符串

python 中 print 字符串 要加单引号:'' 或者双引号:""
例如:

print("hello world!")

或者:

print('hello world!')

这两种输出完全一样

二、print 字符串叠加

print("hello"+"world!")

输出:

helloworld!

三、简单运算

可以直接print 加法+,减法-,乘法*,除法/. 注意:字符串不可以直接和数字相加,否则出现错误。
正确:

print(2+3)
print(2-3)
print(2*3)
print(2/3)

输出:

5
-1
6
0.6666666666666666

四、int() 和 float()

当int()一个浮点型数时,int会保留整数部分,比如 int(1.9),会输出1,而不是四舍五入。

>>> print(int(1.9))
1
>>> print(int('2')+3)
5
>>> print(float('2.6'+2))
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    print(float('2.6'+2))
TypeError: must be str, not int
>>> print(float('2.6')+2)
4.6

注意第三个语句:print(float(‘2.6’+2))
报错的原因:字符串不可以和数字直接相加

猜你喜欢

转载自blog.csdn.net/PoGeN1/article/details/84064769