I want to declare a one2n_sum2() function that takes an integer as a parameter and obtains the sum from 1 to the integer from 1 if it is greater than 1, and from -1 to the integer from 0 if it is less than 0. And I want to get an integer, call the function, get the result back, and print it out. Also, I want to print out that 0 is input when I receive 0 but there is an error in the elif part, can I get feedback?
def one2n_sum2(n):
if n>1:
j=0
for i in range(1, n, 1):
j=j+i
return j
print('1 --', n, '=', j)
elif n<0:
h=0
for i in range(-1, n,-1):
h=h+i
return h
print('-1 --', n, '=', h)
else:
print ('Number entered', n, '.')
a=int(input('integer:')
one2n_sum2(n)
def one2n_sum2(n):
if n>1:
j=0
for i in range(1, n+1, 1):
j+=i
print('1 --', n, '=', j)
return j
elif n<0:
h=0
for i in range(-1, n-1,-1):
h+=i
print('-1 --', n, '=',h)
return h
else:
print ('Number entered', n, '.')
a=int(input('integer:')
one2n_sum2(a)
Change the order of print and return, and both print and return must be in the if statement
And if you look at the last two lines, you get an integer as variable a, but you also have to fix the variable that you put in the function is n
+) If you think of the for statement as an index, it would be better to change the positive part to n+1 and the negative part to n-1Yo
+) Write j + = i instead of j = j + i for a cleaner code.
Please look down. Is that what I understand?
To explain further to No. 3, I think this is a problem that can be solved by introducing a mathematical formula. As long as n
is an integer, it's better to think of it as a general solution to all integers as a problem (more concise and logical, and most of the time performance increases) I don't know why you're asking me to solve this problem with loop computation I'd rather give you a star...
And once, the Indentation of the given function is wrong. To look at just one section:
def one2n_sum2(n):
if n>1:
j=0
for i in range(1, n, 1):
j=j+i
print('1 --', n, '=', j) # n>1
Return j # Must be in if above
© 2024 OneMinuteCode. All rights reserved.