函数的第二个参数总是被视为 1 的原因是什么?

问题描述

我的目标是创建一个骰子滚轮,让用户可以选择骰子的数量和面数。

当我让用户可以再次完成该过程(选择骰子数和面数)时,问题就开始了。现在它不显示除了第一个骰子之外的任何结果,当用户输入“n”并且函数中断时,有时它会显示,有时它会继续运行。最后一部分是有意义的,因为接下来是函数“开始”。我还没有想出真正完成脚本运行的方法。

from random import randint


def dice(n_sides,n_dice):
    rolls = []
    for i in range(n_dice):
        # variable "roll" generates random number between 1 and user input
        roll = randint(1,n_sides)
        # variable "roll" is appended to the previously created empty list "rolls"
        rolls.append(roll)
        # enumerates however many results there was
        i += 1
        # prints the end result to the user
        print("Result",i,":",roll)

        choice = input("Do you want to roll the dice again? (y/n)")

        # if user input is "y",start over by running function "start"
        if  choice.lower() == 'y':
            start()
        # uses lower() so that lower case is allowed
        elif choice.lower() == 'n':
            # break terminates function
            break


def start():
    print()
    try:
        print("How many sides your dice has?")
        n_sides = int(input().lower())
    # if something other than integers are typed by user
    except ValueError:
        print("This is not a whole number.")

    try:
        print("How many dice do you want to use?")
        n_dice = int(input().lower())
    # if something other than integers are typed by user
    except ValueError:
        print("This is not a whole number.")

    dice(n_sides,n_dice)


start()

解决方法

这是一种更好的组织方式。让每个函数做一件事。当它完成它的一件事后,让其他人来做决定。

此外,当您只需要整数时调用 lower() 毫无意义。

from random import randint

def dice(n_sides,n_dice):
    rolls = []
    for i in range(n_dice):
        # variable "roll" generates random number between 1 and user input
        roll = randint(1,n_sides)
        # variable "roll" is appended to the previously created empty list "rolls"
        rolls.append(roll)
        # prints the end result to the user
        print("Result",i+1,":",roll)
    return rolls

def round():
    print()
    try:
        n_sides = int(input("How many sides your dice has?"))
    # if something other than integers are typed by user
    except ValueError:
        print("This is not a whole number.")
        continue

    try:
        n_dice = int(input("How many dice do you want to use?"))
    # if something other than integers are typed by user
    except ValueError:
        print("This is not a whole number.")
        continue

    print(dice(n_sides,n_dice))

while True:
    round()
    choice = input("Do you want to roll the dice again? (y/n)")
    if  choice.lower() == 'n':
        break
,

我的理解是,您有 n 个骰子,每个骰子有 m 面,用户将每次输入掷出所有骰子。 您的代码在 dice(n_sides,n_dice): 函数中存在错误,因为您正在执行 for 循环中的所有语句,该循环的运行次数与骰子数相同。记住,缩进在python中很重要

此外,当您接受输入时,您可以使用 while 循环来强制用户输入一个有效的数字,如下所示:

isNumeric = False
while(isNumeric == False):
    try:
        print("How many sides your dice has?")
        n_sides = int(input().lower())
        isNumeric = True
# if something other than integers are typed by user
    except ValueError:
        print("This is not a whole number.")

isNumeric = False
while(isNumeric == False):
    try:
        print("How many dice do you want to use?")
        n_dice = int(input().lower())
        isNumeric = True
# if something other than integers are typed by user
    except ValueError:
        print("This is not a whole number.")

要消除骰子函数中的错误,您可以执行以下操作:

def dice(n_sides,n_sides)
        # variable "roll" is appended to the previously created empty list "rolls"
        rolls.append(roll)
        # prints the end result to the user
        print("Result of Dice Number",roll)

    choice = input("Do you want to roll the dice again? (y/n)")

    # if user input is "y",start over by running function "start"
    if  choice.lower() == 'y':
        start()
    # uses lower() so that lower case is allowed

这将顺利解决您的所有问题!

,

首先,我会使用 exit() 而不是 break。 Break 可以在循环中使用(参见此处:https://www.programiz.com/python-programming/break-continue
其次,对是或否问题使用 while 循环,例如:

    while True:
        a = input("Do you want to roll the dice again? (y/n)")
        if a == "y":
            start()
            continue
        elif a == "n":
            exit()
        else:
            print("Enter either y/n")

所以如果你不想改变代码的逻辑:

from random import randint

def dice(n_sides,n_dice):
    rolls = []
    for i in range(n_dice):
        roll = randint(1,n_sides)
        rolls.append(roll)
        i += 1
    print("Result",i,roll)
    while True:
        a = input("Do you want to roll the dice again? (y/n)")
        if a == "y":
            start()
            continue
        elif a == "n":
            exit()
        else:
            print("Enter either y/n")

def start():
    while True:
        try:
            print("How many sides your dice has?")
            n_sides = int(input())
            break
        except ValueError:
            print("This is not a whole number.")
    while True:
        try:
            print("How many dice do you want to use?")
            n_dice = int(input())
            break
        except ValueError:
            print("This is not a whole number.")
    dice(n_sides,n_dice)

if __name__ == '__main__':
    start()

编辑: 您需要导入 exit 才能执行此操作:from sys import exit

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...