How do I get the output using while loop? - python

I am not getting the output I am expecting. The output should be the sequence of values of less than 6. Is something wrong in the syntax? I think it has very simple error!! I am not getting it.
Write a while loop to display the values of the Rating of an album playlist stored in the list PlayListRatings. If the score is less than 6, exit the loop. The list PlayListRatings is given by: PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
PlayListRatings=[10,9.5,10,8,7.5,5,20,10]
rating=0
i=0
while rating<6:
rating=PlayListRatings[i]
i=i+1
print(rating)
>>output 10

I think it's easier to use a for loop:
for item in PlayListRatings:
if item < 6:
break
print(item)
If you must use a while loop:
index = 0
while index < len(PlayListRatings) and PlayListRatings[index] > 6:
print(PlayListRatings[index])
index += 1

You define I=0 but then use i=i+1. Python is case sensitive, so you need to use the same casing (i.e. set i=0 instead of I=0).
If the score is less than 6, exit the loop.
This means that your while condition is incorrect. It should be while rating >=6.
I would highly recommend reviewing conditional statements, looping, and basic python syntax.

While loops are generally used when you don't know when the loop is expected to end, for loops are better when you know the loop will end.
In your example you are looping through a list, you are better using a for loop.

Take a look at this:
PlayListRatings=[10,9.5,10,8,7.5,5,20,10]
rating=0
i=0
while i != len(PlayListRatings):
rating = PlayListRatings[i];
if rating < 6: print(rating);
i=i+1;
I know that while loop logic needs some time to get accustomed to. Here is what you need to think of when building a while loop:
When building a while loop: Logic that governs while loop needs to be negative.
## don't run this , it is an infinite loop
iDontWantThis = false; # starting argument
# it is always false, so the loop will go forever
while iDontWantThis == false:
print("I want this");
So when iterating over a list of some kind, the logic that governs when you exit the loop, must not be the same logic that you wish to implement inside the loop. That is main difference between while and for loops.
In your case , your main logic was to print out any element in list that was smaller than 6, so in while loop you need to have logic that is either:
1. For rating that is greater than 6
2. For i index that is smaller than list length
3. Infinite loop with break points inside while loop.
Python is case sensitive : which means that I and i aren't the same variable. But this can happen even to experienced programmers.
Beginner while loop building : when you start learning about while loops. The best course of action is to start with infinite loops, and then implement breaks where you need them. When your code works, then you optimise it so you don't have too much lines and it gets faster.

Related

In this For loop why is the variable not referred to within the body of the expression

From my understanding of for loops, you are defining the variable in the first line of the argument, you then use this definition in the body of the loop where you create an expression which involves the variable.
Here the for loop is iterating over a sequence of 1-10 and creating a list of head/tails. Why is x (the variable) not referred to in the body, and how does the code know to iterate over the 1-10 sequence if x is not referred to in the if-else statement. Sorry I'm a beginner, so very basic
import numpy as np
np.random.seed(123)
outcomes = []
for x in range(10) :
coin = np.random.randint(0, 2)
if coin == 0:
outcomes.append("heads")
else :
outcomes.append("tails")
print(outcomes)
Blockquote
From my understanding of for loops, you are defining the variable in the first line of the argument
You are defining a variable whose job is to decide how many times to repeat the block of code below.
Blockquote
you then use this definition in the body of the loop where you create an expression which involves the variable. Here the for loop is iterating over a sequence of 1-10 and creating a list of head/tails
You can if you choose to use this variable in the body of the loop in an expression.
For example here, you want to double all the numeric values up to, but not including 10. Since you know that your for loop will generate all the numbers from 0-9 for you, it makes sense to re-use that value in your loop body that prints the numbers.
for x in range(10):
print(x*2)
However, like in your case, you want 10 random choices, represented as TRUE/FALSE, 0/1, or HEADS/TAILS. The x value that counts how many times you repeat your code block has no impact on whether the outcome is a HEADS or TAILS. Therefore there is no need to use x in the indented code block. You can just let it do it's one job, which is keeping track of how many times you want to repeat the code block.
That is neat feature of Python.
Consider
for x in something:
If something is iterable, the for loop will interate over its elements.
That also means you do not need to access list elements by index:
for x in ['first', 'second', 'third']:
print(x)
#Output
first
second
third
Range in addition is a something like a generator function which generates equally spaced integers (it actually is a sequence object, see link below). In your case, where you did insert only ony argument, the spacing is 1, so it will generate numbers starting from 0 until 9 (the given argument is not part of the generated sequence).
For more details on loops in python see for example here
For details on range, pretty interesting stuff about what range is doing under the hood.
I think I didn't understand your question, but if you meant how can the code know the variable and close the loop when it's done, then you need to know that the range(1, 5)object returns the list [1, 2, 3, 4] and the for loop must be given a list or any other iterator type, and the code:
for x in range(1, 5):
print('loop')
reads the items of the list one by one and save it as x and do everything inside the for loop until the list has no more items, and when the list is over, the the code will stop repeating the loop and will go to the next line after the loop, the variable doesn't necessarily have to be used (i.e. save it in a throwaway variable like _), but it can be used to know if end of the loop arrived and change the loop according to it's variable.
you can tell me if this is not what you meant and give me more explanation about the question.

