简体   繁体   English

如何将两个随机数相加?

[英]How to sum random two numbers?

This is a tough question I got from my school for a beginner.这是我从学校得到的一个针对初学者的棘手问题。 The program asks to generate two random numbers between 1 to 10 and told to make the output of the sum in a separate function with two passed parameters.该程序要求生成 1 到 10 之间的两个随机数,并被告知在带有两个传递参数的单独函数中输出总和。 I managed to generate two random numbers but how to sum up that is a kinda new deal to me.我设法生成了两个随机数,但如何总结这对我来说是一笔新交易。

import random
randomlist = random.sample(range(1, 10), 2)
print randomlist 

You need to create a function and then return the output of the addition.您需要创建一个函数,然后返回加法的输出。 A function which takes two arguments.一个接受两个参数的函数。

def addition(number1, number2):
    return number1 + number2

number1 and number2 are the 2 arguments. number1 和 number2 是 2 个参数。 Since you already have 2 numbers in your list you can pass them like this.由于您的列表中已经有 2 个数字,因此您可以像这样传递它们。

print(addition(*randomlist))

The * unpacks the items in your list and passes them as seperate variables. * 解包列表中的项目并将它们作为单独的变量传递。

I would suggest doing some reading on python functions我建议对 python 函数做一些阅读

Here is how I would do it:这是我将如何做到的:

import random
randomlist = random.sample(range(1, 10), 2)
print (randomlist)

def get_sum (integer0, integer1):
    sum = integer0 + integer1
    return sum

print(str(get_sum(randomlist[0], randomlist[1])))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM