Python支持同类型的变量作 “+“运算:
>>> 3+5
8
>>> "加"+"油!"
'加油!'
>>> "3"+"5"
'35'
>>> print("he"+"llo")
hello
>>> print(3 + 5)
8
支持乘法运算,无论是数值还是字符串:
>>> 3 * 5
15
>>> "3" * 5
'33333'
>>> print(3*5)
15
>>> print("3" * 5)
33333
转义符号 "\" 在Python中仍然适用:
>>> "hello\"hello"
'hello"hello'
但是对于有换行符号"\n"的,必须要使用print()函数才可以实现。(笔者还没弄明白。。。)
>>> "hello\n" * 3
'hello\nhello\nhello\n'
>>> print("hello\n" * 3)
hello
hello
hello
(以下解释为引用,侵删)
注意:input() 和 raw_input() 这两个函数均能接收 字符串 ,但 raw_input() 直接读取控制台的输入(任何类型的输入它都可以接收)。而对于 input() ,它希望能够读取一个合法的 python 表达式,即你输入字符串的时候必须使用引号将它括起来,否则它会引发一个 SyntaxError 。
除非对 input() 有特别需要,否则一般情况下我们都是推荐使用 raw_input() 来与用户交互。
注意:python3 里 input() 默认接收到的是 str 类型。
在这里我理解的是,input函数跟C语言里的scanf函数作用差不多,作为输入函数,只是不用说明类型。此后可以对输入的变量定义类别。
一个猜数字的小游戏,作为例子:
temp = input("猜猜我心里想的数字:")
guess = int(temp)
if guess==2:
print("对啦!")
else:
print("错啦!")
print("游戏结束!")
==================== RESTART: C:/Users/123/Desktop/em.py ====================
猜猜我心里想的数字:5
错啦!
游戏结束!
>>>
==================== RESTART: C:/Users/123/Desktop/em.py ====================
猜猜我心里想的数字:2
对啦!
游戏结束!
>>>
Python的简单之处就在这里,定义变量时并不需要同时定义类型。
这里guess = int(temp)要将temp取整,也定义了变量类型为数值型,因为input自定义类型为str字符串,字符串不能跟一个数值型比较。否则即使输入2,也是错误的。
temp = input("猜猜我心里想的数字:")
guess = temp
if guess==2:
print("对啦!")
else:
print("错啦!")
print("游戏结束!")
==================== RESTART: C:/Users/123/Desktop/em.py ====================
猜猜我心里想的数字:2
错啦!
游戏结束!
小作业:
temp = input("你的名字是:")
print("你好!" + temp + "!")
你的名字是:石原里美
你好!石原里美!