Whats the difference between a while loop and a for loop?
Reddit
Python While Loop
If you want to modify a global from within a function scope you need to use global in the function (basically saying "use the upper scope instead of local"). Generally though try to avoid globals as good programming style.
Example demonstrating this:
global testMore on reddit.com
def set_true_local():
test = True
def set_true_global():
global test # Use global version of test
test = True
test = False
print('Before: {}'.format(test)) # False
set_true_local()
print('After set_true_local: {}'.format(test)) # False
set_true_global()
print('After set_true_global: {}'.format(test)) # True
I've trying to learn while loops for over 2 weeks... Help? [ELI5]
You have two variables, m and c. The variable m is what the user inputs to determine what height the ball is dropped from. The variable c will count the number of bounces.
Then the while loop starts. Quite literally, while the ball bounces back to a height that is greater than 0.01, your program keeps executing the rest of the code over and over.
In this specific case, your program first decreases the height to 70% of previous value (so it bounces back lower due to gravity), then increments the c counter by one, so says the ball bounces one time.
Then the instruction in the while loop is over. The program checks again if the height m is greater than 0.01. If it is, it will keep repeating the while loop code block until the condition is no longer met. If it isn't, it will do the rest of the code. In this example it will print that the ball has bounced c number of times.
You print c because that is the variable where you store number of bounces. If you printed m it would print the height the ball is at right now, after all those operations. Which would mean it would print a number that's less than 0.01.
Q1. What is while loop in Python?
Q3. Can we use else with While loop in Python?
Q4. How to stop the infinite while loop in Python?
Videos
I want to ask, whats the difference between looping using the while and the for function? I know both of these functions loops through stuff but what exactly is the difference between them? I have trouble understanding so I decide to ask this question on here