我遇到了将随机数打印到同一行,然后在第二个打印语句上打印6个随机数的总和的问题。这是我到目前为止所做的。
import random
def main():
randnums()
def randnums():
for num in range(0, 6):
num1 = random.randint(1,9)
print(str(num1))
print(" The total is: ")
main()
应该是这样的
2 4 8 9 9 3
The total is 35
答案 0 :(得分:1)
我不确定你的代码有什么问题,因为它的缩进很差但是有些事情需要注意:
这很简单,只需在for循环外添加一个变量,该变量将添加数字:
def randnums():
total = 0
for num in range(0, 6):
num1 = random.randint(1, 9)
total += num1
# End the string with a space. Also removes newline
print(num1, end=" ")
# Add a newline before printing again.
print("\nThe total is:", total)
对于Python 3,删除换行很简单。只需为print函数提供一个新的关键字参数,它就可以工作:
print_function
如果您将来使用Python 2,可以采用以下两种方式:从__future__
导入__future__
或用逗号导入print
:
从# Note that this import must come first
from __future__ import print_function
import random
def main():
randnums()
def randnums():
total = 0
for num in range(0, 6):
num1 = random.randint(1, 9)
total += num1
print(num1, end=" ")
print("\nThe total is:", total)
main()
导入:
import random
def main():
randnums()
def randnums():
total = 0
for num in range(0, 6):
num1 = random.randint(1, 9)
total += num1
# The comma is put after what you want to print. It also adds a space
print num1,
print "\nThe total is:", total
main()
或使用逗号:
3 9 8 2 4 1
The total is: 27
输出:
string accessKey = "xxxx";
string secretKey = "mxxxxx";
string bucketName = "irisdb"; // Set to a bucket you create
// Create S3 service client.
BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3Config asConfig = new AmazonS3Config()
{
ServiceURL = "http://irisdb.s3-ap-southeast2.amazonaws.com/",
ServiceEndPoint = "irisdb.s3-website-ap-southeast2.amazonaws.com" //error here (cannot convert string to endpoints)
};
AmazonS3Client client2 = new AmazonS3Client(awsCredentials, asConfig);
ListBucketsResponse response = client2.ListBuckets();
答案 1 :(得分:0)
如果你正确地缩进代码,你会有更好的运气。
def randnums():
for num in range(0, 6):
num1 = random.randint(1,9)
print(str(num1), end=" ")
print()
print(" The total is: ")
而且你需要在变量中积累总数,这是微不足道的,因为求和是非常基本的,所有基本的都有很好的记录。
答案 2 :(得分:0)
正确的代码如下:
import sys
def randnums():
sum = 0
for num in range(0, 6):
num1 = random.randint(1,9)
sum += num1
sys.stdout.write(str(num1)+" ")
print("\nThe total is: "+str(sum))
OR(如果是Python 3)
def randnums():
sum=0
for num in range(0, 6):
num1 = random.randint(1,9)
sum += num1
print(str(num1), end=' ')
print("\nThe total is: "+str(sum))
答案 3 :(得分:0)
请参阅:Print new output on same line
另外:
确保修复缩进; python对此非常严格。
您需要将数字保存在列表中或在变量中累加总和。否则,在打印num1后,它就消失了。
pred(*(i - 1), *i) != false
答案 4 :(得分:0)
在python 2.7中
import random
def main():
randnums()
def randnums():
sum=0
for num in range(0, 6):
num1 = random.randint(1,9)
print(str(num1))
sum+=num1,
print
print(" The total is: %d" % sum)
main()
在python 3中
def randnums():
sum=0
for num in range(0, 6):
num1 = random.randint(1,9)
print("{}".format(num1)),
sum+=num1
print
print("{}{}".format(" The total is: " , sum))