簡體   English   中英

為什么此代碼不起作用以及如何修復它?

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

我寫了一個代碼,這是一個簡單的程序,有 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)。 嘗試這個:

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()

在您的程序中, xy在鏈函數調用后不會改變。 你應該在你的year_checkname_check函數中使用return像這樣對xy生效:

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM