There are some differences in control flow in C# and Python though the concept in both languages is pretty much the same. Let’s take a look at them.
- Entry point
The entry point to Python program can be expressed like the following. class is NOT necessary in Python, so if you are working on a simple script, I would just start to write logic in the file without a class. That said, I still like to encapsulate everything classes.class Main: def __init__(self): pass def say_hello(self): print('hello Python!') if __name__ == '__main__': entry_class = Main() entry_class.say_hello()
- if elif else
Let’s think about the function that returns month name in a string.def get_month_name(num): if num == 1: return "January" elif num == 2: return "February" elif num == 3: return "March" elif num == 4: return "April" elif num == 5: return "May" elif num == 6: return "June" elif num == 7: return "July" elif num == 8: return "August" elif num == 9: return "September" elif num == 10: return "October" elif num == 11: return "November" elif num == 12: return "December" else: return "Invalid number" # Could throw an error
I know the sample is ugly, but you get the idea. switch statement is NOT available in Python unfortunately but there is a workaround. I will write about in a separate blog post.
- while
i = 0 while i < 100: print(i) i += 1
Not so elegant but while is still a necessary control statement.
- for
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9] for n in nums: print(n)
for in Python acts like foreach in C#. If you want to express something like for (int i = 0; i < nums.length; i++) {}, you can do something like the following.
for n in range(1, 10): print(n)
The sample shows that range function can be used to mimic “for (int i = 0; i < nums.length; i++) {}” in C#.