Python菜鸟教程笔记之实例

1.计算平方根

import cmath
num1 = float(input(' '))
num2 = int(input(' '))
num1_sqrt = num1 ** 0.5            #只适用于正数
num2_sqrt = cmath.sqrt(num2)       #适用于负数和复数
print(num1_sqrt,',',num2_sqrt)

2.计算二次方程ax**2 + bx + c = 0

import cmath
a = float(input('输入a: '))
b = float(input('输入b: '))
c = float(input('输入c: '))
d = b ** 2 - 4*a*c
sul1 = (-b-cmath.sqrt(d))/(2*a)
sul2 = (-b+cmath.sqrt(d))/(2*a)
print(sul1,',',sul2)

3.计算三角形的面积

a = float(input('输入第一条边: '))
b = float(input('输入第二条边: '))
c = float(input('输入第三条边: '))
s = (a+b+c)/2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('%0.3f'%area)

4.计算圆的面积

import cmath
r = float(input('输入圆的半径 '))
area = cmath.pi*(r**2)
print('圆的面积为%0.3f'%area)

5.交换变量

x = input('输入x: ')
y = input('输入y: ')
temp = x
x = y
y = temp
print('x的值为:',x)
print('y的值为:',y)
x,y = y,x
print('x的值为:',x)
print('y的值为:',y)

6.判断奇数还是偶数

num = int(input(' '))
if (num%2) == 0:
    print('偶数')
else:
    print('奇数')

7.输出指定范围内的素数

num_min = int(input('输入区间最小值: '))
num_max = int(input('输入区间最大值: '))
for num in range(num_min,num_max+1):
    if num > 1:
        for i in range(2,num):
            if (num%i) == 0:
                break
        else:
            print(num)

8.计算阶乘

import math
num = int(input(' '))
fact = 1
if num < 0:
    print('负数没有阶乘')
elif num == 0:
    print('1')
else:
    for i in range(1,num+1):
        fact = fact * i
    print(fact)
print(math.factorial(num))

9.斐波那契数列

nterms = int(input(' '))
n1 = 0
n2 = 1
count = 2
if nterms <= 0:
    print('请输入一个正整数')
elif nterms == 1:
    print(n1)
else:
    print(n1,n2,end=' ')
    while count < nterms:
        n3 = n1 + n2
        print(n3,end=' ')
        n1 = n2
        n2 = n3
        count += 1

你可能感兴趣的:(Python菜鸟教程笔记之实例)