我写了一个代码,这是带有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()
答案 0 :(得分: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()
答案 1 :(得分:0)
在您的程序中,链函数调用后x
和y
不变。您应该在return
和year_check
函数中使用name_check
,以使x
和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()