Python Forum
Can't make it print 0 if false
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can't make it print 0 if false
#1
I'm working on a little code for class and I'm not sure what to do to make it print 0 when everything else is false.

Input:
1 -3 4 -2 1

a = [int(i) for i in input().split()]
for i in range(1, len(a)):
  if a[i - 1] * a[i] > 0:
    print(a[i - 1], a[i])
    break
Output:
Output:
No output (0 is expected)
I have no idea where to start to get that part working.

P.S. Here is the problem:
Given a list of non-zero integers, find and print the first adjacent pair of elements that have the same sign. If there is no such pair, print 0.
Reply
#2
for i in range(1, len(a)):
1. You don't need range() when looping over an iterable type, you can just provide the iterable.
2. i is a particular item from the list, starting with first one, and moving to next as loop goes forth. If you want index, then you can use enumerate(), which returns a tuple of form (index, item).

a = [int(i) for i in input().split()]
for index, number in enumerate(a[:-1]):
    if a[index] * a[index+1] > 0:
        print(a[index], a[index+1])
        break
a[:-1] means elements of a from first to one before last. In my example this is needed because list index could go out of range with last iteration.
As for the 0 to be printed in case no numbers are found you have several options. You could use a flag variable and set it in loop if proper pair of numbers is found. In the end you can print 0 only if the flag is set.
Reply
#3
Today I have learned that for loops can also have an else clause, which are executed if break statement doesn't get executed in the loop. This is a way better alternative to the flag idea I gave in previous post.
Reply
#4
a = [int(i) for i in input().split()]
for i in range(1, len(a)):
  if a[i - 1] * a[i] > 0:
    print(a[i - 1], a[i])
    break
  if i >= len(a)-1:  #added line
      print 0        #added line
try add the last 2 lines. 0 printed when eveything is false and the loop meets its end
Reply
#5
(Jan-28-2018, 04:28 AM)ka06059 Wrote:
a = [int(i) for i in input().split()] for i in range(1, len(a)): if a[i - 1] * a[i] > 0: print(a[i - 1], a[i]) break if i >= len(a)-1: #added line print 0 #added line
try add the last 2 lines. 0 printed when eveything is false and the loop meets its end

Thanks, this worked.
Reply
#6
a = [1, -3, 4, -2, 1]
for n, m in zip(a[:-1], a[1:]):
    if n*m > 0:
        print(n, m)
        break
else:
    print(0)
Reply


Forum Jump:

User Panel Messages

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