我写了一个代码,这是一个简单的程序,有 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()
在你的程序中,x
和y
在链函数调用后不会改变。 您应该在year_check
中使用return
,并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()
问题是你第一次只捕获变量(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()