我一直在试图弄清楚一些东西(可能是由于我的编码能力有限)已经茫然了两天(可能是由于我的编码能力有限) Usgin Python 3.4.1
我正在尝试为输入设计一系列选项,并将选项"4"作为传递,但前提是文件存在于特定位置。我可以随时按任何数字,它会重复。但是,如果我选择 4 并且文件不存在,它会返回不正确,但无论下一个答案如何,它都会继续我的程序。
print ("Please Choose From the Following Options")
print ("1. Option A")
print ("2. Option B")
print ("3. Option C")
print ("4. Option D")
print ("5. Option R")
monkeyGuess = input("Selection: ")
monkey = "4"
while monkey != monkeyGuess:
print ()
print ("Incorrect")
monkeyGuess = input("Selection: ")
while monkey == monkeyGuess:
try:
with open('c:test.txt') as file:
break
pass
except IOError as e:
time.sleep(1)
print ()
print ("Incorrect")
monkeyGuess = input("Selection: ")
我厌倦了将两者梳理在一起,但收效甚微:
while monkey != monkeyGuess:
time.sleep(1)
print ()
print ("Incorrect Inputs Found")
monkeyGuess = input("Selection: ")
monkey == monkeyGuess or os.path.isfile('test.txt')
print ()
print ("Incorrect Inputs Found")
monkeyGuess = input("Selection: ")
你的第一种方法不起作用,因为一旦输入了正确的输入(4
),第一个while
循环就已经通过,用户所要做的就是绕过第二个循环,就是选择一个错误的输入,因为这样while monkey == monkeyGuess
就会False
,循环就会停止。
第二种方法是缺少if
语句,但即使它有一个,用户需要做的就是通过选择正确的数字来while monkey != monkeyGuess:
False
- 文件是否存在并不重要。
溶液:
print ("Please Choose From the Following Options")
print ("1. Option A")
print ("2. Option B")
print ("3. Option C")
print ("4. Option D")
print ("5. Option R")
monkey = "4"
while True:
monkeyGuess = input("Selection: ")
if monkeyGuess != monkey:
print ()
print ("Incorrect")
continue
try:
with open('c:test.txt') as file:
break
except IOError as e:
print ()
print ("Incorrect")
通常,while True
循环最适合此方案。在循环内请求用户输入,然后使用 if
语句break
出循环。
你的问题是你运行这段代码的python版本:
bash-3.2$ touch test.txt #Creates a file there so we can ignore the line that checks if it exists
bash-3.2$ python2.7 monkey.py #This is where the script is
Please Choose From the Following Options
1. Option A
2. Option B
3. Option C
4. Option D
5. Option R
Selection: 4
()
Incorrect
Selection: ^C
bash-3.2$ python3.4 monkey.py #Using python3.4
Please Choose From the Following Options
1. Option A
2. Option B
3. Option C
4. Option D
5. Option R
Selection: 4
bash-3.2$ #It exits fine
bash-3.2$