I'm new to Python so forgive me for such a newbie question but I have to ask.
I started from C++ and PHP, they have the operators { and } which could be used to set the loop execution range, even in VB there is such thing called "end for(while)" to define the range of the loop; But in Python, I searched for a while and I didn't see any article which can tell me that there is such thing?
I need to use the Loop to execute multiple lines of code, and I need a way to limit its execution area so the Loop won't affect the code after the Area I wish. Please tell me how can I achieve that.
In Python, consecutive lines with same amount of indentation form a 'BLOCK'
In the following example, statement 1 to 3 are in the same block.
for i in range(n):
statement 1
statement 2
statement 3
statement 4
Related
This question already has answers here:
When to use "while" or "for" in Python
(10 answers)
Closed 2 years ago.
Can someone explain me difference between for loop and while loop in easy language and with some example ?
I have trying to go through some websites or videos but the language may be little complicated for me
They mostly do the same thing, or they can be configured to do the same thing. But generally, for loop is used if we know how long the loop should run, and while is used if we need to loop "while" a condition is satisfied.
for i in range(0,10):
print("hello")
This will print "hello" 10 times, but if we want to print "hello" until a condition changes, we use while:
while(i != 20):
print("hello")
This will loop forever until i is changed to 20.
Both for loop and while loop are used to excute one or more lines of code certain number of times. The main differences are as follows.
Syntax:
While loop:
while(condtion) {
//statements to excute.
}
For loop:
for(intialization; condition; Increment or decrement){
// statements to be excuted.
}
There are few variations we can do with for loop.
Such as all three parts of for loop are optional. That means you can also have a loop like this.
for(;;) which is nothing but an infinite loop.
For initialization there can be multiple statements.
for(i =0, j =0;i<20;i++)
Similarly for the third component there can be any expression and not necessarily increment or decrement.
for(i =0;i<10;i = i * 2)
Working:
In while loop first of all the condition expression is evaluated and if it is true then the body of the loop is excuted. Then control again evaluate the condition expression. This goes on untill condition becomes false.
When solving a question of Project Euler I ran into the following logical error related to when n is updated.
while(n<1000):
#update n
#do something with n
#do stuff
vs
while(n<1000):
#do something with n
#do stuff
#update n
In the first instance, I ended up performing an operation with n even though the condition of n<1000 is violated.
Does this logical error have a name? How common is this bug?
I tried to look for it, I did find things about pre-incrementing and post-incrementing a variable. Although that is close to the error, it isn't exactly what is happening here. I found a reference to this in a SO answer about for loop vs while loop in the part describing how for loops are more concise and direct when compared to while loops. Essentially with while loops we end up running code after a variable update which could be buried somewhere in the code.
This is not always a bug: it depends on the algorithm. In some cases, you know that the original value of n is legal (so you can enter the loop), but you want to update and use the new value in your processing. You need to match your code to your algorithm. Your second code block is the canonical for-equivalent, and is more common.
This falls under the general heading of "off by 1 error".
display expression: prints out the value of an expression each time it gets changed. This is useful for monitoring the value of variables that get changed in loops. So, suppose the following is the code:
for i in range(100):
for j in range(100):
a=f(i,j)
I know something is wrong with the execution of a=f(i,j) for certain values of i and j. Then, how to use the display command from pdb module to find out the values of i and j when it does not work? I suppose when you use display command, it will display the value of i and j automatically, right? Do I need to combine the c command and b command from pdb module also? Many thanks for your time and attention.
display sets a "watch", so that each time execution stops (whether by completing a next, a step, or an until, or breaking on a continue ), if the value has changed, it will print a message showing the old value and the new value.
Since you know something is wrong with your f function, your easiest solution is to put a break on that function, and set display of the inputs inside that scope. Since you have shown us nothing about f, I don't know what the input variables will be called at that level, but it's likely that it won't be "i" and "j", so set the display appropriately.
I find display most useful for when I'm stepping through code that involves loops, using n or s or c. It keeps track of variables for me, and saves me from having to print the variables I'm interested in. If you know your problem is in f, you'll have to step through the code there yourself, and check all the variables at all the interesting statements. If you find yourself checking a variable repeatedly, that's where you use display.
This is probably a dumb question, but I'm new to programming and I have a recursive function set up that I'm trying to figure out. For any print function in Python, is it necessarily true that lines are printed in the order that they are written in the script OR for larger outputs, is it possible that smaller length outputs can get printed first in the console even though the print statement is later in the code (maybe due to some memory lag)?
Example:
def test_print():
#don't run this, but was meant for scale. Is there any chance the 1 would print before the list of lists?
print([[i for i in range(10000)] for j in range(10000)])
print(1)
Print statements pile output into stdout in the order the code was written. Top to bottom. It isn't possible any other way because that's the way the code is interpreted. Memory lag doesn't play any role here because the output to your console is a line for line rendition of the data that was piled into stdout. And the order the data was written to it can't change, so you'll maintain chronology. Of course, you can always play around with the how the print function itself works. But I wouldn't recommend tampering with standard library functions.
As said above, print() function is executed in the order which they are in your code. But you yourself can change the order in which you want it executed, after all you have every right to instruct the code to do whatever you want.
You'll always get the same order in the output as the order you execute print() functions in Python.
I have a piece of coding that is most basically a quiz. I had error handling so that if someone pressed a letter or anything other than a number, it would carry on with the quiz instead of letting the person attempt another question. (For example, if question 5 was 2+3 and they entered t, then it would carry on and not give them a different question for question 5).
I tried to update the coding, so it would loop:
def random_question():#defines function to get random question
count = 0#equates count to 0
for number in range (0,10):#makes the code generate the question 10 times
try:#the code makes it so the computer tries one thing and is the beggining
questionList = [random_sum,random_subtraction,random_times]#puts functions in a list to be called on
randomQuestion = random.choice(questionList)#calls on the list to generate the random questions
randomQuestion()#calls on variable
except ValueError:#if there is a value error or a type error it will notice it and try to stop it
print ("Please enter a number")#prints out the statement if there is a type error or a value error
else:
break
random_question()#calls on the function random_question
However, it comes up with a syntax error, and highlights the 'except' part next to the ValueError.
Any help as to why this is would be much appreciated.
Your except statement should have the same indention as your try statement. In your sample code it is indented an extra tab which would cause that error.
Python takes indention seriously and it is often the culprit. I'm unclear if your def line is a place holder or if this code is part of it, but if this code is part of the function definition you have other indention issues to worry about.
I'd suggest going through it carefully and making sure everything is lined up properly. The basic rule of thumb is, if something is part of something else, it is indented under it.
def something():
step 1
step 2
if (condition):
the true thing
else:
the false thing
while (something):
repeat something
this is not part of the function anymore