python - What is wrong with my code? Python. Trying to make a gamelist game
问题描述
I am learning python and want to learn from my mistake instead of just look at the course answer to this task.
I am trying to make a gamelist game. We have a list gamelist = [1,2,3] and the user will then get the opportunity to change a value in the list. The user will be able to choose between 0-2 (index position in the list) and after the user will be able to input a value. After this iteration, the gamelist will update.
My problem:
- I am able to change index position 2 and 1 but not 0.
- And I can do it in the sequence [2][1] but I cant change the gamelist if I got the other way around.
Code:
def userindextry():
User_input = 'u'
index_range = range(0,3)
range_check = False
while User_input.isdigit() == False and range_check == False:
User_input = input('Please enter a number: ')
if User_input.isdigit() == True:
if int(User_input) not in index_range:
User_input.isdigit() == False
range_check == False
print('not in range')
else:
print('You choosed', User_input)
break
else:
print('Number please')
return(int(User_input))
def uservalue():
input_value = input('Please enter a value: ')
return(input_value)
and
def game():
gamelist = [1,2,3]
while True:
userindex = userindextry()
userV = uservalue()
for i in range(len(gamelist)):
number = gamelist[i]
if number == userindex:
gamelist[number] = userV
cmd = input('Do you want to quit? Enter \'q\'!')
if cmd == 'q':
print('You did now Quit')
break
else:
pass
print(gamelist)
game()
What is going wrong with my code?
解决方案
def game():
gamelist = [1, 2, 3]
while True:
userindex = userindextry()
#print("userindex", userindex)
userV = uservalue()
#print("userV", userV)
for i in range(len(gamelist)):
number = gamelist[i]
if i == userindex:
gamelist[i] = userV
cmd = input('Do you want to quit? Enter \'q\'!')
if cmd == 'q':
print('You did now Quit')
break
else:
pass
print(gamelist)
您的错误在 game() 函数中。研究我写的带有更正的 game() 的重写(有两个更正)。您将索引与提取的值进行了比较。您将看到更正后的代码有两个修复:
if i == userindex:
gamelist[i] = userV
推荐阅读
- openlayers - 如何在 openlayers 中放置图表
- php - 我的 PHP 没有按我想要的方式工作(未定义的索引是错误)
- scala - 如何在 Gatling 中使用会话中的馈线和值
- wcf - DiscoveryClient 不在我的其他机器上工作
- c# - 每 1 毫秒从可观察队列中添加和删除项目
- reactjs - rc-year-calender 不更新事件
- python - 无法从 Python 中部分初始化的模块“连接”导入名称“mydb”
- python - 有没有办法在 python 中使用函数属性
- java - oracle上的列数据随机丢失
- javascript - Uncaught TypeError: Object (...) is not a function