python-3.x 下面的代码会产生该错误:赋值前引用了局部变量“valid_num2”和“valid_num2”

gmxoilav  于 2023-01-10  发布在  Python
关注(0)|答案(1)|浏览(173)
import re
def Calculator():    
    raw_input=input("Please enter the calculation you wish to be performed in the necesseary roman numeral format (e.g II + IV ensuring a space between each number and sign): ") #Here we ask for the desired calculation the user wishes to complete

    # assume arguments in the format "VII +II"
    arguments= raw_input.split(" ") #The initial string is then split into three seperate arguments for each separate entity involved in the calculation.
    num1=arguments[0]
    operator = arguments[1] #This indicates that the operator/Command is the second place of our users input which in pyton indices is the 1 space
    num2 = arguments[2] 

    def Validating(num1):
        return (re.search(r"^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$",num1))\
    
    if Validating(num1):
        if Validating(num2):
            print('Both Numerals accepted')
            valid_num1=num1
            valid_num2=num2
        else:
            print('The second numeral entered', num2, 'is not a valid numeral please try again!')
            Calculator()
    else:
        if Validating(num2):
            print("The first numeral entered", num1, "is not a valid numeral please try again!")
            Calculator()
        else:
            print('Both numerals entered', num1, 'and', num2, 'are invalid please try again!')
            Calculator()

    def romanToInt(num1): #This function is essential to the running of the calculator as it converts our first number in our calculations from its roman numeral form to its numerical form 
        #When using roman numerals if the larger numeral comes before the smaller numeral we add them
        #If the smaller numeral comes before larger number we subtract
        
            roman= { "I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000 } #Here we pair each base roman numeral with its numerical counterpart
        
            Int=0
        
            for i in range(len(num1)):
                if i+1<len(num1) and roman[num1[i]] < roman[num1[i+1]]:    #i+1<len(num1) checks to see whether the roman numeral present has another roman numeral after it in our order 
                    Int-=roman[num1[i]]    #roman[num1[i]] < roman[num1[i+1]] this compares whether the first roman numeral is larger or smaller than the one that follows. This is extremely important in determining the value of our roman numerals
                else:    #Int-=roman[s[i]] indicates that in this circumstance we must subtract the first roman numeral from our result
                        Int += roman[num1[i]]     #Int +=roman[num1[i]] indicates that if the previous conditions are not met then we are okay to add both roman numerals together
            return Int #After inserting our roman numeral we are left with an integer as our output

    Int1=romanToInt(valid_num1)
    Int2=romanToInt(valid_num2)

    print(Int1)
    print(Int2)
    print(operator)
    
Calculator()

我试着写一段代码来验证用户输入的计算中的两个罗马数字是否正确,然后在两者都有效时转换成相应的整数。但是我一直收到前面提到的错误。如果我删除这段代码,下面的函数会转换num1和num2的所有输入,即使它们被发现不是有效的数字。我该怎么解决这个问题呢?任何帮助都将不胜感激。
完整的错误代码如下所示:

52     print(Int2)
     53     print(operator)
---> 55 **Calculator()**

Input In [13], in Calculator()
     28         print('Both numerals entered', num1, 'and', num2, 'are invalid please try again!')
     29         Calculator()
---> 31 **num2=valid_num2**
     32 num1=valid_num1
     33 def romanToInt(num1): #This function is essential to the running of the calculator as it converts our first number in our calculations from its roman numeral form to its numerical form 
     34     #When using roman numerals if the larger numeral comes before the smaller numeral we add them
     35     #If the smaller numeral comes before larger number we subtract

UnboundLocalError: local variable 'valid_num2' referenced before assignment
ffdz8vbo

ffdz8vbo1#

当您先输入至少一个无效数字,然后再输入有效数字时,问题就出现了。您遇到了范围问题。
下面是一个可行的解决方案:

import re
def Calculator():    
    raw_input=input("Please enter the calculation you wish to be performed in the necesseary roman numeral format (e.g II + IV ensuring a space between each number and sign): ") #Here we ask for the desired calculation the user wishes to complete

    # assume arguments in the format "VII +II"
    arguments= raw_input.split(" ") #The initial string is then split into three seperate arguments for each separate entity involved in the calculation.
    num1=arguments[0]
    operator = arguments[1] #This indicates that the operator/Command is the second place of our users input which in pyton indices is the 1 space
    num2 = arguments[2] 
    
    status = False  # not yet succeeded

    def Validating(num1):
        return (re.search(r"^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$",num1))\
    
    if Validating(num1):
        if Validating(num2):
            print('Both Numerals accepted')
            valid_num1=num1
            valid_num2=num2
            status = True  # succeed
        else:
            print('The second numeral entered', num2, 'is not a valid numeral please try again!')
    else:
        if Validating(num2):
            print("The first numeral entered", num1, "is not a valid numeral please try again!")
        else:
            print('Both numerals entered', num1, 'and', num2, 'are invalid please try again!')

    def romanToInt(num1): #This function is essential to the running of the calculator as it converts our first number in our calculations from its roman numeral form to its numerical form 
        #When using roman numerals if the larger numeral comes before the smaller numeral we add them
        #If the smaller numeral comes before larger number we subtract
        
            roman= { "I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000 } #Here we pair each base roman numeral with its numerical counterpart
        
            Int=0
        
            for i in range(len(num1)):
                if i+1<len(num1) and roman[num1[i]] < roman[num1[i+1]]:    #i+1<len(num1) checks to see whether the roman numeral present has another roman numeral after it in our order 
                    Int-=roman[num1[i]]    #roman[num1[i]] < roman[num1[i+1]] this compares whether the first roman numeral is larger or smaller than the one that follows. This is extremely important in determining the value of our roman numerals
                else:    #Int-=roman[s[i]] indicates that in this circumstance we must subtract the first roman numeral from our result
                        Int += roman[num1[i]]     #Int +=roman[num1[i]] indicates that if the previous conditions are not met then we are okay to add both roman numerals together
            return Int #After inserting our roman numeral we are left with an integer as our output

    if status:
        Int1=romanToInt(valid_num1)
        Int2=romanToInt(valid_num2)
        
        print(Int1)
        print(Int2)
        print(operator)
    else:
        Calculator()

Calculator()

相关问题