Python Forum
If loop inside of a while loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
If loop inside of a while loop
#1

I have a problem where, I'm trying to use an if loop inside of a while loop to create an array. Its running infinitely.
Anyone see my problem?
import numpy as np

x = np.linspace(1, 100, num = 100)

def append(start, stop, change):
    s = ([])
    x = 0
    while x <= 10:
        if x < start:
            s = np.append(s, 0)
            x = x + 0.01
        elif start <= x <= stop:
            s = np.append(s, change)
            x = x + 0.01
        elif x > stop:
            s = np.append(s, 0)
            x = 0.01
    return s
s = append(3, 7, 0.01)
Reply
#2
In line 17, you reset x to 0.01 because x is above 7 (the value of stop) and your while loop stops when x is greater 10 !
Reply
#3
That would be because when x > stop, you set x to be 0.01, which is less than or equal 10 (your while loop condition).
Reply
#4
OH OKAY, that's the problem. I completely missed that typo. Thanks ya'll! Smile
Reply
#5
minor quibble: your if conditional is not a loop.

while is conditional and also a loop, if is conditional but it is not a loop-- though its certainly understandable why someone would think of it as one.

while x > 5:
    print(True)
    break
does the same as:

if x > 5:
    print(True)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Matplotlib scatter plot in loop with None values ivan_sc 1 2,268 Nov-04-2021, 11:25 PM
Last Post: jefsummers
  while loop mazeemagha 2 1,785 Aug-28-2021, 03:24 PM
Last Post: naughtyCat
Question I want to vectorize a really long for loop to improve performance Miregal1 1 1,962 Jul-18-2021, 11:13 AM
Last Post: jefsummers
  change for loop into numpy functions ToffiFaye 1 1,981 Feb-06-2021, 11:38 AM
Last Post: paul18fr
  Change classic loop to TensorFlow tf.while_loop vsl_neuro 0 1,776 Dec-15-2020, 07:57 AM
Last Post: vsl_neuro
  Python PDF merging from an excel pandas for loop siraero 0 2,189 Aug-16-2020, 09:34 AM
Last Post: siraero
  KeyError: 1 on a simple loop? preliator 0 2,093 Aug-14-2020, 02:13 PM
Last Post: preliator
  while loop problem fid 2 2,238 Jun-19-2020, 07:21 PM
Last Post: fid
  Creating new lists with names depending on a changing integer in a while loop l_butler 0 1,569 May-24-2020, 04:05 PM
Last Post: l_butler
  Breaking a loop in Multiple Random Walks PythonGainz 10 4,150 May-01-2020, 03:15 PM
Last Post: buran

Forum Jump:

User Panel Messages

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