每种编程语言都有自己的语法规则,就像我们说的语言一样。
关键字和标识符
以下标识符用作保留字或语言的关键字,不能用作普通标识符。 它们必须完全按照此处所写的方式输入:
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
在 Python 中,我们没有指定将要放入变量的数据类型。 所以你可以直接写 abc = 1, abc 会变成整数类型。 如果你写 abc = 1.0,abc 就会变成浮点类型。 这里有一个将两个给定数字相加的小程序
>>> a = 13
>>> b = 23
>>> a + b
36
从上面的示例中可以理解,要在 Python 中声明变量,只需要输入名称和值。Python 还可以操作字符串,它们可以用单引号或双引号括起来
>>> 'India'
'India'
>>> 'India\'s best'
"India's best"
>>> "Hello World!"
'Hello World!'
从键盘读取输入
通常,现实生活中的 Python 代码不需要从键盘读取输入。 在 Python 中,我们使用 input 函数来进行输入。 input(“String to show”) ,这将返回一个字符串作为输出。 让我们编写一个程序来从键盘读取一个数字并检查它是否小于 100。 程序名称是 testhundred.py
#!/usr/bin/env python3
number = int(input("Enter an integer: "))
if number < 100:
print("Your number is smaller than 100")
else:
print("Your number is greater than 100")
输出
$ ./testhundred.py
Enter an integer: 13
Your number is smaller than 100
$ ./testhundred.py
Enter an integer: 123
Your number is greater than 100
在下一个程序中,我们将计算投资。
#!/usr/bin/env python3
amount = float(input("Enter amount: "))
inrate = float(input("Enter Interest rate: "))
period = int(input("Enter period: "))
value = 0
year = 1
while year <= period:
value = amount + (inrate * amount)
print("Year %d Rs. %.2f" % (year, value))
amount = value
year = year + 1
输出
$ ./investment.py
Enter amount: 10000
Enter Interest rate: 0.14
Enter period: 5
Year 1 Rs. 11400.00
Year 2 Rs. 12996.00
Year 3 Rs. 14815.44
Year 4 Rs. 16889.60
Year 5 Rs. 19254.15
一些例子
一些变量和数据类型的例子:
N 个数字的平均值
在下面程序中,我们将计算 N 个数字的平均值。
#!/usr/bin/env python3
N = 10
sum = 0
count = 0
while count < N:
number = float(input(""))
sum = sum + number
count = count + 1
average = float(sum)/N
print("N = %d , Sum = %f" % (N, sum))
print("Average = %f" % average)
输出
$ ./averagen.py
1
2.3
4.67
1.42
7
3.67
4.08
2.2
4.25
8.21
N = 10 , Sum = 38.800000
Average = 3.880000
温度转换
在这个程序中,我们将使用公式 C=(F-32)/1.8 将给定的温度从华氏温度转换为摄氏温度
#!/usr/bin/env python3
fahrenheit = 0.0
print("Fahrenheit Celsius")
while fahrenheit <= 250:
celsius = ( fahrenheit - 32.0 ) / 1.8 # Here we calculate the Celsius value
print("%5.1f %7.2f" % (fahrenheit , celsius))
fahrenheit = fahrenheit + 25
输出
$ ./temperature.py
Fahrenheit Celsius
0.0 -17.78
25.0 -3.89
50.0 10.00
75.0 23.89
100.0 37.78
125.0 51.67
150.0 65.56
175.0 79.44
200.0 93.33
225.0 107.22
250.0 121.11
单行中的多个变量赋值
甚至可以在一行中为多个变量赋值,如
>>> a , b = 45, 54
>>> a
45
>>> b
54
使用这个交换两个数字变得非常容易
>>> a, b = b , a
>>> a
54
>>> b
45
为了理解其工作原理,你必须了解一种名为 tuple 的数据类型。我们用逗号来创建元组。 在右侧,我们创建了元组(我们称之为元组打包),在左侧,我们将元组拆包为一个新的元组。
下面我们有另一个元组拆包的例子。
>>> data = ("Kushal Das", "India", "Python")
>>> name, country, language = data
>>> name
'Kushal Das'
>>> country
'India'
>>> language
'Python'
不能修改元组。如果您希望有任何更改,则必须创建另一个新元组。很多时候,我们创建用 CAPS 编写的变量来标记程序运行时不会改变的值(常量)。例如,如果我们认为颜色是 RGB 值的元组,那么我们可以将它们定义为:
元组不能被修改。 如果你想进行任何更改,则必须创建另一个新元组。 很多时候,我们创建用全大写字母编写的变量来标记在程序运行时不会改变的值(常量)。 例如,如果我们将颜色视为 RGB 值的元组,那么我们可以将它们定义为:
>>> RED = (255, 0, 0)
>>> GREEN = (0, 255, 0)
>>> BLUE = (0, 0, 255)
>>> print(RED)
(255, 0, 0)
格式化字符串
在 Python 3 中,有几种不同的方式来格式化字符串。 我们使用这些方法来动态格式化文本。 我将在下面的举几个例子。
在 Python 3.6 中,我们有一种新的字符串格式化方法。 PEP 498 引入了称为 f-strings
的概念。
以下是使用 f-strings 的相同示例:
>>> name = "Kushal"
>>> language = "Python"
>>> msg = f"{name} loves {language}."
>>> print(msg)
Kushal loves Python.
f-strings 提供了一种简单易读的方法,可以将 Python 表达式嵌入到字符串中。这里还有几个例子。
>>> answer = 42
>>> print(f"The answer is {answer}")
The answer is 42
>>> import datetime
>>> d = datetime.date(2004, 9, 8)
>>> f"{d} was a {d:%A}, we started the mailing list back then."
'2004-09-08 was a Wednesday, we started the mailing list back then.'
如果您想了解有关这个特性如何进入 Python 的更多信息,请观看 Mariatta Wijaya 的演讲。
在 Python3.8 中,我们可以使用以下样式来帮助打印值和变量名。
>>> a = 1
>>> b = 2
>>> print(f"{a=} and {b=}")
a=1 and b=2
.format 方法
我们也可以在字符串中使用 format 方法
>>> name = "Kushal"
>>> language = "Python"
>>> msg = "{0} loves {1}.".format(name, language)
>>> print(msg)
Kushal loves Python.