r/learnpython • u/NightCapNinja • Jun 29 '24
Whats the difference between "try" and "while" in Python?
Hi, I'm having a hard time understanding the difference between the try and while function, what is the difference between these 2? Anyone explaining it to me would be appreciated, thank you.
13
u/GXWT Jun 29 '24
while <condition> is a loop. So 'while' the condition is true, it will keep running the loop. For example:
x = 0
while x < 10:
print(x)
x += 1In this case, with x starting at 0, it enters the while loop, prints x (so it prints '0') and then adds 1 to x. It reaches the end of the loop, so it goes back up to while, and evaluates the condition. x is only 1 at this point, which is less than 10, so it once again prints x (prints '1') and adds 1 to x again. This repeats until x=10, and which case the condition x<10 is no longer true, so the rest of the loop can be run.
A try except block is a separate thing. Basically you use it to 'try' to some that may produce an error:
x = 10
y = 2
try:
print(x/y)
except:
print('code failed')The code within 'try' will be run first. In this case, printing 10/2 produces no error so the 'except' block is not ran and your program can continue succesfully. But what if y=0? We can't divide by 0 and, specifically, in python it produces a ZeroDivisionError. In this case, a python program would usually fail and stop running. But an except block catches any error, and takes over if the code fails. So it would print 'code failed'.
As a beginner you question why this is useful - why would I want to stop something that would break my code? But that will come with time and experience. There's more you can do with this, like catching specific errors. https://www.w3schools.com/python/python_try_except.asp
9
u/SnipahShot Jun 29 '24
While the condition is true, do something.
Try to do something, if failed do something else afterwards.
1
13
u/NerdyWeightLifter Jun 29 '24
"while" is for doing loops.
i = 1
while i < 10:
print(i)
i = i + 1"try" is the start of a section of code where you want to catch exceptions.
a, b = 2, 0
try:
c = a / b
except ZeroDivisionError as _e:
print("Can't divide by zero")
13
u/engelthehyp Jun 29 '24
Pardon me, but... how are these at all similar? To you, I mean, what made you think that?