首页 > 解决方案 > 如果用户输入的涂料不等于字母打印错误消息

问题描述

我在编码的第一周,正在尝试解决我的代码中的一个问题

挑战:如何通知用户他的输入不在字母表中,然后在不继续代码的情况下将他返回到输入行。

我的代码

import random
import re

print("    _______\\__")
print("   (_. _ ._  _/")
print("    '-' \__. /")
print("         /  /")
print("        /  /    .--.  .--.")
print("       (  (    / '' \/ '' \              ||  ||   /\   |\  |  _____ |\  /|   /\  |\  |")
print("        \  \_.'            \   )         ||--||  /__\  | \ | | ___  | \/ |  /__\ | \ |")
print("        ||               _  './          ||  || /    \ |  \| |____| |    | /    \|  \|")
print("         |\   \     ___.'\  /")
print("           '-./   .'    \ |/")
print("              \| /       )|\'")
print("               |/       // \\")
print("               |\    __//   \\__")
print("              //\\  /__/     \__|")
print("          .--_/  \_--.")
print("         /__/      \__\'")

name_user = str(input("What is your name?:"))
print("Hello,", name_user, "lets play HangMan, try to guess the word i have challenged you with?")

word_list = ["fireboard", "identical", "chocolate", "christmas", "beautiful", "happiness", "wednesday", "challenge", "celebrate"]

random_pick = random.choice(word_list)
random_pick_a = re.sub("[a-z]","*", random_pick)
random_pick_list_a = list(random_pick_a)
print(random_pick)
count = 0


def main_function():
    global count
    while count <= 9:
        user_input = str(input("type a letter:"))
        for i, c in enumerate(random_pick):
            if c == user_input.casefold():
                random_pick_list_a[i] = user_input.casefold()
                random_pick_list_b = ''.join(random_pick_list_a)
                if random_pick_list_b == random_pick:
                    print("done")
                    exit()
                else:
                    continue
        else:
            if user_input.casefold() not in random_pick:
                count = count+1
                print(count)
                if count == 10:
                    print("sorry")
                    exit()
            print(random_pick_list_b)


main_function()

标签: pythonpython-3.x

解决方案


import string

def get_valid_answer(prompt, errormessage):
    answer = ""
    while True:
        answer = input(prompt)
        if answer not in string.ascii_lowercase:
            print(errormessage)
        else:
            return answer

像这样使用:

get_valid_answer("Make a guess!:","Sorry mate, pick a lower case letter.")

示例运行:

猜一猜!:1
对不起,伙计,选择一个小写字母。
猜一猜!:F
对不起,伙计,选择一个小写字母。
猜猜看!:a

(函数返回'a')


推荐阅读