p02

本文介绍了Python编程的基础知识,并通过实例展示了如何使用while循环、for循环、泰勒公式求指数e、break与continue语句、打印乘法表、求解一元二次方程、函数定义与调用、全局变量操作等核心概念。此外,还涵盖了函数、全局变量、打印乘法表、一元二次方程求解、函数调用与全局变量操作的实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. while:

i = 0
while i < 10:
    print i
    i += 1

2. for:

for i in range(0, 3):
    print i
0 1 2
for i in range(3):
    print i
0 1 2
for i in range(0, 3, 2):
    print i
0 2
for i in range(3, 0, -1):
    print i
3 2 1

3. 根据泰勒公式e = 1 + 1/1! + 1/2! + ...,求指数e

en_1 = 1
n = 1
factorial = 1
infactorial = 1
while infactorial > 1e-6:
    en = en_1 + infactorial

    n += 1
    factorial *= n
    infactorial = 1.0/factorial
    en_1 = en
print "e = %-.5f"%en
#使用了格式化输出,取小数点后5为有效数字输出。还可以使用round(en,5)

4. 可以使用break,continue

5. 打印乘法表:

for i in range(1,10):
    for j in range(1,i + 1):
        print str(i) + "*" + str(j) + "=" + str(i*j),
    print

6. 求一元二次方程:

import math

while True:
    a,b,c = eval(raw_input("Enter three coefficients: "))
    #a, b,c = input("Enter three coefficients: ")
    if a== 0:
        print "the equation is linear, not quadratic"
    else:
        delta = b*b - 4*a*c
        print 'delta =',delta
        if delta < 0:
            print "Without real roots"
        elif delta == 0:
            print "Only one root is", (-b/2.0/a)
        else:
            discRoot = math.sqrt(delta)
            r1 = (-b + discRoot) / (2*a)
            r2 = (-b - discRoot) / (2*a)
            print "Two distinct roots are: ", r1, r2
    ch = raw_input("Please input \'c\' to end or any keys to continue\n")
    if ch != 'c' and ch != 'C':
        pass
    else:
        break
print "=== end ==="

7. 函数:

def sum(i1, i2):
    result = 0
    for i in range(i1, i2+1):
        result += i
    return result
def main():
    print "sum(1, 10):", sum(1, 10)
    print "sum(5, 7):", sum(5, 7)

main()

8. 函数中可以打印全局变量,要对全局变量进行运算时要使用global关键字:

x = 1
def increase():
    global x
    x += 1
    print x

increase()
print x



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值