Python的非程序员教程3
输入和变量
现在,我觉得是时候编写一个真正复杂的程序了。代码如下:
print("Halt!")
user_input = input("Who goes there? ")
print("You may pass,", user_input)
当我运行它时,屏幕上显示了以下内容:
Halt!
Who goes there? Josh
You may pass, Josh
注意:在按下 F5 运行代码后,Python Shell 只会输出:
Halt!
Who goes there?
你需要在 Python Shell 中输入你的名字,然后按回车键,剩下的输出才会显示。
当然,当你运行该程序时,屏幕的显示会有所不同,因为 input()
语句会暂停程序,等待用户输入。你可能注意到(你是运行了程序吧?)你需要输入你的名字,然后按回车键。程序随后打印出一些额外的文本以及你的名字。这就是输入的示例。程序执行到某一部分时,会暂停,等待用户输入一些数据,程序才能在后续处理中使用这些数据。
当然,从用户获取信息没有意义,如果我们没有地方存储这些信息,这就是变量的作用。在前面的程序中,user_input
就是一个变量。变量就像一个盒子,可以存储某些数据。下面是一个展示变量使用的程序示例:
a = 123.4
b23 = 'Spam'
first_name = "Bill"
b = 432
c = a + b
print("a + b is", c)
print("first_name is", first_name)
print("Sorted Parts, After Midnight or", b23)
输出如下:
a + b is 555.4
first_name is Bill
Sorted Parts, After Midnight or Spam
在上面的程序中,变量包括 a
、b23
、first_name
、b
和 c
。基本的数据类型有两种:字符串和数字。字符串是由字母、数字和其他字符组成的一串字符。在这个例子中,b23
和 first_name
都是存储字符串的变量。Spam
、Bill
、a + b
is
、first_name is
和 Sorted Parts, After Midnight
or
都是字符串,字符串内容由双引号("
)或单引号('
)括起来。另一个变量类型是数字。记住,变量用于存储值,数字类型的变量不使用引号。如果你想存储实际的字符串值,必须使用引号。
例如:
value1 = Pim
value2 = "Pim"
这两行看起来相同,但第一个例子中,Python 会检查变量 value1
中存储的值是否与变量 Pim
的值相同;而在第二个例子中,Python 会检查存储在 value2
中的字符串(即 "Pim")是否与实际值相同。
赋值
好了,我们有了这些被称为变量的“盒子”,以及可以放入这些变量的数据。计算机会看到像 first_name = "Bill"
这样的语句,它会理解为:“把字符串 Bill
放入变量 first_name
”。稍后,计算机会看到语句 c = a + b
,它会理解为:“把 a + b
的结果(即 123.4 +
432
,结果是 555.4
)放入变量 c
”。语句右侧的部分(a +
b
)会先被计算,结果会存储到左侧的变量(c
)中。这叫做赋值,你不应将赋值操作符(=
)与数学中的“相等”概念混淆(这就是以后会使用 ==
的场合)。
这是另一个变量使用的例子:
a = 1
print(a)
a = a + 1
print(a)
a = a * 2
print(a)
输出如下:
1
2
4
即使同一个变量出现在等号的两边(例如 spam = spam
),计算机仍然会先计算出要存储的数据,然后再将结果存入相应的变量。
再来看一个程序:
number = float(input("Type in a number: "))
integer = int(input("Type in an integer: "))
text = input("Type in a string: ")
print("number =", number)
print("number is a", type(number))
print("number * 2 =", number * 2)
print("integer =", integer)
print("integer is a", type(integer))
print("integer * 2 =", integer * 2)
print("text =", text)
print("text is a", type(text))
print("text * 2 =", text * 2)
我得到的输出是:
Type in a number: 12.34
Type in an integer: -3
Type in a string: Hello
number = 12.34
number is a <class 'float'>
number * 2 = 24.68
integer = -3
integer is a <class 'int'>
integer * 2 = -6
text = Hello
text is a <class 'str'>
text * 2 = HelloHello
注意,number
是通过 float(input())
创建的,而 int(input())
返回一个整数(没有小数点的数字),而通过 input()
创建的 text
则返回一个字符串(也可以写作 str(input())
)。当你希望用户输入一个小数时,使用 float(input())
;当你希望用户输入一个整数时,使用 int(input())
;而如果你希望用户输入一个字符串,则使用 input()
。
程序的后半部分使用了 type()
函数,它会返回变量的类型。数字可以是 int
或 float
类型,分别表示整数和浮点数(主要用于小数)。文本字符串是 str
类型,表示字符串。整数和浮点数可以用来进行数学运算,但字符串则不行。注意,当 Python 把一个数字乘以一个整数时,结果符合预期;而当字符串与整数相乘时,结果是该字符串的多个副本(例如:text * 2 =
HelloHello
)。
字符串操作
字符串操作与数字操作的结果不同。有些操作只适用于数字(无论是整数还是浮点数),如果对字符串使用这些操作,程序会报错。以下是一些交互模式的示例,展示了一些字符串操作:
>>> print("This" + " " + "is" + " joined.")
This is joined.
>>> print("Ha, " * 5)
Ha, Ha, Ha, Ha, Ha,
>>> print("Ha, " * 5 + "ha!")
Ha, Ha, Ha, Ha, Ha, ha!
>>> print(3 - 1)
2
>>> print("3" - "1")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'
以下是一些字符串操作的例子:
操作 | 符号 | 示例 |
---|---|---|
重复 | * |
"i" * 5 == "iiiii" |
拼接 | + |
"Hello, " + "World!" == "Hello, World!" |
示例
Rate_times.py
# 这个程序计算速率和距离问题
print("Input a rate and a distance")
rate = float(input("Rate: "))
distance = float(input("Distance: "))
time = (distance / rate)
print("Time:", time)
示例运行:
Input a rate and a distance
Rate: 5
Distance: 10
Time: 2.0
Input a rate and a distance
Rate: 3.52
Distance: 45.6
Time: 12.9545454545
Area.py
# 这个程序计算矩形的周长和面积
print("Calculate information about a rectangle")
length = float(input("Length: "))
width = float(input("Width: "))
Perimeter = (2 * length + 2 * width)
print("Area:", length * width)
print("Perimeter:", Perimeter)
示例运行:
Calculate information about a rectangle
Length: 4
Width: 3
Area: 12.0
Perimeter: 14.0
Calculate information about a rectangle
Length: 2.53
Width: 5.2
Area: 13.156
Perimeter: 15.46
Temperature.py
# 这个程序将华氏温度转换为摄氏温度
fahr_temp = float(input("Fahrenheit temperature: "))
celc_temp = (fahr_temp - 32.0) * (5.0 / 9.0)
print("Celsius temperature:", celc_temp)
示例运行:
Fahrenheit temperature: 32
Celsius temperature: 0.0
Fahrenheit temperature: -40
Celsius temperature: -40.0
Fahrenheit temperature:
212 Celsius temperature: 100.0
Fahrenheit temperature: 98.6 Celsius temperature: 37.0
### 练习
编写一个程序,获取用户输入的两个字符串变量和两个数字变量,将这两个字符串拼接在一起并显示,然后在新的一行显示这两个数字的乘积。
解决方案
编写一个程序,从用户那里获取两个字符串变量和两个数字变量,将字符串连接在一起并显示,然后在新的一行中显示这两个数字的乘积。
string1 = input('字符串 1: ')
string2 = input('字符串 2: ')
float1 = float(input('数字 1: '))
float2 = float(input('数字 2: '))
print(string1 + string2)
print(float1 * float2)