0% found this document useful (0 votes)
4 views1 page

Understanding Python Main and Functions

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

Understanding Python Main and Functions

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

if __name__ == ‘__main__’:

main()

main() function used to define the program’s starting point

Allows us to import and run the program in another script

if statement checks whether the program is being run independently as the primary module or as a
library in another script

- If the file is being run through a command line, __name__ variable (stores the name of the
current module) becomes __main__ and the main() function is called
- If the file is being used as a module in another script, __name__ becomes the filename and
so the main() function doesn’t run

def factorial(num):

if num == 1:

return 1

else:

return num * factorial(num – 1)

base case avoids infinite recursions

square_lambda = lambda x: x ** 2

Lambda is an anonymous function => can take any number of arguments but one expression

Convenient for small throwaway functions but can only contain expressions not statements

Can be used for higher-order functions e.g. map(), filter() and sorted()

map() syntax => map(function, iterables)=> performs a function on each element in an


iterable

filter() filters an iterable then returns a new array/list without the filtered items

Object-orientated programming

A programming paradigm that allows for organisation of code with data states and functionalities =>
code becomes modular, abstract and easy to maintain

class = a data type encapsulating information and functions as a blueprint for objects i.e. their
attributes and methods

class ClassSchedule:

def __init__(self, course):

[Link] = course

__init__() method is a constructor and is called when an object is instantiated from the class. self
parameter refers to the current instance and the instance variable course can be assigned an input

You might also like