2. Hello World

Local Python interpreters can execute lines of code as you input them – for example, on a Mac from Terminal you may run the command ‘python3’, which will load the Python version 3 interpreter.

Input math functions

[cc lang=”python” width=”100%” height=”100%”]

2 + 2

[/cc]

Output

[cc lang=”python” width=”100%” height=”100%”]

4

[/cc]

Input print function

[cc lang=”python” width=”100%” height=”100%”]

# The print command echos back the data called within that function.
def main():
print (“hello world!”)

if __name__ == “__main__”:
main()

[/cc]

Output

[cc lang=”python” width=”100%” height=”100%”]

Hello World

[/cc]

Python lets you write code that is either procedural, or object oriented, so you may use classes. Classes are a great way of encapsulating functionality that can be kept together and passed around for use in other projects.

Classes

[cc lang=”python” width=”100%” height=”100%”]

class myClass:
def method1(self):
print(“myClass method1”)

# The ‘self’ argument refers to the object itself where it is being operated.

def method2(self, someString):
print(“myClass method2 ” + someString)

class anotherClass(myClass):
def method2(self):
print (“anotherClass method2”)

def method1(self):
myClass.method1(self);
print (“anotherClass method1”)

# ‘c’ instantiates method1 by calling on the class, ‘myClass’.
def main():
c = myClass()
c.method1()
c.method2(“This is a string”)

c2 = anotherClass()
c2.method1()
c2.method2()

if __name__ == “__main__”:
main()

[/cc]

The output from this script is

[cc lang=”python” width=”100%” height=”100%”]

myClass method1
myClass method2 This is a string
myClass method1
anotherClass method1
anotherClass method2

[/cc]

Comments are closed.