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

What's the reason why second parameter of a function is always being treated as 1?

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

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

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()

我的理解是,你有 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_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 of Dice Number", i+1, ":", 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

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

这里有一个更好的组织方式。让每个函数做一件事。当它完成了它的一件事,让别人来做决定。

此外,当您想要的只是整数时,调用 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

首先,我会使用 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