我仍然是一個只有幾個月編程經驗的初學者。我正在撰寫一個程式以幾種模式擲骰子。我的選擇性模式有問題。
代碼:
from os import system
from platform import system as operating_system
from random import randint, randrange
from textwrap import dedent
from time import sleep
from typing import Union
def user_input() -> tuple[list[int], list[int]]:
"""Option selection"""
dictionary_input: dict[str, str] = {
"dice":
"How many dice to roll?\n",
"sides":
"Type in the maximum number:\n",
"confirm": """
Your mode is {2}, you're rolling {0}d{1} dice.\n
Is this correct? (y/n/quit)\n""",
"includes_confirm": """
Your mode is {2}, you're rolling {0} dice from numbers:
{1}\n
Is this correct? (y/n/quit)\n""",
"mode": """
Please select a number of your desired mode:
1) Normal
2) Increments of 10 (0 included)
3) Selective (Only numbers specified by user)
4) Exclude (Do not repeat numbers)
5) Exit the app\n"""}
mode_input: dict[int, str] = {
1: "Normal",
2: "Increments",
3: "Selective",
4: "Exclude"
}
choice: list[int] = [0, 0, 0]
dice, sides, mode = 0, 6, 0
included_numbers: list[int] = []
confirmation: str = ""
while confirmation.upper() != "Y":
try:
# ask for mode
mode = int(input(dedent(dictionary_input["mode"])))
if mode == 5:
break
# ask for number of dice to roll
dice = int(input(dictionary_input["dice"]))
if mode == 3:
# selective numbers options
included_numbers.append(*number_inclusion()) # this part returns [], why?! (ノ?益?)ノ彡┻━┻
print(included_numbers) # <- doesn't work
if len(included_numbers) < 1:
continue
else:
# check for increment of 10 while in increments mode
if mode == 2:
while sides % 10 != 0:
sides = int(input(dictionary_input["sides"]))
if sides % 10 != 0:
print(f"{sides} is not an increment of 10")
continue
else:
sides = int(input(dictionary_input["sides"]))
# confirmation from user
if dice > 0 and sides > 0:
if mode in mode_input:
if mode != 3:
confirmation = input(
dedent(dictionary_input["confirm"]).format(
dice, sides, mode_input[mode]))
else:
confirmation = input(
dedent(dictionary_input["includes_confirm"])
.format(dice, included_numbers,
mode_input[mode]))
if confirmation.upper() != "QUIT":
choice[0], choice[1], choice[2] = dice, sides, mode
else:
break
else:
print("Mode accepts numbers 1 - 5\n\n")
continue
else:
print("Only positive numbers\n\n")
continue
except ValueError:
print("Only numbers accepted\n\n")
continue
return (choice, included_numbers)
def number_inclusion() -> list[int]:
"""Function used with mode Selective, stores user numbers"""
included_numbers: list[int] = []
temp_input: Union[int, str] = 0
ask = {
"first": """
Type \"review\" to view numbers,
type \"remove\" to delete numbers,
type \"done\" to finish.""",
"next":
"Type in your number:\n"
}
print(dedent(ask["first"]))
while str(temp_input).upper() != "DONE":
temp_input = input(dedent(ask["next"]))
# input verification
if temp_input.upper() not in ["DONE", "REVIEW", "REMOVE"]:
try:
if int(temp_input) < 0:
print("Only positive numbers accepted")
raise ValueError
if float(temp_input) % 1 != 0:
print("Only integers accepted")
raise ValueError
if int(temp_input) in included_numbers:
print("Number is already on the list")
continue
included_numbers.append(int(temp_input))
print(f"added number {temp_input} to selection")
continue
except ValueError:
print("Unsuported option")
continue
if str(temp_input).upper() == "REVIEW":
print(f"Saved numbers are:\n{included_numbers}")
continue
if str(temp_input).upper() == "REMOVE":
print(f"Saved numbers are:\n{included_numbers}")
try:
temp_remove: int = int(input(
"Which would you like to remove?\n"))
if temp_remove in included_numbers:
included_numbers.remove(temp_remove)
print("Number removed")
else:
raise ValueError
except ValueError:
print("Select a number from your list.\n\n")
else:
included_numbers.append(int(temp_input))
print(f"added number {temp_input} to selection")
print(included_numbers) # <- doesn't work
return included_numbers
該函式number_inclusion()應該回傳一個帶有數字的串列并附加到included_numbers該user_input()串列中。雖然審查時一切看起來都很好
Type in your number:
>>>1
>>>2
>>>3
>>>review
Saved numbers are:
[1, 2, 3]
在number_inclusion()執行后,user_input()我直接收到第一次嘗試ValueError的訊息Only numbers accepted...除了塊user_input()
我想number_inclusion()回傳一個list[int]將替換included_numbers的user_input()
任何關于如何改進這個怪物功能的提示也將不勝感激!
編輯:感謝Paul Cornelius,我設法修復了我的錯誤。對于任何經過這里的人來說,這都是有效的:
洗掉底部的這部分,number_inclusion()因為它已經包含在 while 回圈中
else:
included_numbers.append(int(temp_input))
print(f"added number {temp_input} to selection")
替換append為extend_user_input()
if mode == 3:
# selective numbers options
included_numbers.extend(number_inclusion())
if len(included_numbers) < 1:
continue
這里可能還有更多需要改進的地方,但至少它可以按預期作業。
uj5u.com熱心網友回復:
您的函式中存在邏輯問題number_inclusion,在回圈的底部:
if str(temp_input).upper() == "REMOVE":
print(f"Saved numbers are:\n{included_numbers}")
try:
temp_remove: int = int(input(
"Which would you like to remove?\n"))
if temp_remove in included_numbers:
included_numbers.remove(temp_remove)
print("Number removed")
else:
raise ValueError
except ValueError:
print("Select a number from your list.\n\n")
else:
included_numbers.append(int(temp_input))
print(f"added number {temp_input} to selection")
如果temp_input是“完成”,則將采用else:分支并int(temp_input)引發 ValueError。您可以簡單地消除整個 else 塊;回圈邏輯處理 temp_input “完成”的情況。
正如 Tadhg McDonald-Jensen 在評論中指出的那樣,在程式邏輯允許的情況下,在 try: 和 except: 之間放置盡可能少的代碼行是一種很好的做法。如果有太多的代碼行可能會在處理之前引發例外,則程式變得難以除錯。
您還可以查看該traceback模塊,它允許您從例外處理程式塊內列印回溯。有時它很快就會把你引向問題。事實上,我就是這樣找到這個的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/523718.html
