Get Delayed output of a variable - python

hey I have a Loop That is always running That keeps changing a variable Called X like this
And It keeps running And keeps changing. And I want to get the previous output of the variable. How Can I do this?
while True:
X = X+10
X = X*5
print(X)

You can put them in an array and select the last element of the array

I assume this is what you're looking for when you say previous output of variable. I'd suggest you to also read on loops if you've just started with python. Here's a source
while True:
print(x) #this will print value X after each iteration
x= x+10
x= x*5

The psuedo code:
arr1 = []
infinte loop:
x= x+10
x= x*5
append x to array
print arr1 index current time looping minus one

Related

How to add numbers from a for loop in a list?

I tried to make a loop that ranges from 1 to 101 and then I tried to add those numbers to a list, but when I run the code, it makes a new line from every number it added so it will look like a huge half pyramid. I want my code to make a single line that shows all numbers in that list.
Here's the code:
nr_random = []
x = 1
for x in range(1, 101):
nr_random.append(x)
print(nr_random)
You can just print the numbers in the list after the for loop executes:
x=1
for x in range(1,101):
nr_random.append(x)
print(nr_random_greu)
I found the answer, just write print(nr_random_greu) outsite the loop
Just create a variable for the last added item:
x=1
nr_random = []
for x in range(1,101):
nr_random.append(x)
last_element = nr_random[-1]
print(last_element)
You are adding numbers to the list (assumed to be nr_random) correctly. Just print the list outside the for loop. Everytime you print it inside it will print the list filled till the ith iteration of the loop on a new line.

List comprehensions in Python "freezing" Jupyter notebook

When I run the code below in Jupyter notebook, my "kernel" freezes (I get an asterisk between the square brackets like so: [*]):
x = [1,2,3,4]
for num in x:
x.append(num**2)
Why doesn't this code "append" the exponentiated numbers to the end of x?
The code below works and I understand why, but why doesn't the code above work:
x = [1,2,3,4]
out = []
for num in x:
out.append(num**2)
print(out)
You are iterating over a list, and in every iteration you append a new element to the list, so the iteration is never going to end.
To see what's happening, change your code to this:
import time
x = [1,2,3,4]
for num in x:
x.append(num**2)
time.sleep(0.5)
print(x)
If you know what you are doing, you can avoid this kind of "dynamic iteration" with the [:] trick:
x = [1,2,3,4]
for num in x[:]:
x.append(num**2)
This way you are iterating over x[:], not the growing x, in effect it's like you are iterating over a snapshot of x.
More concisely, you could use a list comprehension as follows:
x = [1,2,3,4]
x_squared = [elem**2 for elem in x]
x.extend(x_squared)

Errors trying to append specific number of floats from user input

x={}
continueQ=input("would you like to continue?"))
if (continueQ=="yes"):
#if there is less than 4
if x<4:
variable=float(input("Input a float to append to the array:")
x.append(variable)
print(x)
else:
print(x)
else:
print("Goodbye!")
There are a few errors in this code, could someone help me how to create an if statement to check if there are minimum than 4 values inside an array .
Also how to append to an array from an input.
Create a list with x = [], Use len(x) to get the length of list, use while loop with condition if x<4
x=[]
continueQ=input("would you like to continue?")
if (continueQ=="yes"):
#if there is less than 4
while len(x)<4:
variable=float(input("Input a float to append to the array:"))
x.append(variable)
print(x)
else:
print(x)
else:
print("Goodbye!")
The first thing you'll want to do is change that x={} to an x=[]. What you've done is create a dictionary rather than an array, and consequently will run into an assortment of issues as you're dealing with the wrong data structure.
Once you've done that, we can move on to how to check if there are less than 4 values inside an array. In Python, arrays carry a length attribute, which can be accessed by writing len(arrayName), or in your case, len(x). For example, if your array x contained the following values: [1,2,3], then len(x) would return 3, seems simple enough.
Now to check that the length is less than 4, you need to replace your if x<4: with if len(x)<4:.
You already have the correct code to append to your array, it likely wasn't working before because you created a dictionary instead of an array.
There are several errors in your code. Here's a working version:
x = []
continueQ = input('Would you like to continue?')
if continueQ.lower() == 'yes':
while len(x) < 4:
variable=float(input('Input a float to append to the array:'))
x.append(variable)
print(x)
print("Goodbye!")
Explanation
[] represents an empty list, while {} is use for an empty set.
Make sure your bracketing is consistent; all open brackets must be closed.
Use len(x) to find the number of entries in a list x.
Use a while loop to repeat logic until a criterion is satisfied.

random.choice shows the same answer if you use a variable

When I run this code, print(x) will print the same letter every time, and yet when I run it like the second example print(random.choice(b)) it works as expected. What is the difference? I checked for an answer a found references to "seeding", but I am not using random.seed() prior to this.
import random
b = "Hello World"
x = random.choice(b)
print(x)
print(x)
print(x)
# same answer as many times as you want to print
print(random.choice(b))
print(random.choice(b))
print(random.choice(b))
# random choice each time
By printing an assigned value 3 times will not change the value of the variable unless u call the random function to generate a new random variable again:)
random.choice(b) gets called only once when you assign the return value to x, it does not get called again each time you reference that variable. Each time you print x you are seeing the result of that initial assignment. When you do print(random.choice(b)) it is calling random.choice() on b each time. It would indeed be quite problematic if the value assigned to a variable changed each time you reference the variable.
There is really not much difference between what you are doing here:
x = random.choice(b)
print(x)
and what you are doing here:
print(random.choice(b))
The difference is that you do the latter 3 times (i.e., you call random.choice() 3x and print the result 3x), so you see 3 different results. If you do:
x = random.choice(b)
print(x)
x = random.choice(b)
print(x)
x = random.choice(b)
print(x)
You will see a different result each time (or at least a random result each time - it could be the same).
The difference is that the first one, x = random.choice(b) sets x to a random and then prints x, the letter that was randomly selected from b. It only randomly selects what x is when you declare x. The second, print(random.choice(b)) generates a new random every time.
You could use the following code to make x equal to random.choice:
b = "Hello world!"
x = random.choice
print(x(b))
And that does the same thing as print(random.choice(b)).

Appending to 2 lists simultaneously

I have a piece of Python code that looks something like this:
array1 = []
array2 = []
def my_function():
# do some stuff
return x, y # both are integers
# append x to array1; append y to array2
What I'm trying to do is append the outputs of my_function to separate arrays. I understand that I need to somehow separate my_function's 2 outputs and then make 2 separate append() statements, but I'm not quite sure how to implement that.
Thanks in advance!
x, y = my_function() #get x,y returned from my_function()
# append x to array1; append y to array2
array1.append(x)
array2.append(y)

Categories

Resources