Python没有做数学

时间:2017-09-21 17:44:48

标签: python math add

import time
import sys
pass1 = False
while pass1 == False:
   bob = int(0)
   hi = int(4)
   password = input("Enter your 4 digit number password: ")
   if bob == 5:
       print("Locked out of phone")
       time.sleep(2)
       sys.exit()
   elif password == "5674":
       print("Correct password")
       pass1 = True
   else:
      hi -= 1
      print("Incorrect password, remaining attempts = ",hi)
      bob = bob + 1

我不知道为什么它不会只减去变量“hi”和“bob”并将其加1。

3 个答案:

答案 0 :(得分:2)

每次进入循环时,

hibob都会重新初始化。将初始化移到循环外部,你应该没问题:

bob = 0
hi = 4
while not pass1:
    # loop body...

答案 1 :(得分:2)

实际上它正在工作,但在循环开始时你重置变量。熟悉像pudb之类的工具来计算这样的事情可能是值得的。

在这里,您的代码还有一些额外的改进:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import time
import sys

tries = 0
maxtries = 4

while True:
   tries += 1
   if tries > maxtries:
       print("Locked out of phone")
       time.sleep(2)
       sys.exit()

   password = input("Enter your 4 digit number password: ")
   if password == "5674":
       print("Correct password")
       break
   else:
      print("Incorrect password, remaining attempts = ", maxtries - tries)
  • 在循环之外移动变量初始化
  • 删除了不必要的int来电
  • 使循环更加pythonic
  • 给出了变量的合理名称

希望这有帮助!

答案 2 :(得分:1)

正如@Barmar所说,你的变量初始化发生在循环中。像这样纠正:

import time
import sys
pass1 = False
bob = 0
hi = 4
while pass1 == False:
   password = input("Enter your 4 digit number password: ")
   if bob == 5:
       print("Locked out of phone")
       time.sleep(2)
       sys.exit()
   elif password == "5674":
       print("Correct password")
       pass1 = True
   else:
      hi -= 1
      print("Incorrect password, remaining attempts = ",hi)
      bob = bob + 1