What function is better for what scenario? In Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What function is better for what scenario? In Python

Can someone please give a quick example, which statement is better for which scenario: 1. while/for loop : maybe for guessing number type of thing, or? 2. if/elif/else : maybe for yes or no type of thing, or? 3. try/except : maybe for user input type of thing, or? I know there isn't a perfect answer for it, but I would like to know in what certain situation, you will absolutely use that certain type of statements or functions.

21st Aug 2018, 3:31 AM
Vosen Chen
Vosen Chen - avatar
1 Answer
+ 1
while is used for looping over something that is conditional ex. wait for userinput or incrementation for is used for iterating over an iterable datatype or a generator ex. range, list, tuple if is used as a statement that is or isnt elif is used as a secondary if statement in the order they are given in else is used if the above statements are all false try is used when you might be expecting an exception from the code instead of getting an error except is used to output an exception to the user ex. zerodivision or a custom one. also finally: can be added to proceed to something after an exception.
21st Aug 2018, 9:58 AM
Markus Kaleton
Markus Kaleton - avatar