我在這裏使用類輸入分數(當給定分子和分母時),以及將兩個分數相加和相乘。出於某種原因,導入的分數模塊僅對部分程序正確工作; gcd方法有效,但Fraction方法(當給出兩個數字時,放入分數格式)不起作用,而是拋出一個NameError(具體地說,「全局名稱'分數'未定義」)。在Python中使用分數
我在做什麼錯?我對Python相對來說比較陌生,對於如何使這些代碼更緊密以及更多的例外情況,我們將不勝感激。
這裏是我的代碼:
import fractions
class FractionClass:
# Initialize starting numerator and denominator.
n = 0
d = 0
def __init__(self, numerator, denominator):
self.n = numerator
self.d = denominator
# Function that adds fractions, whichs throws NameError if gcd() doesn't work!
def add_fractions(self, other):
try:
sum_numerator = self.n + other.n
sum_denominator = fractions.gcd(self.d, other.d)
return(sum_numerator, sum_denominator)
except NameError:
print("Methods aren't defined.")
# Function that multiplies fractions, whichs throws NameError if gcd() doesn't work!
def multiply_fractions(self, other):
try:
product_numerator = self.n * other.n
product_denominator = self.d * other.d
return(product_numerator, product_denominator)
except NameError:
print("Methods aren't defined.")
# Enter input function.
def user_input():
try:
print("Enter a numerator and denominator:")
n, d = [int(x) for x in input().split()]
print("Enter a numerator and denominator:")
n2, d2 = [int(x) for x in input().split()]
# Check used to debug for denominators that aren't the minimum of 1 (0 can't be divided!)
check = 1/d
check = 1/d2
# print(check)
# Exception for d = 0.
except ZeroDivisionError:
print("\n You didn't enter the minimum denominator.")
print("Set denominator to minimum default.")
d = 1
# Exception for not entering a space in between numbers.
except UnboundLocalError:
print("You didn't enter your numbers in properly! Try again.")
# Exception for not entering all required.
except NameError:
print("\n You didn't enter two numbers.")
# Exception for user input both or one of them, not being integers.
except TypeError:
print("\n You didn't enter all valid numbers.")
# General exception case.
except:
print("Something went wrong!")
fract = FractionClass(n,d)
another_fraction = FractionClass(n2, d2)
total_sum = fract.add_fractions(another_fraction)
# Unpacks total sum tuple.
# Puts in fraction format.
sum_numerator, sum_denominator = total_sum
add_output = fractions.Fraction(sum_numerator, sum_denominator)
total_product = fract.multiply_fractions(another_fraction)
# Unpacks product sum tuple.
# Puts in fraction format.
product_numerator, product_denominator = total_product
multiply_output = fractions.Fraction(product_numerator, product_denominator)
print(add_output, multiply_output)
爲什麼你捕捉「NameError」或「UnboundLocalError」?這些很可能是您的代碼中的錯誤。 – lqc
不僅你的代碼中沒有任何名爲'Fractions'的代碼,也沒有任何與名稱有關的任何引用 - 所以我想你說的爲'全局名'分數'獲得'NameError' 「不可能是正確的。請將堆棧跟蹤中的所有實際行添加到您的問題中,或者至少糾正它。 – martineau
@ lqc這些例外是爲了確保有效的輸入。因此,例如,NameError用於用戶未輸入指定數量的數量,UnboundLocalError用於空格等等。現在它可以工作。謝謝大家! – user1739537