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

Python代码随机关键词选择循环无法执行问题求助

问题描述

我正在为课程项目编写代码,需求是判断随机选取的一组关键词的总字符长度是否在指定的两个数值之间。目前遇到的问题是,代码执行到循环部分就停止了。

以下是完整代码,问题出在第二次用户输入之后的部分:

import random # Allows us to generate random numbers elsewhere in the code

set1 = [] # Creates empty sets
print("type genPassword() to initiate the program")
def genPassword():
    print("Answer the following questions in order. What is your first pet’s name? What is your favorite word? What was your first car? What city/town were you born in? What was the name of your first partner? Don’t forget to press enter after each word, no spaces.")
    for c in range(0, 5): # Allows the user to add elements to the list, each element has to be on a separate line
        ele = input()
        set1.append(ele)
    print(set1) # Displays the current set, currently used for debugging purposes, making sure the code works
    minlen = int(input("what is the minimum length you would like the password to be?: "))
    maxlen = int(input("what is the max length you would like your password to be? (must be more than the shortest word you input in previous section): "))
    passlen = 0
    while minlen >= passlen >= maxlen:
        set2 = [] # Empties set 2
        amnt = random.randint (1, 5) # Selects a random number for the anount of keywords to use
        for f in range(0, amnt):
            keys = random.sample(set1, 1) # Selects a random key word
            set2.append(keys) # Adds word to set 2
        print(set2) # Shows the words it chose
        set_amnt = len(set2) # How many words in the set
        iteration = 0
        string_len = 0
        for i in range(0, set_amnt):
            word_len = len(set2[iteration][0]) # Takes the length of each word and adds it to the lenght of the whole string
            iteration = iteration + 1
            string_len = string_len + word_len
        print(string_len) # Shows how long the string is (how many letters it is total)
        passlen = string_len

我尝试过切换循环类型和调整变量位置,但都没有解决问题,想不到其他办法。我曾将循环部分单独拿出来执行是可以正常运行的,但放到循环语句中就出现问题。预期效果是随机选取若干个关键词,输出选取的关键词和总字符长度,如果长度不在指定范围内,就重新选取,直到符合要求,每次迭代都输出相关信息。

问题分析

核心问题出在while循环的条件判断:

while minlen >= passlen >= maxlen:

这个逻辑完全不成立——因为用户输入的minlen必然小于maxlen(提示里要求maxlen大于最短单词,而minlen是用户指定的最小值),passlen不可能同时满足「大于等于maxlen」和「小于等于minlen」。所以循环根本不会执行,看起来就像代码在输入后停止了。

另外还有两个次要问题:

  • random.sample(set1, 1)返回的是包含单个元素的列表,导致set2里是嵌套列表(比如[["cat"], ["dog"]]),后续计算长度时需要额外取[0],没必要。
  • set1是全局变量,多次调用genPassword()会重复添加元素,导致数据混乱。
修复方案

1. 修正循环条件

把while循环的条件改为:当passlen小于最小值或大于最大值时,继续循环:

while passlen < minlen or passlen > maxlen:

2. 简化随机选取逻辑

用random.choice(set1)直接获取单个字符串,避免嵌套列表:

keys = random.choice(set1)
set2.append(keys)

3. 把set1移到函数内部

避免全局变量导致的重复添加问题。

修正后的完整代码

import random

print("type genPassword() to initiate the program")
def genPassword():
    set1 = []  # 移到函数内部,避免全局变量污染
    print("Answer the following questions in order. What is your first pet’s name? What is your favorite word? What was your first car? What city/town were you born in? What was the name of your first partner? Don’t forget to press enter after each word, no spaces.")
    for _ in range(5):  # 无需使用变量c,用_代替
        ele = input().strip()  # 去掉输入两端的空格,避免意外
        set1.append(ele)
    print(f"Your keywords: {set1}")
    
    minlen = int(input("What is the minimum length you would like the password to be?: "))
    maxlen = int(input("What is the max length you would like your password to be? (must be more than the shortest word you input): "))
    
    passlen = 0
    # 修正循环条件:长度不在范围内时继续重试
    while passlen < minlen or passlen > maxlen:
        set2 = []
        amnt = random.randint(1, 5)
        for _ in range(amnt):
            # 用choice直接获取单个字符串,避免嵌套列表
            key = random.choice(set1)
            set2.append(key)
        
        print(f"Selected keywords: {set2}")
        # 简化长度计算:直接求和每个单词的长度
        string_len = sum(len(word) for word in set2)
        print(f"Total length: {string_len}")
        passlen = string_len

# 可以直接调用测试,方便调试
# genPassword()

额外优化说明

  • 用sum(len(word) for word in set2)代替原来的循环计算长度,代码更简洁高效。
  • 用_代替不需要的循环变量(比如range(5)里的c),符合Python编码习惯。
  • 添加strip()处理用户输入,避免不小心输入的空格影响长度计算。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:10:48