python - Python掷骰子游戏卡在代码上,如果满足某些用户输入,想要循环重新启动
问题描述
所以我对整个编码场景还很陌生,我正在做一些初学者项目来建立我所学到的东西。
- 本质上,我想要做的是让程序在用户想要再次滚动时重新启动回到循环顶部,或者意外键入其他不是“是”或“否”的内容。
- 另外,有没有办法跳过某行代码,这样就不会询问用户是否要滚动两次?
- 我应该改用函数吗?
找不到任何直接帮助我的信息,所以我想我会问,任何信息都会有帮助,谢谢!
import random
useless_varaible1 = 1
useless_varaible2 = 1
# this is the only way I know to set a while loop, I know yikes.
while useless_varaible1 == useless_varaible2:
lets_play = input('Do you wish to roll? Yes or no: ')
if lets_play.lower() == 'yes':
d1 = random.randint(1, 6)
d2 = random.randint(1, 6)
ask = input('Do you wish to roll again? ')
if ask.lower() == 'yes':
# How do I return to give the user another chance?
elif ask.lower() == 'no':
print('Alright, later!')
break
elif lets_play.lower() == 'no':
print('Alright, later!')
break
else:
print('Not any of the options, try again...')
# how do I return to the top to give the user another chance?
(原代码为图片)
解决方案
你已经提出了几个问题,但我会尝试用一个例子来回答它们。首先,要无限运行 while 循环,您可以将其设置为(与您的语句True
基本相同,只是更简单)。1=1
您关于函数的第二个问题通常是肯定的 - 如果某些代码需要重复多次,通常最好将其提取到函数中。
关于跳过一行代码的第三个问题 - 最简单的方法是 if/else 语句,就像你已经做过的那样。可以改进的一件事是使用continue
; 它从头开始重新启动循环,而break
跳出循环。
这是您的场景的简单代码示例:
import random
def roll():
print('First roll:', random.randint(1, 6))
print('Second roll:', random.randint(1, 6))
play = input('Do you wish to roll? Yes or no: \n')
while True:
if play.lower() == 'yes':
roll()
play = input('Do you wish to roll again? \n')
elif play.lower() == 'no':
print('Alright, later!')
break
else:
play = input('Not any of the options, try again... Yes or no: \n')
推荐阅读
- python - Python Pandas .to_sql() 使用 chunksize > 1 时出现错误 22018
- python - using button feature in dash
- python - Django 表单除了提交按钮没有显示
- javascript - 为什么当我在输入字段上单击输入键时切换下拉列表?
- python - 从两个现有的 DataFrame 创建一个新的 DataFrame
- python - 无法用 pika 清除 rabbitmq 队列
- audio - FFmpeg:在特定时间后覆盖另一个视频,包括音频
- regex - 为什么非捕获和原子组似乎增加了许多步骤
- javascript - 自动完成滚动不适用于反应窗口
- ruby-on-rails - Sprockets 在推送到 Heroku 时抛出 NoMethodError