You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术求助:完成计数模式步骤3,修正len函数并实现指定奇数打印

Got it, let's sort this out for you! It sounds like your textbook didn't do a great job breaking down how to handle user input and loop through odd numbers—especially with that misleading len() example. Let's build a working solution step by step that matches your requirements.

Working Code Implementation

First, here's the full code that adds the input prompt, validates the user's input, and prints all odd numbers between the starting number and an end number (I added the end number input because we need a clear range for "between"—if you meant something else, just let me know!):

# Prompt user for a positive starting number, with validation
while True:
    try:
        start_num = int(input("请输入一个正起始数:"))
        if start_num > 0:
            break
        print("Oops, that's not a positive number. Try again!")
    except ValueError:
        print("Whoa, that's not a valid integer. Please enter a number.")

# Get an end number to define our range (since we need a "between" set of numbers)
while True:
    try:
        end_num = int(input("请输入一个大于起始数的结束数:"))
        if end_num > start_num:
            break
        print("End number needs to be bigger than your starting number. Try again!")
    except ValueError:
        print("Invalid input—please enter an integer.")

# Loop through the range and print only odd numbers
print(f"\nHere are all the odd numbers between {start_num} and {end_num}:")
for num in range(start_num, end_num + 1):
    if num % 2 != 0:
        print(num)
Key Explanations
  • Input Validation: The while True loops with try/except make sure the user can't break the program by entering non-numeric text or negative numbers—super useful for real-world use!
  • For Loop Range: range(start_num, end_num + 1) tells Python to loop from your starting number up to (and including) the end number. Without the +1, it would stop one number short.
  • Odd Number Check: num % 2 != 0 checks if the number leaves a remainder when divided by 2—if yes, it's an odd number, so we print it.
  • Why len() Was Wrong: Your textbook's bad len() example probably tried to use len() to set loop counts, but len() is only for getting the length of sequences (like lists or strings). We don't need it here because range() handles the loop range directly.

If you actually wanted to print odd numbers starting from the input number (without an end number, like the first X odds), just let me know and I can adjust the code!

内容的提问来源于stack exchange,提问作者Allison

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:12:39