max_num = None
count = 0
while True:
num = int(input("请输入一个整数(以0结束):"))
if num == 0:
break
if max_num is None or num > max_num:
max_num = num
count = 1
elif num == max_num:
count += 1
print("最大数是:", max_num)
print("它出现的次数是:", count)
测试:
import random
count = 0
for i in range(1000000):
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
if x < 0 or (x > 0 and y > 0 and x + y <= 1):
count += 1
res = count / 1000000
print("落在奇数区域的概率为:", res)
测试:
res = []
count = 0
for i in range(2001, 2101):
if i % 4 == 0 and (i % 100 != 0 or i % 400 == 0):
res.append(i)
for i in res:
print(i, end=' ')
count += 1
if count % 10 == 0:
print()
测试:
def fahrenheit_to_celsius(fahrenheit):
celsius = (5 / 9) * (fahrenheit - 32)
return round(celsius, 2)
def celsius_to_fahrenheit(celsius):
fahrenheit = (9 / 5) * celsius + 32
return round(fahrenheit, 2)
print("------------------")
print("摄氏度\t华氏度")
print("------------------")
for c in range(31,41):
f = celsius_to_fahrenheit(c)
print(f"{c}\t\t{f}")
print("------------------")
print("华氏度\t摄氏度")
print("------------------")
for f in range(30,120,10):
c = fahrenheit_to_celsius(f)
print(f"{f}\t\t{c}")
测试:
def sum_m(n):
total = 0
for i in range(1, n+1):
total += i/(i+1)
return total
for j in range(1, 21):
s = sum_m(j)
print(f"{j}\t{s}")
测试:
def sqrt(n):
lastGuess = 1
nextGuess = (lastGuess + n / lastGuess) / 2
while (nextGuess - lastGuess) > 0.0001 or (lastGuess - nextGuess) > 0.0001:
lastGuess = nextGuess
nextGuess = (lastGuess + n / lastGuess) / 2
print(nextGuess)
sqrt(81)
测试:
def is_zhishu(num):
for i in range(2, num // 2 + 1):
if num % i == 0:
return False
return True
def is_huiwenshu(num):
if str(num) == str(num)[::-1]:
return True
count = 0
num = 2
while count < 100:
if is_zhishu(num) and is_huiwenshu(num):
print("%5d" % num, end=" ")
count += 1
if count % 10 == 0:
print()
num += 1
测试:
def is_zhishu(num):
for i in range(2, num // 2 + 1):
if num % i == 0:
return False
return True
def reverse(num):
return int(str(num)[::-1])
def is_not_huiwenshu(num):
if str(num) != str(num)[::-1]:
return True
count = 0
num = 2
while count < 100:
if is_zhishu(num) and is_zhishu(reverse(num)) and is_not_huiwenshu(num):
print("%4d" % num, end=" ")
count += 1
if count % 10 == 0:
print()
num += 1
测试: