首页 > 编程问答 >在 Python 中创建和/或检查编号变量的优雅方法

在 Python 中创建和/或检查编号变量的优雅方法

时间:2024-07-31 15:00:57浏览次数:6  
标签:python loops variables

我是一个试图学习 Python 的老家伙,所以我最后的编码经验是使用 BASIC - 不,不是 Visual Basic。 我理解一些与 Python 相关的概念,但我处于初级编码阶段,所以我使用“强力”逻辑编写了这个项目 - 基本上,将字符串分解为单个字母,然后用经典的“”测试每个字母猜单词类型的游戏。

采用的基本逻辑是: 1.) 提出标准问候语 2.) 从定义的列表中抓取一个随机单词 - 列表被缩短以使测试更容易 3.) 将字符串分解为单独的字母 4.) 将未猜出的字母显示为“ ”并缩短显示,以便如果字符少于每个单词的变量数,则会显示“” 5.) 更改“ ”如果这封信包含在先前的猜测列表中 6.) 如果“_”被消除,则宣布您获胜 7.) 如果您的猜测用完,则宣布您失败 8.) 询问您是否要重播

要扩展超过 4 位数字的单词的代码,我会复制并粘贴逻辑以创建 v4 和 output4 等 - 就像我说的,这是一种暴力方法。|| |所以,人们对以下方面的任何评论:

1.) 使其看起来更漂亮的提示 - 或实现相同目标的更好方法(即,我根本不需要将字符串分解为单个字母) 2.)任何不必强力命名所有变量并使用较小的代码自动生成您试图猜测的随机单词的正确长度的变量的技巧

这是我的代码:

我的解决方案有效并且可以扩展 - 但是,这是一种蛮力方法,我认为有更好的方法来编码。 但是,该函数中的编码确实达到了其预期目的。

import random

words = ['rai', 'com']

turns = 5

def set_random(): # set the random word the user will try to guess
    ran = random.choice(words)
    main(ran)
def main(ran): # main body, a giant function which avoids using global variables
    lives = turns # used to pass in the initial message on how many lives and then count down for wrong guesses
    user_guesses = []
    print(f'Your word has {len(ran)} letters')
    flag = True # used to end the game if the user guesses all of the letters

    while lives > 0 and flag == True: # testing both conditions, lives still remain and game not won
        test_length = len(ran)

    # my logic to break down the random word string into individual letters used for the subsequent testing.  Also,
    # fixes display so that if the brute force placeholders for checking is longer than the actual answer, it will
    # display a black placeholder
        if test_length > 0:
            v0 = ran[0]
        else:
            v0 = ""

        if test_length > 1:
            v1 = ran[1]
        else:
            v1 = ""

        if test_length > 2:
            v2 = ran[2]
        else:
            v2 = ""

        if test_length > 3:
            v3 = ran[3]
        else:
            v3 = ""

    # brute for logic - initialize the output with default values which are then tested and changed in the next step
        output0 = "_"
        output1 = "_"
        output2 = "_"
        output3 = "_"

    # collect user guess, add it to the prior guess list and sort it for display later
    guess = input(str("Please guess a letter:  "))
    user_guesses.append(guess)
    user_guesses.sort()

    # the positive condition meaning the guess was included and then to change the display output to reflect guessed
    # letters or the "_" or show nothing if the word was shorter than the brute force placeholders
        if guess in ran:
            print(f'"{guess}" is in the word')
            if v0 == "":
                output0 = ""
            elif v0 in user_guesses:
                output0 = v0
            else:
                pass

            if v1 == "":
                output1 = ""
            elif v1 in user_guesses:
                output1 = v1
            else:
                pass

            if v2 == "":
                output2 = ""
            elif v2 in user_guesses:
                output2 = v2
            else:
                pass

            if v3 == "":
                output3 = ""
            elif v3 in user_guesses:
                output0 = v3
            else:
                pass

            print(f'You have guessed {user_guesses}')

    else:
            lives -= 1
            if v0 == "":
                output0 = ""
            elif v0 in user_guesses:
                output0 = v0
            else:
                pass

            if v1 == "":
                output1 = ""
            elif v1 in user_guesses:
                output1 = v1
            else:
                pass

            if v2 == "":
               output2 = ""
            elif v2 in user_guesses:
                output2 = v2
            else:
                pass

            if v3 == "":
                output3 = ""
            elif v3 in user_guesses:
                output0 = v3
            else:
                pass

            print("")
            print(f'Sorry, there is no "{guess}" is in the word')
            print(f'You have {lives} lives remaining')
            print(f'You have guessed {user_guesses}')
            print("")

    # command to display the user guesses with "_" for the unguessed numbers
    print(output0, output1, output2, output3)

    # logic to test if the game has been won by guessing all the correct letter - eliminating all "_"
        x = output0 + output1 + output2 + output3
        if "_" not in x:
            print("")
            print(f'You have correctly guessed "{ran}"! You have won the game!')
            print("")
            flag = False
        else:
            pass

# code to end the game if all the lives are lost
    if lives == 0:
        print(f'Sorry, you are out of lives.  Your word was {ran}')
        print("")
    else:
        pass

    replay_game()

# function to replay the game starting with the random word being re-selected and passed to the main function
def replay_game():
    choice = input("Would you like to play again? (Y/N): ")
    choice = choice.lower()
    if choice == 'y':
        print("")
        set_random()
    else:
        print("")
        print("Thanks for playing!, good bye")

# standard greeting message - ask for name and if the user wants instructions on how to play
def greeting():
    print("Welcome to my game!")
    print("")
    name_player = input(str("Please input your name: "))
    print("")
    print(f'Hello {name_player}, let us begin the Word Guessing Game')
    instructions = input(str(f'Would you like instructions on how to play? Y/N: '))
    if instructions.upper() == "Y":
        print("")
        print(
            f'You will have {turns} lives to guess the right word.  Input letters until you solve the word or you run out of lives.')
        print(f'Now, we will start the game!')
        print("")
    else:
        print("")
        print(f'Then we will start the game!')
        print("")

greeting()
set_random()

我不知道的是:

1.) 我是否违反了任何编码经验规则? 例如,我的原始代码使用全局变量,所以这是我的重新代码来解决这个问题 2.)像我一样划分代码是标准的还是应该将其划分为更多函数以便代码函数更可重用? - 基本上,主要功能是巨大的。 3.) 自动生成变量并根据 if/then 语句赋值的更好方法。 基本上,我可以结合缩短显示的步骤来匹配单词的 len 以及更改为猜测与“_”与使用多个步骤(如我的代码中所示)吗?

任何帮助将不胜感激 -对我来说,编写代码是一个令人愉快的项目,但我知道这不是经验丰富的程序员编写代码的方式。

Any help will be greatly appreciated - it was an enjoyable project for me to code but I know this is not the way you experienced coders would write it.


做得很好!你的代码运作良好,而且你已经有了很好的逻辑思维。让我们来探讨一下如何让它更“Pythonic”和更有效。

1. 用字符串代替单个字母变量

你最大的突破是认识到你不必单独跟踪每个字母。在 Python 中,字符串可以像字母列表一样被索引,这使得事情变得简单多了。

word = "rai"
for letter in word:
    print(letter) 

这段代码将遍历 "rai" 中的每个字母并打印它。

2. 使用列表来存储猜测

你已经在用 user_guesses 列表来存储猜测了,这很棒!我们可以用它来动态地显示单词的状态。

3. 重构代码

让我们重构你的代码,利用这些想法:

import random

words = ['rai', 'com']
turns = 5

def get_random_word():
    return random.choice(words)

def display_word(word, guessed_letters):
    """显示单词,用'_'表示未猜到的字母。"""
    display = ''
    for letter in word:
        if letter in guessed_letters:
            display += letter
        else:
            display += '_'
    return display

def play_hangman():
    """运行一个猜词游戏。"""
    word_to_guess = get_random_word()
    guessed_letters = []
    lives = turns

    print(f'你的单词有 {len(word_to_guess)} 个字母。')

    while lives > 0 and not all(letter in guessed_letters for letter in word_to_guess):
        print(f'你还有 {lives} 条命。')
        print(display_word(word_to_guess, guessed_letters))

        guess = input('请猜一个字母: ').lower()

        if not guess.isalpha() or len(guess) != 1:
            print('请输入一个字母。')
            continue

        if guess in guessed_letters:
            print('你已经猜过这个字母了。')
            continue

        guessed_letters.append(guess)

        if guess in word_to_guess:
            print('猜对了!')
        else:
            lives -= 1
            print('猜错了。')

    if lives == 0:
        print(f'你输了!这个单词是 "{word_to_guess}"。')
    else:
        print(f'你赢了!你猜对了 "{word_to_guess}" 这个单词。')

def main():
    """处理游戏流程,包括问候和重玩选项。"""
    print("欢迎来到我的猜词游戏!")
    name = input("请输入你的名字: ")
    print(f'你好,{name}!')

    while True:
        play_hangman()
        if input("你想再玩一次吗?(y/n) ").lower() != 'y':
            break
    print("谢谢参与,再见!")

if __name__ == "__main__":
    main()

解释:

  1. 函数化: 我们将代码分解成函数 ( get_random_word , display_word , play_hangman , main ) 来提高可读性和可重用性。
  2. 循环: 我们使用 for 循环来遍历单词中的字母,而不用单独跟踪每个字母。
  3. 列表推导式: 我们使用列表推导式 [letter in guessed_letters for letter in word_to_guess] 来简洁地检查是否猜对了所有字母。
  4. 输入验证: 我们添加了输入验证来确保用户输入的是单个字母。
  5. 游戏流程: main 函数现在处理问候语、游戏循环和重玩选项。

其他提示:

  • 考虑添加更多单词到你的 words 列表中,以增加游戏的趣味性。
  • 你可以探索使用集合( set )来更有效地存储猜测的字母,因为集合会自动删除重复的元素。
  • 对于更高级的功能,你可以添加提示或难度级别。

请记住,编程的最佳方式是不断练习和探索新的概念。祝你在 Python 学习之旅中一切顺利!

标签:python,loops,variables
From: 78814826

相关文章

  • 使用法兰克福 API 和 Python 虚拟环境时出现 404 错误
    我正在VisualStudioCode中用Python制作货币转换器脚本,并且使用法兰克福API,它在几天前一直工作正常,直到现在每次我尝试获取API时都会收到404错误:|||输出:>response=requests.get(f"https://api.frankfurter.app/latest?amount={amount}&from={CF}&to={CT}")>......
  • 我的目标是检测车道并控制车辆保持在车道中央。使用Python
    我目前正在做一个项目,我是一个初学者。并且我需要找到一种方法来使用检测到的车道来控制我的项目车辆保持在两条线之间的中心。img1|||img2我有疑问的话题如下如何判断我的机器人车是否在车道中央?我们应该用什么方法来控制机器人的转向......
  • 【学习笔记】Matlab和python双语言的学习(主成分分析法)
    文章目录前言一、主成分分析法1.主成分分析法简介2.主成分分析法原理3.主成分分析法思想4.PCA的计算步骤二、代码实现----Matlab三、代码实现----python总结前言通过模型算法,熟练对Matlab和python的应用。学习视频链接:https://www.bilibili.com/video/BV1EK41187......
  • 如何使用python输入提示具有相同参数类型但不同返回类型的函数?
    我有一个函数,它的返回类型是tuple[bool,set[int]|str]如果第0项是True,则第1项是结果set[int],否则第1项是一个str,显示失败的原因。是这样的defcallee(para_a:int)->tuple[bool,set[int]|str]:result=set([1,2,3])if......
  • 彻底卸载Python
        前言通常我们在一些软件的使用上有碰壁,第一反应就是卸载重装。所以有小伙伴就问我Python怎么卸载才能彻底卸载干净,今天这篇文章,小编就来教大家如何彻底卸载Python 软件卸载方法1:首先,在安装python时,下载了一个可执行文件,也就是Python的安装包,我们双击它,点击uninstal......
  • 如何使用 Azure Devops API (Python) 提取特定提交的文件内容?
    这就是我想要做的:每次对我的存储库中的特定分支进行提交时,我想提取该提交中更改的所有YAML文件,对其内容进行一些修改,然后将结果作为PR推送到一个新的、独立的分支。我已经弄清楚了这里的大部分步骤,但我陷入了解析提交文件内容部分。我已经尝试过get_item_content和......
  • 在Python中,为什么这个负浮点数能够通过非负while循环测试条件?
    在Python中工作收集用户输入输入需要非负在程序的另一部分成功使用了While条件但现在不明白为什么这个捕获有效输入的测试失败了。print("Howmanygramsofxyzarerequired?")xyz_string=input()xyz=int(float(xyz_string))whilex......
  • 【Python】正色表达式 - 验证罗马数字
    一、题目Youaregivenastring,andyouhavetovalidatewhetherit'savalidRomannumeral.Ifitisvalid,printTrue.Otherwise,printFalse.TraytocreatearegularexpressionforavalidRomannumeral.InputFormatAsinglelineofinputcontainin......
  • 三种语言实现二维差分(C++/Python/Java)
    题目输入一个n行m列的整数矩阵,再输入q个操作,每个操作包含五个整数x1,y1,x2,y2,c其中(x1,y1)和(x2,y2)表示一个子矩阵的左上角坐标和右下角坐标。每个操作都要将选中的子矩阵中的每个元素的值加上c。请你将进行完所有操作后的矩阵输出。输入格式第一行包含整数n,......
  • 基于python电力安全员施工培训系统【源码+文档+PPT】
    精彩专栏推荐订阅:在下方主页......