定义和使用变量

变量命名规则

硬性规则:

1.变量名由字母、数字和下划线构成,数字不能开头。
2.大小写敏感
3.不要关键字保留字冲突。

官方建议:

用全小写字母,多个单词用下划线练级。
见名知意

 

print = 1000
#改变了print函数的定义

 

运算符

 

赋值运算符:=  +=   -=   *=   /=    **=
算术运算符:+   -    *    /    //    %    **
关系运算符:>    >=    <    <=    ==    !=
逻辑运算符:and or not

例 1:

x = float(input('x = '))
y = float(input('y = '))
# 求和
print('%f + %f = %f' % (x, y, x + y ))
# 求差
print('%f - %f = %f' % (x, y, x - y ))
# 求乘积
print('%f * %f = %f' % (x, y, x * y ))
# 整除
print('%f // %f = %f' % (x, y, x // y ))
# 求模(求余数)
print('%f %% %f = %f' % (x, y, x % y ))
# 求幂
print('%f ** %f = %f' % (x, y, x ** y ))


print(x)

 

 

例 2:求圆的周长和面积

radius = float(input('请输入圆的半径: '))
# Python在语言层面没有定义常量的语法
# 但是我们可以通过把变量名用全大写来做一个隐含提示(隐喻)
# 全大写的变量要当做常量来看待在代码中不能修改它的值
# 经验提示:符号常量总是优于字面常量
PI = 3.14
print('圆的周长:%.2f' % (2 * PI * radius))
print('圆的面积: %.2f' % (PI * radius ** 2))

 

 

例 3:实现英制单位到公制单位

inch = float(input('请输入英寸: '))
"""
CM = 2.54
print('该英寸等于',inch * CM,'厘米')
"""
cm = 2.25 * inch
print(str(inch) + '英寸=' +str(cm) + '厘米')

 

 

例 4:判定是不是闰年

year = int(input('请输入年份'))
# condition1 = year % 4 ==0
# condition2 = year % 100 != 0
# condition3 = year % 400 == 0
# is_leap = condition1 and condition2 or condition3
is_leap = year % 4 == 0 and yaer % 100 != 0 or year % 400 == 0
print(is_leap)

 

 

例 5:华氏温度摄氏温度双向转换

fahrenheit = float(input('请输入华氏度'))
celsius = (fahrenheit - 32 ) / 1.8
print('摄氏度为%.2f度' % celsius)
celsius = float(input('请输入摄氏度'))
fahrenheit = celsius * 1.8 + 32
print('华氏度为%.2f度' % fahrenheit)

 

 

例 6:泳池修建问题

import math
radius = float(input('请输入圆的半径'))
money1 = (math.pi * (radius + 3) ** 2 - math.pi * radius ** 2 ) * 25
money2 = 2 * math.pi * (radius + 3 ) * 35.5
money3 = money1 + money2
print('修建泳池的走道需要 %.2f元' % money1)
print('修建泳池的走道围墙需要 %.2f元' % money2)
print('总共需要 %.2f元' % money3)

 

 

 

例 7:三角形

import math # 导入数学式
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
if a + b > c and a + c > b and c + b > a:
p = a + b + c
# 开平方根 print(math.sqrt)
s = math.sqrt((p / 2) * (p / 2 - a) * (p / 2 - b) *(p / 2 - c))

print('三角形的周长为:%.2f' % p)
print('三角形的面积为:%.2f' % s)
else:
print('三角形不成立')