簡體   English   中英

如何保存隨機輸出以在 python 的另一個函數中使用它

[英]How can I save the random output to use it in another function in python

我是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

使用變量或為其設置全局變量

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

或者

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

這應該為您提供一個基本示例。 我會花一些時間搜索一些資源來幫助您開始學習 Python 編程的基礎知識; 有無數的數量。 如果您了解如何先做小事,您會發現進步會容易得多。

#!/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())

輸出:

Dice:  1
Dice2: 3
Dice Total: 4

一些可能有用的資源:

真正的 Python - 定義你自己的 Python 函數

真正的 Python - f-Strings

官方 Python 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM