我正在努力完成一个数学问题,它使用Newton的猜测和检查方法来近似数字的平方根.用户应该输入一个数字,该数字的初始猜测,以及他们想要在返回之前检查他们的答案的次数.为了让事情变得更容易并且了解Python(我几个月前才开始学习这门语言),我把它分解成了许多小函数; 但现在的问题是,我无法调用每个函数并传递数字.
这是我的代码,有帮助的注释(每个函数按使用顺序):
# This program approximates the square root of a number (entered by the user)
# using Newton's method (guess-and-check). I started with one long function,
# but after research, have attempted to apply smaller functions on top of each
# other.
# * NEED TO: call functions properly; implement a counting loop so the
# goodGuess function can only be accessed the certain # of times the user
# specifies. Even if the - .001 range isn't …Run Code Online (Sandbox Code Playgroud) 我在这里使用类来输入分数(给定分子和分母时),以及将两个分数相加和相乘。由于某些原因,导入的分数模块仅对程序的一部分有效。gcd方法有效,但是Fraction方法(给定两个数字时,将其转换为小数格式)不起作用,而是引发NameError(具体来说,“未定义全局名称'Fractions'”)。
我究竟做错了什么?我对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 …Run Code Online (Sandbox Code Playgroud) 我正在尝试完成一个简单的字数统计程序,它可以跟踪连接文件中的单词,字符和行数.
# This program counts the number of lines, words, and characters in a file, entered by the user.
# The file is test text from a standard lorem ipsum generator.
import string
def wc():
# Sets the count of normal lines, words, and characters to 0 for proper iterative operation.
lines = 0
words = 0
chars = 0
print("This program will count the number of lines, words, and characters in a file.")
# Stores a variable as a …Run Code Online (Sandbox Code Playgroud) python ×3
python-3.x ×2
class ×1
file ×1
file-io ×1
fractions ×1
math ×1
methods ×1
word-count ×1