Python Forum
Is this right/ what should i change?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is this right/ what should i change?
#1
# 3. Using the following list and a “for” loop, display differences of all consecutive pairs of numbers in the list.

our_list = [1,2,5,6,3,77,9,0,3,23,0.4,-12.4,-3.12]

for i in our_list:
print(i-1)
Reply
#2
Did you run it?  Does the output seem right?
Reply
#3
output looks like this but I want it to subtract consecutive pairs of numbers:

our_list = [1,2,5,6,3,77,9,0,3,23,0.4,-12.4,-3.12]
for i in our_list:
    print(i-1)
Output:
0 1 4 5 2 76 8 -1 2 22 -0.6 -13.4 -4.12
Reply
#4
If you have an element, and subtract 1 from it, how would that be related to finding the difference between two different elements?

Try this:
our_list = [1,2,5,6,3,77,9,0,3,23,0.4,-12.4,-3.12]

for ndx in range(0, len(our_list), 2):
    left = our_list[ndx]
    right = our_list[ndx+1]
    print("{0} - {1} = {2}".format(left, right, (left-right)))
Reply
#5
pour_list = [1,2,5,6,3,77,9,0,3,23,0.4,-12.4,-3.12]

for i in range(0, len(our_list), 2):
left = our_list[i]
right = our_list[i+1]
print("{0} - {1} = {2}".format(left, right, (left-right)))
1 - 2 = -1
5 - 6 = -1
3 - 77 = -74
9 - 0 = 9
3 - 23 = -20
0.4 - -12.4 = 12.8
Traceback (most recent call last):

File "<ipython-input-5-3f1c5e913d44>", line 5, in <module>
right = our_list[i+1]

IndexError: list index out of range



why does it keep saying list index out of range?
Reply
#6
You have been warned 2-3 times before about not using code tag and indentation.
Read  BBCode help.
Short version use Ctrl+Shif+v when copy in code to keep indentation.
Mark all code and push button  [Image: python.png] 
Then code look like this.
class Parent:
    def my_method(self):
        print('Calling parent method')

class Child(Parent):
    def my_method(self):
        print('Calling child method')
        super().my_method()

c = Child()
c.my_method()
Try to follow this,if not your next post will be deleted until okay.
Reply
#7
Threads merged.  This isn't a separate issue, so no need for another thread.

...especially when your code is literally just my code, with the error I purposefully left in there, to help you think about what you're doing ;)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020