首页 > 解决方案 > 如何在 Python 中检查两个随机生成的字符串是否匹配

问题描述

因为我正在尝试编写一个简单的脚本来检查使用“选择”函数生成的两个字符串是否匹配。“选择”功能从给定列表中挑选字母。我在使用 while 循环时遇到问题。这是我的尝试:

from random import choice

list1 = ['a', 'r', 'l', 'd', 'n', 'm']

ticket = ''
for i in range(3):
    ticket += choice(list1)
print(f"This is the winning ticket: {ticket}\n")

my_tickets = []  #store here the tickets that don't match 
my_ticket = ''

for i in range(3):
    my_ticket += choice(list1)
print(f"The ticket you buy is: {my_ticket}")

active = True
while active:
    for i in range(3):
        my_ticket += choice(list1)

    if my_ticket == ticket:
        active = False
        print("Congratulations, you got the winning ticket!!")

    else:
        print('Try again')

你能帮我找出错误在哪里吗?是否可以在不使用字符串模块的情况下使该脚本工作?谢谢

标签: pythonwhile-loopchoice

解决方案


您还没有描述出了什么问题,但我建议在 else 语句中将 my_ticket 的值设置回 '' 并附加到 my_tickets 变量,因为注释表明了这一点,但您最终不会这样做。


推荐阅读