【问题标题】:Having trouble with with if statements being accessed in python 3在 python 3 中访问 if 语句时遇到问题
【发布时间】:2021-05-22 05:38:24
【问题描述】:

我正在编写一个数学游戏的测试程序。我正在努力显示用户是否正确回答了一个问题,它显示为“正确”(目前在 shell 中),但即使所有 10 个问题都正确回答,它也永远不会正确显示。我尝试了多种方法,例如来回更改变量,但没有任何效果,并添加了许多打印语句以查看 if 语句是否正在被访问,它只显示了一个没有被访问的东西。


    def addition_frame_fun (self): #Creates the frame where students will be answering addition questions with the labels and entry box.
 
        
        self.add_ans_entry=Entry (self.add_frame)
        self.add_ans_entry.grid (row=3,column=5,padx=5)

        next_btn=Button (self.add_frame,text="Next Question",command=self.generate_add_question)
        next_btn.grid (row=12,column=5,sticky=SE)

    def generate_add_question (self):
        
        self.count+=1

        if self.count <11:

            self.num1=random.randint (1,10)
            self.num2=random.randint (1,10)

            self.num1_str =str (self.num1)
            self.num2_str=str (self.num2)

            self.total= str(self.num1+self.num2)

    
    def check_ans (self):
        
        if self.count > 0:

            self.user_add_ans = str (self.add_ans_entry.get () )

           
        if self.user_add_ans == self.total: 
            
            print (self.total)
            print (self.user_add_ans)
            
            print("correct")
            self.score+=1         

【问题讨论】:

  • 请尝试将此代码缩减为minimal reproducible example。似乎有很多代码不需要说明问题。
  • @bryan 工作完成,感谢您告诉我。

标签: python-3.x if-statement tkinter tk


【解决方案1】:

与其将self.total转换为字符串,不如将self.user_add_ans转换为float然后进行比较。

【讨论】:

  • 试过这样做,但我现在得到一个值错误。
  • @VikashPatel 在您分配值之前,该条目是否包含文本或其他内容,因为如果您尝试将文本转换为浮点数,则会发生此错误(例如 float('cat') 然后 python 将引发错误)您可以检查以下链接:[cs.carleton.edu/cs_comps/1213/pylearn/final_results/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多