Search code examples
pythonvariableserror-checkingattribution

Why this code doesn't work and how to repair it?


I wrote a code, this is simple program with 2 inputs and print. I add some code to prevent that name and year are correct. When data from inputs are correct my program works correctly but when its not there is equal messange and input is possible to enter again, but after asign to variables new words, old ones are printed :/ I use 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()

Solution

  • In your program ,x and y doesn't change after chain function calls. you should use return in your year_check and name_check functions like this to take effect to x and 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()