[英]Assigning a variable name to a function in Python 3
So I'm writing a program that, once finished, will have a user roll 2 dice and then keep a running sum of the values shown and assign some points to the values that are rolled, but I am running into a problem when first getting started.所以我正在编写一个程序,一旦完成,将让用户掷 2 个骰子,然后保持显示的值的运行总和,并为掷出的值分配一些点,但是我在第一次获得时遇到了问题开始了。 This is what I have so far:
这是我到目前为止:
def diceOne():
import random
a = 1
b = 6
diceOne = (random.randint(a, b))
def diceTwo():
import random
a = 1
b = 6
diceTwo = (random.randint(a, b))
def greeting():
option = input('Enter Y if you would like to roll the dice: ')
if option == 'Y':
diceOne()
diceTwo()
print('you have rolled a: ' , diceOne, 'and a' , diceTwo)
greeting()
(after, I plan to do calculations like diceTwo + diceOne
and do all the other stuff - i know this is very rough) (之后,我打算做像
diceTwo + diceOne
这样的计算,然后做所有其他的事情——我知道这很粗糙)
But when it runs, it does not give nice integer values as expect, it returns function diceOne at 0x105605730> and a <function diceTwo at 0x100562e18>
Does anyone know how to get around this while still being able to assign variable names in order to later be able to perform calculations?但是当它运行时,它没有像预期的那样给出很好的整数值,它返回
function diceOne at 0x105605730> and a <function diceTwo at 0x100562e18>
有谁知道如何解决这个问题,同时仍然能够分配变量名以便以后使用能够进行计算吗?
There are several problems with your code.您的代码有几个问题。 I'll post this as an answer because it's more readable than a comment
我会将此作为答案发布,因为它比评论更具可读性
dice()
dice()
dice()
, not assign dice()
to random.randint()
dice()
返回一个值,而不是将dice()
分配给random.randint()
You can call dice()
directly in your print statement您可以在打印语句中直接调用
dice()
import random def dice(): a = 1 b = 6 return random.randint(a, b) def greeting(): option = input('Enter Y if you would like to roll the dice: ') if option == 'Y': print('you have rolled a ' , dice(), 'and a ', dice()) greeting()
You have to return
something from your functions for them to have an influence on anything outside of the functions themselves.你必须从你的函数中
return
一些东西,以便它们对函数本身之外的任何东西产生影响。 Then, in your function greeting()
you have to call
the functions by calling diceOne()
instead of diceOne
.然后,在您的函数
greeting()
您必须通过调用diceOne()
而不是diceOne
来call
函数。
Try:尝试:
def diceOne():
import random
a = 1
b = 6
return (random.randint(a, b))
def diceTwo():
import random
a = 1
b = 6
return (random.randint(a, b))
def greeting():
option = input('Enter Y if you would like to roll the dice: ')
if option == 'Y':
diceOne()
diceTwo()
print('you have rolled a: ' , diceOne(), 'and a' , diceTwo())
greeting()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.