我一直在试图找出一些东西(可能是由于我的能力编码能力有限)但是我已经损失了两天#Ikgin 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: ")
答案 0 :(得分:0)
您的问题是您运行此代码的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$
答案 1 :(得分:0)
您的第一种方法不起作用,因为一旦输入了正确的输入(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
循环最适合此方案。在循环中请求用户输入,然后使用break
语句在循环中if
。