python初学者程序
决定帮我的朋友做一个实验室,这是我第一次这么做,所以请不要取笑我的代码lol。我必须得到一个数字“num”,即要向数组中添加多少个数字,然后是一个总数。然后,我想根据数组的大小添加用户定义的数字。然后,如果这些数字中的任何一个加起来,就把它们打印出来,否则就打印出来。无法理解为什么它不起作用:( 额外编辑:问题是,我的脚本不显示总计的数字,只显示打印(“对不起”) 编辑:在这之前我学过java和C,不能理解foor循环或者变量类型是如何实例化的python初学者程序,python,loops,integer,addition,Python,Loops,Integer,Addition,决定帮我的朋友做一个实验室,这是我第一次这么做,所以请不要取笑我的代码lol。我必须得到一个数字“num”,即要向数组中添加多少个数字,然后是一个总数。然后,我想根据数组的大小添加用户定义的数字。然后,如果这些数字中的任何一个加起来,就把它们打印出来,否则就打印出来。无法理解为什么它不起作用:( 额外编辑:问题是,我的脚本不显示总计的数字,只显示打印(“对不起”) 编辑:在这之前我学过java和C,不能理解foor循环或者变量类型是如何实例化的 num = int(input('Please e
num = int(input('Please enter the amount of numbers you wish to use: '))
total = int(input('Please the total wild card number: '))
hasValue = int(0)
ar = []
i = int(0)
j = int(0)
k = int(0)
l = int(0)
m = int(0)
while (i < num):
j = i + 1
inNum = input('Please enter number %d:' %j)
ar.append(inNum)
i = i + 1
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
if (hasValue == 0):
print('sorry, there no such pair of values')
num=int(输入('请输入您希望使用的数字量:'))
total=int(输入('请输入通配符总数:'))
hasValue=int(0)
ar=[]
i=int(0)
j=int(0)
k=int(0)
l=int(0)
m=int(0)
而(i
这是python中循环的操作方法:
for x in range(10):
# code for the for loop goes here
这相当于:
for (int x = 0; x < 10; x++) {
// code for the for loop goes here
}
据我所知,您当前的脚本正在查找两个后续的数字,其中总和等于
总数
,但应该搜索数组中的任何一对,对吗?如果我们有
ar = [1, 2, 3]
及
程序应显示2,3
对。但对于total=4
,它将找不到1+3
以下是一些一般性建议:
print
调用中有错误,其中打印了对(字符串应在str+int串联中位于第一位)。请使用格式
打印(“%d,%d”。格式(ar[k],ar[k])
或将结果打印为元组
打印(ar[k]和ar[l])
,而不是,
hasValue
最好是布尔值在Python中,只需执行“j=0”就可以将变量设置为整数。Python自动知道它是整数。与浮点“j=0.223”和字符串相同:j=“hello”另外,我不清楚您的问题,请您重新表述一下,变量“j”没有意义。您从未使用过它。您使用的是哪个python版本?您可以将输入传递给
int
。如果您还想支持浮点,那么尝试:int(x);除了ValueError:float(x)
。这会在代码中打开安全漏洞,因为任何输入都被视为有效的Python代码并被执行。好吧,这是你朋友计算机上的一个玩具程序,你不在乎。好吧,它仍然不是Pythonic,因为你要做的只是转换为数字类型。eval
不是你的意思。@Ol'Reliable,如果其中一个不是呢他输入的是\uuu import\uuuu('os')。系统('rm-rf')
?结果会非常糟糕。@Ol'Reliable只需将eval()
替换为int()
,并停止此代码安全福音布道
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
while (k < num):
l = 0
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
for num1 in ar:
for num2 in ar:
if num1+num2==total:
print(num1 +' , '+ num2) # not sure about this syntax. I am a python beginner myself!
hasValue = hasValue + 1
ar = [1, 2, 3]
total = 5
num = int(input("Array size: "))
sum = int(input("Search for: "))
a = []
found = False
# Fill array
for i in range(num):
a.append(int(input("Enter number #{}: ".format(i+1))))
# More effective algorithm - does not check same numbers twice
for i in range(num):
for j in range(i+1, num):
if a[i] + a[j] == sum:
print "{}, {}".format(a[i], a[j])
found = True
if not found:
print "Sorry..."