-1

我写了一个代码,这是一个简单的程序,有 2 个输入和打印。我添加了一些代码以防止名称和年份正确。当来自输入的数据正确时,我的程序可以正常工作,但是当它不存在相同的消息并且输入可以再次输入时,但是在分配给变量新词之后,会打印旧词:/我使用 Python 3.7.3

import re
def name_check(x):
    pattern1=r'[A-Za-z]'
    if re.match(pattern1,x):
        pass
    else:
        print ('This is not your name.')
        give_name()
def year_check(y):
    pattern2=r'(\d)'
    if re.match(pattern2,y):
        pass
    else:
        print ('This is not your year of birth.')
        give_year()
def printing(x,y):
    try:
        print('Hey,',x,',in',int(y)+100,'year you will have 100 years.')
    except:
        print ('An error occured.')
def give_name():
    x=str(input('Enter your name: '))
    name_check(x)
    return x
def give_year():
    y=input('Enter your year of birth: ')
    year_check(y)
    return y
def program():
    x=give_name()
    y=give_year()
    printing(x,y)
program()
4

2 回答 2

0

问题是您第一次只捕获变量(x 和 y)。尝试这个:

import re

def name_check(x):
    pattern1=r'[A-Za-z]'
    if re.match(pattern1,x):
        return True
    else:
        print ('This is not your name.')
        return False

def year_check(y):
    pattern2=r'(\d)'
    if re.match(pattern2,y):
        return True
    else:
        print ('This is not your year of birth.')
        return False

def printing(x,y):
    print(x,y)
    try:
        print('Hey,',x,',in',int(y)+100,'year you will have 100 years.')
    except:
        print ('An error occured.')

def give_name():
    x=str(input('Enter your name: '))
    while not name_check(x):
        x=str(input('Enter your name: '))
    return x

def give_year():
    y=input('Enter your year of birth: ')
    while not year_check(y):
        y=input('Enter your year of birth: ')
    return y

def program():
    x=give_name()
    y=give_year()
    printing(x,y)

program()
于 2019-04-27T14:51:33.557 回答
0

在您的程序中,x并且y在链函数调用后不会改变。你应该return在你的year_checkandname_check函数中使用这样的函数来生效xand y

def name_check(x):
    pattern1=r'[A-Za-z]'
    if re.match(pattern1,x):
        return x
    else:
        print ('This is not your name.')
        return give_name()
def year_check(y):
    pattern2=r'(\d)'
    if re.match(pattern2,y):
        return y
    else:
        print ('This is not your year of birth.')
        return give_year()
def printing(x,y):
    try:
        print('Hey,',x,',in',int(y)+100,'year you will have 100 years.')
    except:
        print ('An error occured.')
def give_name():
    x=str(input('Enter your name: '))
    return name_check(x)
def give_year():
    y=input('Enter your year of birth: ')
    return year_check(y)
def program():
    x=give_name()
    y=give_year()
    printing(x,y)
program()
于 2019-04-27T14:51:48.123 回答