如何解决 `oldUser()` 函数无法运行且反复重新启动的问题

71 阅读3分钟

如果 oldUser() 函数在运行时出现反复重新启动或无法正常工作的问题,可能是由于以下原因之一导致的。以下是排查和解决问题的步骤,具体看看我是怎么操作的。

1、问题背景

一位用户在编写一个用于学校项目的 Python 程序时遇到了问题。这个程序允许用户输入单词和定义,然后让学生根据定义来猜测单词。用户希望在学生输入 y 表示他们是一个注册用户后,程序能够运行 oldUser() 函数。但是,oldUser() 函数并没有运行,而是程序重新启动了。

2、解决方案

问题出在 displayMenu() 函数中,if status == raw_input == 'y' 这个条件永远不会为真。因为 raw_input 是一个函数,而 status == raw_input == 'y' 比较的是 statusraw_input 函数以及 'y' 的值。

要解决这个问题,需要将条件修改为 if status == 'y':

def displayMenu():
    status = raw_input('Are you a registered user? y/n?: ')
    if status == 'y':
        oldUser()
    elif status == 'n':
        newUser()

现在,当用户输入 y 表示他们是一个注册用户时,程序将成功运行 oldUser() 函数。

以下是修改后的完整代码:

import os  # allows me to use functions defined elsewhere. os module allows for multi platforming.
import sys
words = []
users = {}
status = ""
​
def teacher_enter_words():
    done = False
    print 'Hello, please can you enter a word and definition pair.'
​
    while not done:
        word = raw_input('\nEnter a word: ')
        deff = raw_input('Enter the definition: ')
        # append a tuple to the list so it can't be edited.
        words.append((word, deff))
        add_word = raw_input('Add another word? (y/n): ')
        if add_word.lower() == 'n':
            done = True
​
def student_take_test():
    student_score = 0
    for pair in words:
        print 'Definition:', pair[1]
        inp = raw_input('Enter word: ')
        student_score += check_error(pair[0], inp)
        print 'Correct spelling:', pair[0], '\n'
​
    print 'Your score:', student_score
​
def check_error(correct, inputt):
    len_c = len(correct)
    len_i = len(inputt)
    # threshold is how many incorrect letters do we allow before a
    # minor error becomes a major error.
    # 1 - allow 1 incorrect letter for a minor error ( >= 2 becomes major error)
    threshold = 1
    # immediately check if the words are the same length
    num_letters_incorrect = abs(len_c - len_i)  # abs() method returns value of x - positive dist between x and zero
​
    if num_letters_incorrect == 0:
        for i in xrange(0, len(correct)):
            if correct[i] != inputt[i]:
                num_letters_incorrect += 1
​
    if num_letters_incorrect <= threshold:
        if num_letters_incorrect == 0:
            return 2  # no incorrect letter.
        else:
            return 1  # minor error.
    else:
        return 0  # major error.
​
def displayMenu():
    status = raw_input('Are you a registered user? y/n?: ')
    if status == 'y':
        oldUser()
    elif status == 'n':
        newUser()
​
def newUser():
    createLogin = raw_input('Create login name: ')
​
    if createLogin in users:
        print '\nLogin name already exist!\n'
    else:
        createPassw = raw_input('Create password: ')
        users[createLogin] = createPassw
        print '\nUser created!\n'
​
def oldUser():
    login = raw_input('Enter login name: ')
    passw = raw_input('Enter password: ')
​
    if login in users and users[login] == passw:
        print '\nLogin successful!\n'
    else:
        print "\nUser doesn't exist or wrong password!\n"
​
​
if __name__ == '__main__':
    running = True
    while running:
        os.system('cls' if os.name == 'nt' else 'clear')  # multi-platform, executing a shell command
​
        reg = raw_input('Do you want to start the program? y/n?').lower()
        if reg == 'y' or reg == 'yes':
            displayMenu()
        else:
            sys.exit(0)
​
        inp = raw_input('Are you a Teacher or a Student? (t/s): ').lower()
        if inp == 't' or inp == 'teacher':
            teacher_enter_words()
        else:
            student_take_test()
            running = False

综合排查步骤

  1. 分析错误日志: 获取具体的报错信息。
  2. 添加调试信息: 使用 printlogging 记录函数执行状态。
  3. 检查依赖环境: 确认所有外部依赖可用。
  4. 优化函数逻辑: 修复无限循环、递归等问题。
  5. 隔离测试: 使用最小输入单元测试函数的行为。

通过以上步骤逐步排查,可以有效解决 oldUser() 函数无法正常运行的问题。