Intro To Lists Loops And Functions
Lists
Lists are one of the most common data structures in Python.
Features:
Mutable
Members do not have to be same type
Ordered
sample_list = ['hello', 4, False]Useful operations:
len(list)returns number of memberslist[0]returns member at indexNote: Accessing members at an index that doesn't exist will throw an
IndexError
list.index('dog')returns the index of the valuelist.append(item)adds item to the endlist.pop()removes and returns last itemlist.pop(1)removes and returns item at given indexitem in listchecks if item is a member of the list and returns boolean
Loops
Loops repeat a process/operation multiple times.
for loops run x amount of times (whatever you decide), and while loops run indefinitely as long as a condition is met.
for
forIterating over a list:
Iterating over a string:
Iterating over a range of integers (useful when you want to run a code block a specific number of times):
while
whileJust be careful with a while loop because if the condition is never met, it never runs. And if the condition is always met, you'll run into an infinite loop that crashes your program.
Pro tip: A common use case is to continually request a specific input, re-asking until the user actually provides it.
To exit a while loop completely, simply use the break keyword.
To move onto the next iteration in a while loop, simply use the continue keyword.
Functions
Functions are just blocks of code that can accept an input, performs some computation, and then can return an output. They are useful for code reuse and help make your application more modular.
Built-in functions
Functions that are part of the core language. Python just hands them to you automatically.
User-defined functions
To create your own function, here's the basic syntax:
Pro tip: It's recommended to include a docstring as the first comment in your user-defined function. This description is accessible to any other dev via help(fn) or fn.__doc__.
The main function
main functionEvery Python module (i.e. file) has a special __name__ variable that's accessible.
If the file is being run as the main program,
__name__is set to"__main__"For all other modules,
__name__is set to the module's filename
Pro tip: Best practice when running a main program is to use the following code pattern:
Documentation (for users and programmers)
Last updated