[英]How do I fix my (supposedly while-loop or if-statement) dice-simulator in Python so it prints the amount of tries its taken before landing on a 6?
[英]How do I correct my code so that it finds the exceptions and quits accordingly and if its valid it tries the string mutation?
这是我的代码:
string = input("Enter a sting")
pos = int(input("Enter the position to be modified"))
try:
b = string.split()
b[pos] = 'k'
b = "".join(b)
print(b)
except:
if string == "":
print("Enter a valid string")
quit()
if pos not in range(len(string)):
print("Enter a valid position to be modified")
quit()
如果您尝试使用错误的索引或空字符串来尝试代码,则会看到程序将运行IndexError。 您可以在您的except子句中找到它。 从您的问题来看,您说要在捕获到异常后退出程序,以便下面的代码可以工作。 我修改了错误消息,以免使用户混淆他们下一步应该做什么。
string = input("Enter a sting: ")
pos = int(input("Enter the position to be modified: "))
try:
b = string.split()
b[pos] = 'k'
b = "".join(b)
print(b)
except IndexError as e:
if string == "":
print("Error: Need to enter a valid string.")
if pos not in range(len(string)):
print("Error: Need to enter a valid position to be modified.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.