python - 如果用户输入的涂料不等于字母打印错误消息
问题描述
我在编码的第一周,正在尝试解决我的代码中的一个问题
挑战:如何通知用户他的输入不在字母表中,然后在不继续代码的情况下将他返回到输入行。
我的代码
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()
解决方案
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')
推荐阅读
- twitter-bootstrap-3 - Bootstrap Accordion:subcollapse 应在关闭 supercollapse 时关闭
- windows - 在编辑器打开文件夹之前,Unity 不会通过脚本创建 apk
- javascript - 只有在我选择了范围之后才在范围滑块观察程序中执行代码,而不是在我滑动滑块时一直执行?
- java - 带有返回语句的奇怪警告
- laravel - Laravel 迁移创建用户“意外'使用'(T_USE)”SQLite
- teradata - 根据各种条件寻找天数
- javascript - 打字稿定义 - 嵌套函数
- javascript - IE setData 拖放
- java - 如何在 Spring Boot 2 应用程序中使用实体继承?
- php - PHP这是什么数据格式