python第六周作业(第四章课后程序练习题)

4.1
import random

def guess_number():
target = random.randint(1, 100)
count = 0

while True:
    guess = int(input("请输入你猜的数字(1-100): "))
    count += 1
    
    if guess < target:
        print("猜小了")
    elif guess > target:
        print("猜大了")
    else:
        print(f"恭喜你猜对了!总共猜了{count}次")
        break

guess_number()

4.2
def count_characters():
s = input("请输入一行字符: ")
letters = digits = spaces = others = 0

for char in s:
    if char.isalpha():
        letters += 1
    elif char.isdigit():
        digits += 1
    elif char.isspace():
        spaces += 1
    else:
        others += 1
        
print(f"英文字符: {letters}, 数字: {digits}, 空格: {spaces}, 其他字符: {others}")

count_characters()

4.3
def gcd_lcm():
a = int(input("请输入第一个整数: "))
b = int(input("请输入第二个整数: "))

# 计算最大公约数
x, y = a, b
while y:
    x, y = y, x % y
gcd = x

# 计算最小公倍数
lcm = a * b // gcd

print(f"最大公约数: {gcd}, 最小公倍数: {lcm}")

gcd_lcm()

4.4
import random

def guess_number_extended():
target = random.randint(0, 1000)
count = 0

while True:
    guess = int(input("请输入你猜的数字(0-1000): "))
    count += 1
    
    if guess < target:
        print("猜小了")
    elif guess > target:
        print("猜大了")
    else:
        print(f"恭喜你猜对了!总共猜了{count}次")
        break

guess_number_extended()

4.5
import random

def guess_number_with_validation():
target = random.randint(0, 1000)
count = 0

while True:
    try:
        guess = int(input("请输入你猜的数字(0-1000): "))
        count += 1
        
        if guess < target:
            print("猜小了")
        elif guess > target:
            print("猜大了")
        else:
            print(f"恭喜你猜对了!总共猜了{count}次")
            break
    except ValueError:
        print("输入内容必须为整数!")

guess_number_with_validation()

4.6
def is_leap_year():
year = int(input("请输入年份: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(f"{year}年是闰年")
else:
    print(f"{year}年不是闰年")

is_leap_year()

4.7
def validate_integer_input():
while True:
input_str = input("请输入一个全数字的十进制整数: ")
if input_str.isdigit():
num = int(input_str)
print(f"输入正确: {num}")
break
else:
print("输入不正确,请重新输入")

validate_integer_input()

4.8
def validate_float_input():
while True:
input_str = input("请输入一个带有小数点的浮点数: ")
parts = input_str.split('.')

    if len(parts) == 2 and parts[0].lstrip('-').isdigit() and parts[1].isdigit():
        num = float(input_str)
        print(f"输入正确: {num}")
        break
    else:
        print("输入不正确,请重新输入")

validate_float_input()

posted @ 2025-03-31 22:32  kk/  阅读(39)  评论(0)    收藏  举报