Python之print
本次笔记主要内容
1. print 字符串
2. print 字符串叠加
3. 简单运算
print字符串
>>> print("hello world!")
hello world!
>>> print('hello world 2')
hello world 2
>>>
在print字符串的时候,需要使用单引号”或者”“来括住自己需要输出的字符串。这两种的功能是一样的。
几种特殊情况
>>> print('I'm zhang qi')
SyntaxError: invalid syntax
因为单引号的范围默认在了 I 那里。
解决方法:
1. 使用双引号 “”
>>> print("I'm zhang qi")
I'm zhang qi
- 使用声明 \’
>>> print('I\'m zhang qi')
I'm zhang qi
print字符串叠加
在Python中可以使用 + 将两个字符串连接起来,如一下代码。
>>> print('Hello world'+' hello China')
Hello world hello China
简单运算
在Python中可以使用print进行加法 + ,减法 - ,乘法 *,除法 / 。 注意:字符串不可以直接和数字相加,否则出现错误。
>>> print(1+1)
2
>>> print(3-1)
2
>>> print(3*4)
12
>>> print(12/2)
6.0
>>> print('a'+4)
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
print('a'+4)
TypeError: Can't convert 'int' object to str implicitly
和C语言中一样的是,int() 和 float();当int()一个浮点型数时,int会保留整数部分,比如 int(1.9),会输出1,而不是四舍五入。
>>> print(int('2')+3) #int
5
>>> print(int(1.9)) #只保留整数部分
1
>>> print(float('1.2')+3) #使用float把字符串转换成浮点型(带小数)
4.2
以上就是print中的所有基础内容~
如果觉得不错可以点赞收藏哦~会一直更新下去。