我似乎已经解决了这个问题 . 我前几天进入Python,所以如果这很容易,那就是原因 . ``
`def firstChoice():
time.sleep(2)
print('You come across a path, it splits at the end.')
time.sleep(1)
choice=input('Which path do you take, the left path (1) or the right path (2)? \n')
checkChoice()
def checkChoice():
correct
if choice=='1' or choice=='2':
correct_choice=randint(1,2)
if choice==correct_choice:
correct=True
if choice!='1' or choice!='2':
print('You decide to not take a path, and you die due to random circumstances.')
time.sleep(1)
print('Take a path next time, or at least take it correctly.')
failScreen()
I've imported everything necessary (time and random) EDIT: Here's the whole code.`
import random
import time
choice=0
def introDisplay():
print('This is the pre-game story.')
time.sleep(1)
print('It lasts for 5 lines.')
time.sleep(1)
print('When you can be arsed, fix this.')
time.sleep(1)
print('Thanks,')
time.sleep(1)
print('You, from 18/3/17')
print()
firstChoice()
def firstChoice():
time.sleep(2)
print('You come across a path, it splits at the end.')
time.sleep(1)
choice=input('Which path do you take, the left path (1) or the right path (2)? \n')
checkChoice(choice)
def checkChoice(choice):
correct=False
if choice=='1' or choice=='2':
correct_choice=random.randint(1,2)
if choice==correct_choice:
correct=True
if choice!='1' and choice!='2':
print('You decide to not take a path, and you die due to random circumstances.')
time.sleep(1)
print('Take a path next time, or at least take it correctly.')
failScreen()
def failScreen():
restart=True
print('You have failed.')
print('Do you want to retry?')
restart1=input('Y or y = Yes. N or n = No. \n')
if restart1=='y' or restart1=='Y':
restart=True
if restart1=='n' or restart1=='N':
restart=False
if restart1!='n' or restart!='N' or restart!='y' or restart!='Y':
failScreen()
if restart==True:
introDisplay()
if restart==False:
exit()
introDisplay()
2 回答
首先,如果你正在使用python2.7你需要知道input()如果你通过控制台给它一个数字,这个函数转换为int,那么你需要检查值,如果
choice == 1
或只是改变输入到raw_input()
(这是最好的方法),同样在if choice!='1' and choice!='2':
你需要放else:
然后你避免了很多检查或意外的值 .如果您使用的是python3,则raw_input是新的输入函数,因此您无需更改它
并且,如果您想使用raw_input()或者您正在使用python3,则需要将随机函数更改为
random.choice('1','2')
,因为您要将str与int进行比较,这里您的代码中包含python2.7的更改:我猜你总是在
failScreen
结束,因为你的第二个if
语句正在使用!=1 or !=2
,这将导致始终true
...将其更改为and
以查看它是否有帮助 .我也不确定
checkChoice
函数中是否可以看到choice
. 在Java中,您需要在function-bodys之外声明变量