(一)运算符和表达式:
整数运算示例:
n = int(input('enter the days:'))
months = n // 30
days = n % 30
print('the months = {} the days = {}'.format(months,days))
print('the months = {} the days = {}'.format(*divmod(n,30)))
format格式化,divmod(num1, num2),返回一个元组,这个元组包含两个值,第一个是 num1 和 num2 相整除得到的值,第二个是 num1 和 num2 求余得到的值,然后我们用 *
运算符拆封这个元组,得到这两个值。
类型转换:
我们可以手动的执行类型转换。
类型转换函数 | 转换路径 |
---|---|
float(string) |
字符串 -> 浮点值 |
int(string) |
字符串 -> 整数值 |
str(integer) |
整数值 -> 字符串 |
str(float) |
浮点值 -> 字符串 |
程序实例:
1. 计算数列 1/x+1/(x+1)+1/(x+2)+ ... +1/n,我们设 x = 1
m = int(input('enter a number:'))
sum = 0
for i in range(1,m+1):
sum += 1.0 / i
print('{:2d} {:.4f}'.format(i,sum))
2. 一元二次方程:
#二次方程
a = int(input('enter a:'))
b = int(input('enter b:'))
c = int(input('enter c:'))
d = b * b - 4 * a * c
if d < 0:
print('no answer!')
else:
root1 = (-b + math.sqrt(d)) / (2 * a)
root2 = (-b - math.sqrt(d)) / (2 * a)
print('root1 = ', root1)
print('root2 = ', root2)
math.sqrt(num)函数开方;注意括号,运算顺序。
(二)流程控制
真值检测:
if 1: #真值检测的优雅方式
pass #没想好程序怎么写,写pass不会报错,以后再补充
注意pass的用法。
1. 斐波那契数列:
#斐波那契数列
a, b = 0 ,1
while b < 100:
print(b)
a, b = b, a + b #a比b慢一步
#或者:
b = a + b
a = b
这里先把a+b的值赋值给b,再把b的值赋值给a。在python里,赋值表达式从右边开始。
print()的换行处理:
默认情况下,print()
除了打印你提供的字符串之外,还会打印一个换行符,所以每调用一次 print()
就会换一次行,如同上面一样。可以通过 print()
的另一