如何正确验证用户输入? [重复]

问题描述 投票:0回答:1

我需要创建 4 个四个变量(

first_name
generic_location
whole_number
plural_noun
),然后让代码自动制作一个短篇故事。我很新,所以请耐心等待。

我想要

  1. 制定一些安全措施,要求对除“whole_number”之外的所有变量的响应都是英语词典中的实际单词。

  2. 将所有 True 输入路由到 if 语句,该语句将控制是否输出故事故事。

这是我到目前为止所想到的:

  • 我知道 .isalpha 不会过滤输入中的实际单词。最初我的目的是只接受字母,但现在我想确保输入至少在英语词典中。因此,如果有人可以推荐我如何做到这一点,谢谢!
first_name = input("Enter a first name."); 
if first_name.isalpha():
    first_name = True; 
    print(first_name); 
else:
    first_name = False; 
    print("Please use only letters."); 
whole_number = input("Enter a whole number."); 
if whole_number.isdigit():
    whole_number = True; 
    print(whole_number); 
else:
    whole_number = False; 
    print("Please use only numbers."); 
plural_noun = input("Enter a plural noun."); 
if plural_noun.isalpha():
    plural_noun = True; 
    print(plural_noun); 
else:
    plural_noun = False; 
    print("Please use only letters."); 
generic_location = input("Enter a generic location."); 
if generic_location.isalpha(): 
    generic_location = True; 
    print(generic_location); 
else:
    generic_location = False; 
    print("Please use only letters."); 
print(end=''); 
if(first_name, whole_number, plural_noun, generic_location == True):
    print(first_name, "buys", whole_number, "different types of", plural_noun, "at", generic_location, "."); 
else: 
    print("Oops please double check your answers!"); 

我的期望:

我希望我错了,但我希望不是。

我认为我通过将所有变量标记为“True”,将变量正确路由到作为短篇故事父级的 if 语句。

但是我不知道我是否应该将“short_story”也设置为变量,还是多余的,因为命令只打印一次代码?

if(first_name, whole_number, plural_noun, generic_location == True):
    print(first_name, "buys", whole_number, "different types of", plural_noun, "at", generic_location, "."); 
else: 
    print("Oops please double check your answers!"); 
python if-statement conditional-statements
1个回答
0
投票

不必等到所有输入结束才查看变量是否正确,您可以继续询问相同的问题,直到用户得到正确的答案。这样,除非所有变量都是正确的格式,否则您将永远无法获得最终打印结果。

静态方法

while not (first_name := input("Enter a first name: ")).isalpha(): 
    print("Please use only letters.")
    
while not (quantity := input("Enter a quantity: ")).isdigit(): 
    print("Please use only numbers.")
    
while not (plural_noun := input("Enter a plural noun: ")).isalpha(): 
    print("Please use only letters.")
    
while not (location := input("Enter a location: ")).isalpha(): 
    print("Please use only letters.")
    
# format with an fstring
print(f'{first_name} buys {quantity} different types of {plural_noun} at {location}.')

动态方法

# alias
alpha  = str.isalpha
digit  = str.isdigit
fmt    = 'numbers', 'letters'

def get_message(msg:str, inputs:tuple) -> str:
    if msg.count('{}') != len(inputs):
        raise ValueError('bracket count and input length differ')

    output = []
    
    # input loop
    for label, func in inputs:
        # keep asking the same question until we get the proper answer
        while not func(in_ := input(f'Enter a {label}: ')):
            print(f'Please use only {fmt[func==alpha]}.')
            
        # store answer
        output.append(in_)
    
    return msg.format(*output)


# CONSTANTS
#             label        | function
FIRST_NAME  = 'first name' , alpha
PLURAL_NOUN = 'plural noun', alpha
QUANTITY    = 'quantity'   , digit
LOCATION    = 'location'   , alpha

# message config
inputs = FIRST_NAME, QUANTITY, PLURAL_NOUN, LOCATION
msg    = '{} buys {} different types of {} at {}.'
    
inputs2 = FIRST_NAME, LOCATION
msg2    = '{} went to {}.'

# results
print(get_message(msg, inputs))
print(get_message(msg2, inputs2))

动态方法可能看起来更复杂,但它会自动允许您创建无限的句子。它还允许更高级别的控制。如果您意识到

isalpha
不允许您输入以
's
结尾的单词,但您已经达到了需要它的程度,该怎么办?使用静态方法,您必须重新考虑包含
isalpha
的每一行。通过动态方法,您只需进行此调整即可:

import re

# alias - ex: Freddy's, doesn't, they've, he'll, students'
alpha  = re.compile(r'[a-z]+(\'([st]|ve|ll)?)?', re.I).fullmatch

奖金

只需付出一点额外的努力,您就可以自动化整个过程。

import re

constants = re.compile(r'{(\w)}').finditer
alpha     = re.compile(r'[a-z]+(\'([st]|ve|ll)?)?', re.I).fullmatch 
digit     = str.isdigit
fmt       = 'numbers', 'letters'

###           label        | function
FIRST_NAME  = 'first name' , alpha
NOUN        = 'noun'       , alpha
PLURAL_NOUN = 'plural noun', alpha
QUANTITY    = 'quantity'   , digit
LOCATION    = 'location'   , alpha


def get_message(msg:str) -> str:
    inputs = []
    for c in constants(msg):
        # get constant name
        rep = c.group(1) 
        # store constant value
        inputs.append(globals()[rep])
        # remove constant name from message, leaving only brackets
        msg = msg.replace(rep, '')
        
    output = []
    
    # input loop
    for label, func in inputs:
        # keep asking the same question until we get the proper answer
        while not func(in_ := input(f'Enter a {label}: ')):
            print(f'Please use only {fmt[func==alpha]}.')
            
        # store answer
        output.append(in_)
    
    return msg.format(*output)


messages = (
    '{FIRST_NAME} buys {QUANTITY} different types of {PLURAL_NOUN} at {LOCATION}.',
    '{FIRST_NAME} loves their {NOUN}.'
)

for message in messages:
    print(get_message(message))
© www.soinside.com 2019 - 2024. All rights reserved.