2017-09-27 8 views
-3

私は、入力上限値までの完全な正方形の数を計算して出力する簡単なプログラムを書こうとしています。私のコードは次のとおりです。プログラムで変数を定義する際の問題

"""Print all the perfect squares from zero up to a given maximum.""" 

def read_bound(): 
    """Reads the upper bound from the standard input (keyboard). 
     If the user enters something that is not a positive integer 
     the function issues an error message and retries 
     repeatedly""" 
    upper_bound = None 
    while upper_bound is None: 
     line = input("Enter the upper bound: ") 
     if line.isnumeric() and int(line) >= 0: 
      upper_bound = int(line) 
      return upper_bound 
     else: 
      print("You must enter a positive number.") 



def is_perfect_square(num): 
    """Return true if and only if num is a perfect square""" 
    for num in range(2, upper_bound + 1): 
     for candidate in range(1, num): 
      if candidate * candidate == num: 
       return True 



def print_squares(upper_bound, squares): 
    """Print a given list of all the squares up to a given upper bound""" 


    print("The perfect squares up to {} are: ". format(upper_bound)) 
    for square in squares: 
     print(square, end=' ') 



def main(): 
    """Calling the functions""" 
    upper_bound = read_bound() 
    squares = [] 
    for num in range(2, upper_bound + 1): 
     if is_perfect_square(num): 
      squares.append(num) 

    print_squares(upper_bound, squares) 


    main() 

私はプログラムと入力任意の有効な数値を実行したときしかし、私はfor num in range(2, upper_bound + 1):を持っている行にbuiltins.NameError: name 'upper_bound' is not definedを示すエラーを取得します。この問題の原因は何ですか?どのように修正できますか?

+3

あなたはその関数にupper_boundを渡さず、numだけを渡します。 – jonrsharpe

答えて

0

プログラムでは、 "is_perfect_square"関数に問題があります。ループの "upper_bound"は "main"関数で既に持っているので、これは必要ありません。あなたの "is_perfect_square"関数は以下のようになります:

def is_perfect_square(num): 
    """Return true if and only if num is a perfect square""" 
    for candidate in range(1, num): 
      if candidate * candidate == num: 
       return True 
関連する問題