Is it possible to have multiple conditions in a function which includes a for loop in Python?

I'm new to programming with Python. Currently, I'm working on a program/algorithm to determine maintenance (combined replacement of multiple items) based on these items their condition. To be precise, I want to replace these items when one item's condition is below a predetermined threshold (for example 10%). The problem I have with my code, see below, is when this threshold is met all items are replaced.
def maintenance_action(self):
do_repair = False
for i in item:
if i.condition[-1] <= 10:
do_repair = True
break
if do_repair:
for i in items:
i.repair()
However, I want to include an additional threshold (let's say 50%) which excludes all items with a condition > 50% from the maintenance action. It is important that the first threshold is met (because this item must be replaced) before the second one 'kicks in' (the items I want to include). I hope someone can help me.
Thanks!
The simplest way would be to call repair right away, and not use a flag at all:
for i in items:
if i.condition[-1] <= 10:
i.repair()
Or, if you can't do that, you could build a list of items to be repaired in the first loop, and then process that list later:
items_to_repair = []
for i in item:
if i.condition[-1] <= 10:
items_to_repair.append(i)
# other code here
for i in items_to_repair:
i.repair()
If do_repair is set to True in the for loop when the condition is met, all the variables are repaired in the second loop. In order to prevent this, you should repair the items which are met to the condition in the first loop. So I think there is no need to use the do_repair variable and the second for loop in this case.
def maintenance_action(self):
for i in item:
if i.condition[-1] <= 10:
i.repair()

Trouble understanding break vs else statements with nested loops

I'm practicing python and one of the coding tasks assigned was to create a function that looks through a list and ignores numbers that occur between a 6 and a 9 and returns the sum of all other values.
Edit: this does not mean to add numbers whose values are less than 6 or greater than 9. It means to add all numbers of any value, but to ignore any numbers that come after a 6, until a 9 is seen. Symbolically if i means include and x means exclude, the code should return all the values marked as i:
[i,i...6, x,x,...,9,i,i...,6,x,x,...]
In other words, 6 turns off adding and if adding is off, 9 turns it back on.
Note that a 9 with no preceding 6 is just a number and will be added.
For example if I have a list:
[4,5,6,7,8,9,9]
the output should be:
8 <---(4+5+9)
The solution is provided but I'm having trouble understanding the code. I don't understand the purpose of the break statements in the code. The solution provided is as follows:
def summer_69(*arr):
total = 0
add = True
for num in arr:
while add == True:
if num!=6:
total = total + num
break
else:
add = False
while add == False:
if num !=9:
break
else:
add = True
break
return total
I'm really confused how the break statements help with the code. Particularly, I'm confused why the first 'break' is needed when there is already an 'else'.
The second break confuses me as well.
I understand that 'break' statements stop a loop and go onto the next loop.
My interpretation of the code so is 'if the number does not equal to 6 then total = total + num, if it does equal 6 then the loop is broken and if it is broken, add changes to False'.
I'm not sure if that interpretation is correct or not.
I was wondering how seasoned Python coders interpret 'breaks' vs 'else'.
break will exit whatever loop the statement is in. It's useful for many things, but often it's used to "short-circuit" the loop. If we know that the rest of the loop is irrelevant after some condition is met, then it's just wasted resources to keep looping through.
The break statement allow you to leave the while loop, but the if else statement allow you to stay in loop, until the condition of the while loop change or a break statement is in the action into the while loop
The solution you've provided is extremely convoluted and hard to understand.
A much better solution is:
total = 0
for num in arr_2:
if(num >= 6 and num <=9):
continue
total += num
Or a more pythonic way:
filtered_arr = filter(lambda x: x <6 or x > 9, arr_2)
total = reduce(lambda x, y: x + y, arr)
Anyways, in your solution, the first break is absolutely redundant. The reason why there is a break there, is because when you've found a number that doesn't equal 6, you add it, and you get out of the while loop.
In other words, the solution should have used an if statement, instead of the while statement. The break is there to basically have the while loop execute once.
Because, if a number does equal 6, then add will be false, and the while loop will terminate. If a number does not equal 6, you get out of the while loop. So the while loop is pointless, and meant to be an if statement instead.
This is a tricky way to handle program flow with a toggle nested in conditional loops.
It's a little hard to follow, but it is a well-known classic pattern.
Initially ADD == True, so if we start with a number that is not 6 (as in your example), the algorithm adds the number & breaks out of the first while loop. When it breaks, the next statement executed will be the line while add == False
At this point ADD == TRUE so the second while loop will not be entered. The next statement executed will be for num in arr (the outermost loop).
The outer FOR loop will go again and this process will repeat.
When you encounter a 6, the number will not be added and the break will not occur. The program will execute the else clause, setting ADD = FALSE.
After the else clause, execution continues with statement while add == false. Since ADD == FALSE at this point, the second while loop will be entered.
From now on ADD will be FALSE so the first While loop will not be entered and numbers will not be added. Instead, the condition for the second while loop will be evaluated for each number. As long as numbers are not equal to 9, the second while loop will not be entered.
When you encounter a 9, you will enter the second while loop, switch ADD back to TRUE, and break out of the while loop.
The first 9 comes after a 6 (ADD is FALSE) so it just toggles ADD from FALSE to TRUE and the number 9 doesn't get added.
When the NEXT 9 is encountered, ADD is TRUE and the number is not 6, so the first while loop will be entered and the number 9 will get added.
This is a classic pattern that used to be used in assembly language code perhaps 40 years ago. As written, the IF statements toggle a state variable. The state variable is turned on when the start condition is met, and turned off when a stop condition is met. The while loops ensure that the toggle can only be turned ON when it was OFF and vice versa, and provide places to put in different handling when the state is ON vs when it is OFF. This pattern brings certain efficiencies that are completely irrelevant in modern high-level languages.
There are better ways to do this in all modern languages, but as an exercise in following tricky program flow it's quite good :)

Looping for loop in Python

I have the following code.
for idx in range(len(networks)):
net_ = networks[idx]
lastId=0
for layerUptID in range(len(net_[1])):
retNet,lastId=cn_.UpdateTwoConvLayers(deepcopy(net_),lastId)
networks.append(retNet)
if(lastId==-1):
break
networks has only one net at the beginning.
After running the line retNet,lastId=cn_.UpdateTwoConvLayers(deepcopy(net_),lastId), I have additional six nets and appended to networks.
So after this lastId ==-1, go back to first for loop with len(networks) is 7.
For the next idx, idx=1 and continue.
Then, len(networks) is 13. Then go back to first for loop.
After this, the first for loop breaks.
I am expecting to continue for idx is 2, but it breaks.
What could be the issue?
If you try using a WHILE loop instead of FOR loop, the break statement would be check if the loop is on the last item in 'networks' collection.
This way the network length would be calculated in each loop iteration
For starters: Iterating, or looping, over the list (or data) you're editing is bad practice. Keep that in mind while coding.
This means if you plan to edit what you're looping on, in your case networks, then you're going to have a bad time looping over it. I would advise to break it up into two code parts:
The first part creates a new list of whatever it is you want WHILE looping.
The second part replaces the list you've used to generate what you wanted.
Another thing which could go wrong is net_[i] may not be set up for some i, and you're trying to access it here:
for layerUptID in range(len(net_[1])):
What if there is nothing in net_[1]?
To avoid these errors, usually verifying your data is a great way to start. If it is not null, then proceed, otherwise, print an error.
This is what I can think of. Hope it helps.
If I understood correctly your problem is that you've added new elements to networks, i.e. have increased length of networks and expect that for-loop will pick up this changes, well it's not, let's look at following snippet
elements = [1]
indices = range(len(elements))
for index in indices:
print('index is', index)
elements.append(2)
print('elements count is', len(elements))
print('indices count is', len(indices))
outputs are
index is 0
elements count is 2
indices count is 1
so as we can see despite the fact that length of elements list has changed, range object which is used in for-loop has not. This happens because len returns int object which are immutable, so when you change list length its length becomes different object and range function has no idea about this changes.
Finally, we can use while loop here like
while networks:
net_ = networks.pop()
lastId = 0
for layerUptID in range(len(net_[1])):
retNet, lastId = cn_.UpdateTwoConvLayers(deepcopy(net_), lastId)
networks.append(retNet)
if lastId == -1:
break

Printing one character at a time from a string, using the while loop

Im reading "Core Python Programming 2nd Edition", They ask me to print a string, one character at a time using a "while" loop.
I know how the while loop works, but for some reason i can not come up with an idea how to do this. I've been looking around, and only see examples using for loops.
So what i have to do:
user gives input:
text = raw_input("Give some input: ")
I know how to read out each piece of data from an array, but i can't remember anything how to do it to a string.
Now all i need is working while-loop, that prints every character of the string, one at a time.
i guess i've to use len(text), but i'm not 100% sure how to use it in this problem.
Some help would be awsome! I'm sure this is a very simple issue, but for some reason i cannot come up with it!
Thx in advance! :)
I'm quite sure, that the internet is full of python while-loops, but one example:
i=0
while i < len(text):
print text[i]
i += 1
Strings can have for loops to:
for a in string:
print a
Other answers have already given you the code you need to iterate though a string using a while loop (or a for loop) but I thought it might be useful to explain the difference between the two types of loops.
while loops repeat some code until a certain condition is met. For example:
import random
sum = 0
while sum < 100:
sum += random.randint(0,100) #add a random number between 0 and 100 to the sum
print sum
This code will keep adding random numbers between 0 and 100 until the total is greater or equal to 100. The important point is that this loop could run exactly once (if the first random number is 100) or it could run forever (if it keeps selecting 0 as the random number). We can't predict how many times the loop will run until after it completes.
for loops are basically just while loops but we use them when we want a loop to run a preset number of times. Java for loops usually use some sort of a counter variable (below I use i), and generally makes the similarity between while and for loops much more explicit.
for (int i=0; i < 10; i++) { //starting from 0, until i is 10, adding 1 each iteration
System.out.println(i);
}
This loop will run exactly 10 times. This is just a nicer way to write this:
int i = 0;
while (i < 10) { //until i is 10
System.out.println(i);
i++; //add one to i
}
The most common usage for a for loop is to iterate though a list (or a string), which Python makes very easy:
for item in myList:
print item
or
for character in myString:
print character
However, you didn't want to use a for loop. In that case, you'll need to look at each character using its index. Like this:
print myString[0] #print the first character
print myString[len(myString) - 1] # print the last character.
Knowing that you can make a for loop using only a while loop and a counter and knowing that you can access individual characters by index, it should now be easy to access each character one at a time using a while loop.
HOWEVER in general you'd use a for loop in this situation because it's easier to read.
Try this procedure:
def procedure(input):
a=0
print input[a]
ecs = input[a] #ecs stands for each character separately
while ecs != input:
a = a + 1
print input[a]
In order to use it you have to know how to use procedures and although it works, it has an error in the end so you have to work that out too.
Python allows you to use a string as an iterator:
for character in 'string':
print(character)
I'm guessing it's your job to figure out how to turn that into a while loop.
# make a list out of text - ['h','e','l','l','o']
text = list('hello')
while text:
print text.pop()
:)
In python empty object are evaluated as false.
The .pop() removes and returns the last item on a list. And that's why it prints on reverse !
But can be fixed by using:
text.pop( 0 )
Python Code:
for s in myStr:
print s
OR
for i in xrange(len(myStr)):
print myStr[i]
Try this instead ...
Printing each character using while loop
i=0
x="abc"
while i<len(x) :
print(x[i],end=" ")
print(i)
i+=1
This will print each character in text
text = raw_input("Give some input: ")
for i in range(0,len(text)):
print(text[i])

Categories

Resources