[英]How can I save the random output to use it in another function in python
I am new to python3 I am trying very hard to add the output of the function, is there any way that I can save an output of an random integer so that i can altogether add it please help me.我是python3的新手,我非常努力地尝试添加函数的输出,有什么方法可以保存随机整数的输出,以便我可以完全添加它,请帮助我。
def dice():
import random
rollball = int(random.uniform(1, 6))
return (rollball)
def dice2():
import random
rollball = int(random.uniform(1, 6))
return (rollball)
print(dice())
input("you have 10 chances left")
print(dice2())
input("you have 9 chances left")
print(dice() + dice2())
#i want to print this last function but by adding only this first and second nothing else
Use a variable or set a global variable for it使用变量或为其设置全局变量
import random
def dice():
rollball = int(random.uniform(1, 6))
return (rollball)
def dice2():
rollball = int(random.uniform(1, 6))
return (rollball)
roll1 = dice()
print(roll1)
input("you have 10 chances left")
roll2 = dice2()
print(roll2)
input("you have 9 chances left")
print(roll1 + roll2)
#i want to print this last function
use用
import random
roll1 = 0
roll2 = 0
def dice():
global roll1
rollball = int(random.uniform(1, 6))
roll1 = rollball
return (rollball)
def dice2():
global roll2
rollball = int(random.uniform(1, 6))
roll2 = rollball
return (rollball)
print(dice())
input("you have 10 chances left")
print(dice2())
input("you have 9 chances left")
print(roll1 + roll2)
#i want to print this last function
This should provide you with a basic example.这应该为您提供一个基本示例。 I would spend some time searching out some resources to help you get started with the basics of python programming;
我会花一些时间搜索一些资源来帮助您开始学习 Python 编程的基础知识; There are an enumerable amount.
有无数的数量。 You'll find it much easier to progress if you understand how to do the little things first.
如果您了解如何先做小事,您会发现进步会容易得多。
#!/usr/bin/env python3.9
"""
Basic Function Usage
"""
from random import uniform
from typing import NoReturn
def dice() -> int:
"""A dice function
Returns:
(int)
"""
return int(uniform(1, 6))
def dice2() -> int:
"""Another dice function
Returns:
(int)
"""
return int(uniform(1, 6))
def main() -> NoReturn:
""" Main
Returns:
(NoReturn)"""
d = dice()
d2 = dice2()
print('Dice: ', d)
print('Dice2:', d2)
print(f'Dice Total: {d + d2}')
if __name__ == '__main__':
try:
main()
except Exception as excp:
from sys import exc_info
from traceback import print_exception
print_exception(*exc_info())
Output:输出:
Dice: 1
Dice2: 3
Dice Total: 4
Some possibly helpful resources:一些可能有用的资源:
Real Python - Defining Your Own Python Function真正的 Python - 定义你自己的 Python 函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.