2016-02-27 25 views
-2

我对类很陌生,想通过编写代码来练习。变量的值不会普遍地变化

为什么check_Float的变量p的值不会被传送到代码底部块中的变量p

while p != 3: 
    A.questiondef(p) 
    print(p) 

由于该值不会改变,因此代码只会询问无限多的问题。

class B: 
    def which_Class(self): 
     if i == 0: 
      self.class_number = ("Class One") 
     elif i == 1: 
      self.class_number = ("Class Two") 
     elif i == 2: 
      self.class_number = ("Class Three") 
     else: 
      None 

    def questiondef(self, p): 
     operations = {"x":operator.mul , "-":operator.sub , "/":operator.truediv, "+":operator.add} 
     self.num1 = random.randint(1,200) 
     self.num2 = random.randint(1,10) 
     self.ops = random.choice(list(operations.keys())) 
     self.answer = ((operations.get(self.ops))(self.num1, self.num2)) 
     A.check_Float(p) 


    def student_Score(self, score): 
     if p == 3: 
      print(name , "Your score out of 3 is: " , score) 
      if i == 0: 
       class_1[y][0] = (score) 
       class_1[y][1] = (name) 
      elif i == 1: 
       class_2.append(score) 
      elif i == 2: 
       class_3.append(score) 

      self.score = 0 
     else: 
      None 
    def check_Float(self, p): 
     float1 = self.answer%1 
     if float1 == 0: 
      self.question = int(input("What is {} {} {}?: ".format(self.num1 , self.ops , self.num2))) 
      if self.question == self.answer: 
       print("\nCorrect\n") 
       p = p+1 
       return True 
      else: 
       print("\nIncorrect\n") 
       p = p + 1 
       return False 

     else: 
      return False 
      A.questiondef(p) 

p = 0 
class_1 = [["",""],["",""],["",""]] 
class_2 = [] 
class_3 = [] 
class_number = "" 
A = B() 
score = 0 
import random 
import operator 
for i in range (3): 
    A.which_Class() 
    print(A.class_number) 
    for y in range(3): #Assuming there are 3 students in a class 
     p = 0 
     name = input("\nWhat is your name?: ") 
     score = 0 
     while p != 3: 
      A.questiondef(p) 
      print(p) 

      if p ==3: 
       A.student_Score(score) 
+1

'check_Float'的'else'块中的'A.questiondef(p)'永远不会执行,因为您事先返回。我不知道这是否是问题,我不明白问题描述“变量不会传递到底部”。 – timgeb

+1

我唯一能解释的就是当你改变p时,你在方法的范围内做它,而不返回p的新值,或者甚至使用'self'将它提供给你的实例。除此之外,我很迷茫。 – idjaw

+0

'p'对'Check_Float'是本地的,因为您将它定义为参数。你永远不会更新全球'p' –

回答

2

您可以使用全球关键字 利用等作为 p = 0时在代码 然后在每个函数或函数顶级其中p用于 可以使普全球作为顶级 全球p的函数