编程基础/变量示例 Python
外观
< 编程基础
以下示例演示了 Python 中的数据类型、算术运算和输入。
# This program demonstrates variables, literal constants, and data types.
i = 1234567890
f = 1.23456789012345
s = "string"
b = True
print("Integer i =", i)
print("Float f =", f)
print("String s =", s)
print("Boolean b =", b)
Integer i = 1234567890 Float f = 1.23456789012345 String s = string Boolean b = true
每个代码元素代表
#
开始注释i = , d = , s =, b =
将字面值分配给相应的变量print()
调用 print 函数
# This program demonstrates arithmetic operations.
a = 3
b = 2
print("a =", a)
print("b =", b)
print("a + b =", (a + b))
print("a - b =", (a - b))
print("a * b =", a * b)
print("a / b =", a / b)
print("a % b =", (a % b))
a = 3 b = 2 a + b = 5 a - b = 1 a * b = 6 a / b = 1.5 a % b = 1
每个新的代码元素代表
+, -, *, /, and %
分别代表加法、减法、乘法、除法和模运算。
# This program converts an input Fahrenheit temperature to Celsius.
print("Enter Fahrenheit temperature:")
fahrenheit = float(input())
celsius = (fahrenheit - 32) * 5 / 9
print(str(fahrenheit) + "° Fahrenheit is " + str(celsius) + "° Celsius")
Enter Fahrenheit temperature: 100 100.0° Fahrenheit is 37.77777777777778° Celsius
每个新的代码元素代表
input()
从标准输入读取下一行float()
将输入转换为浮点数