Sei sulla pagina 1di 27

“PROJECT

IN
IT CERTIFICATION-II”

SUBMITTED BY:

REBAñO, EMMANUEL SALGADO

VALENZONA, MELVIN BALABA

HIBAYA, LIEZEL ANTIOLA

MUTIA, JAKE LOURENCE POLGARES

MULIT, JOHN KENNETH DAGUPLO

SUBMITTED TO:

MR. GERSHOM DELA TORRE


BRIEF HISTORY:

What do the alphabet and the programming language Python have in common? Right,
both start with ABC. If we are talking about ABC in the Python context, it's clear that the
programming language ABC is meant. ABC is a general-purpose programming language and
programming environment, which had been developed in the Netherlands, Amsterdam, at
the CWI (Centrum Wiskunde & Informatica). The greatest achievement of ABC was to
influence the design of Python.

Python was conceptualized in the late 1980s. Guido van Rossum worked that time in
a project at the CWI, called Amoeba, a distributed operating system. In an interview with
Bill Venners1, Guido van Rossum said: "In the early 1980s, I worked as an implementer on a
team building a language called ABC at Centrum voor Wiskunde en Informatica (CWI). I
don't know how well people know ABC's influence on Python. I try to mention ABC's
influence because I'm indebted to everything I learned during that project and to the
people who worked on it."

Later on in the same Interview, Guido van Rossum continued: "I remembered all my
experience and some of my frustration with ABC. I decided to try to design a simple
scripting language that possessed some of ABC's better properties, but without its
problems. So I started typing. I created a simple virtual machine, a simple parser, and a
simple runtime. I made my own version of the various ABC parts that I liked. I created a
basic syntax, used indentation for statement grouping instead of curly braces or begin-end
blocks, and developed a small number of powerful data types: a hash table (or dictionary,
as we call it), a list, strings, and numbers."

So, what about the name "Python": Most people think about snakes, and even the
logo depicts two snakes, but the origin of the name has its root in British humor. Guido van
Rossum, the creator of Python, wrote in 1996 about the origin of the name of his
programming language1: "Over six years ago, in December 1989, I was looking for a 'hobby'
programming project that would keep me occupied during the week around Christmas. My
office ... would be closed, but I had a home computer and not much else on my hands. I
decided to write an interpreter for the new scripting language I had been thinking about
lately: a descendant of ABC that would appeal to Unix/C hackers. I chose Python as a
working title for the project, being in a slightly irreverent mood (and a big fan of Monty
Python's Flying Circus)."
Development Steps of Python:

Guido Van Rossum published the first version of Python code (version 0.9.0) at
alt.sources in February 1991. This release included already exception handling, functions,
and the core data types of list, dict, str and others. It was also object oriented and had a
module system.

Python version 1.0 was released in January 1994. The major new features included
in this release were the functional programming tools lambda, map, filter and reduce,
which Guido Van Rossum never liked.

Six and a half years later in October 2000, Python 2.0 was introduced. This release
included list comprehensions, a full garbage collector and it was supporting unicode.

Python flourished for another 8 years in the versions 2.x before the next major
release as Python 3.0 (also known as "Python 3000" and "Py3K") was released. Python 3 is
not backwards compatible with Python 2.x. The emphasis in Python 3 had been on the
removal of duplicate programming constructs and modules, thus fulfilling or coming close
to fulfilling the 13th law of the Zen of Python: "There should be one -- and preferably only
one -- obvious way to do it."

Some changes in Python 3.0:

 Print is now a function


 Views and iterators instead of lists
 The rules for ordering comparisons have been simplified. E.g. a heterogeneous list
cannot be sorted, because all the elements of a list must be comparable to each
other.
 There is only one integer type left, i.e. int. long is int as well.
 The division of two integers returns a float instead of an integer. "//" can be used
to have the "old" behavior.
 Text Vs. Data Instead Of Unicode Vs. 8-bit
AREAS OF APPLICATION:

Python can be more user-friendly because of its advantages. Please find below the uses of
python language for different reasons:

1. Applications:

Python can be used to develop different applications like web applications, graphic
user interface based applications, software development application, scientific and numeric
applications, network programming, Games and 3D applications and other business
applications. It makes an interactive interface and easy development of applications.

2. Multiple Programming paradigms:

Python is also used because of its providing continuous support to several


programming paradigms. As it supports object-oriented programming and structured
programming. Python has features, which also support various concepts of functional
programming language. It is used for dynamic type system and automatic memory
management. Python language features and programming paradigms allow you for
developing the small as well as large applications. It can be used for complex software
applications.

3. Robust Standard Library:

Python has a large and robust standard library to use for developing the
applications. It also makes the developers use Python over other languages. The standard
library helps in using the different range of modules available for Python. As this module
helps you in adding the functionality without writing any more code. To get the information
about various modules, documentation on python standard library can be referred. While
developing any web application, implementing web services, performing string operations
and other usages like interface protocol, the standard library documentation helps.

4. Compatible with Major Platforms and Systems:

Python is mainly compatible with major platforms and systems because of which it
is used mainly for developing applications. With help of python interpreters, python code
can be run on specific platforms and tools as it supports many operating systems. As
python is an interpreted high-level programming language and it allows you to run the code
on multiple platforms. The new and modified code can be executed without recompiling and
its impact can be monitored or checked. It means it’s not required to recompile the code
after every change. This feature helps in saving the development time of the developers.

5. Access of Database:

Uses of Python also helps in accessing the database easily. Python helps in
customizing the interfaces of different databases like MySQL, Oracle, Microsoft SQL
Server, PostgreSQL, and other databases. It has an object database like Durus and ZODB.
It is used for standard database API and freely available for download.

6. Code Readability:

Python code is easy to read and maintained. It is easily reusable as well wherever it
is required. Python’s having simple syntax, which allows the different concepts to develop
without writing any additional code. The code should be of good quality and easy to
maintain the source code and simplify the maintenance, which is required to develop the
software application. It also emphasizes code readability, which is the great feature,
unlike other programming languages. It helps in building custom applications and clean code
helps in maintaining and updating the software applications without putting extra effort on
the same code.

7. Simplify Complex Software Development:

Applications of Python is used to simplifying the complex software development


process as it is a general-purpose programming language. It is used for developing the
complex application like scientific and numeric application, and for both desktop and web
applications. Python has features like analyzing data and visualization, which helps in
creating custom solutions without putting extra effort and time. It helps you to visualize
and present data in an effective way.

8. Many Open Source Frameworks and Tools:

Python is open source and easily available. This also helps in costing the software
development significantly. There are many open source applications of python frameworks,
libraries, and development tools for developing the application without putting extra cost.
Python frameworks simplify and make the process faster for web application development
and the frameworks are Django, Flask, pyramid etc. Python GUI frameworks are available
for developing the GUI based application.
9. Adopt Test Driven Development:

Python makes coding easier as well as testing with help of adopting Test Driven
Development approach. The test cases can be easily written before any code development.
Whenever the code development started, the written test cases can start testing the
code simultaneously and provides the result. These can also be used for checking or
testing the pre-requirements based on the source code.

10. Other applications for which python is used:

There are other applications for which python is used that are Robotics, web
scraping, scripting, artificial intelligence, data analysis, machine learning, face detection,
color detection, 3D CAD applications, console-based applications, audio-based applications,
video-based applications, enterprise applications, and applications for Images etc. These
are some major applications used.

Conclusion – Uses of Python

In this Uses of Python article, we have seen that python is one of the major
languages are used for the development of both desktop and web applications. Python has
features that take care of common programming tasks. Python is simple to learn and easy
to use. Sometimes, python marks as slower than other widely used programming languages
like Java. Python applications can speed up by simply maintaining the code and using custom
runtime

Python does support the modules and packages, which encourages program
modularity and code reuse. Python provides an increase in productivity, which makes the
first choice of developers. It has a great learning curve as it supports functional and
procedural programming language. It is open source and can be freely distributed. The
programming language mainly selected based on the requirement and compatibility with
platforms and database.
Python Identifiers
Python Identifiers are user-defined names to represent a variable, function, class,
module or any other object. If you assign some name to a programmable entity in Python,
then it is nothing but technically called an identifier.

Python language lays down a set of rules for programmers to create meaningful
identifiers.

Guidelines for Creating Identifiers in Python:

1. To form an identifier, use a sequence of letters either in lowercase (a to


z) or uppercase (A to Z). However, you can also mix up digits (0 to 9) or an
underscore (_) while writing an identifier.
For example – Names like shapeClass, shape_1, and upload_shape_to_db
are all valid identifiers.

2. You can’t use digits to begin an identifier name. It’ll lead to the syntax
error.
For example – The name, 0Shape is incorrect, but shape1 is a valid
identifier.

3. Also, the Keywords are reserved, so you should not use them as
identifiers. Example:

>>> for=1

SyntaxError: invalid syntax

>>> True=1

SyntaxError: can't assign to keyword

4. Python Identifiers can also not have special characters [‘.’, ‘!’, ‘@’, ‘#’, ‘$’,
‘%’] in their formation. These symbols are forbidden. Example:
>>> @index=0
SyntaxError: invalid syntax
>>> isPython?=True
SyntaxError: invalid syntax

5. Python doc says that you can have an identifier with unlimited length. But
it is just the half-truth.

Using a large name (more than 79 chars) would lead to the violation of a
rule set by the PEP-8 standard. It says.

Testing If an Identifier Is Valid:

You can test whether a Python identifier is valid or not by using the
keyword.iskeyword() function. It returns “True” if the keyword is correct or “False”
otherwise. Example:

>>> import keyword


>>> import keyword
>>> keyword.iskeyword("techbeamers")
>>> keyword.iskeyword("techbeamers")
False
False
>>> keyword.iskeyword("try")
>>> keyword.iskeyword("try")
True
True
>>>

>>>

Another useful method to check if an identifier is valid or not is by calling the


str.isidentifier() function. But it is only available in Python 3.0 and onwards.
>>> 'techbeamers'.isidentifier()

True

>>> '1techbeamers'.isidentifier()

False

>>> 'techbeamers.com'.isidentifier()

False

>>> 'techbemaers_com'.isidentifier()

True

Best Practices for Identifier Naming:

 Better have class names starting with a capital letter. All other identifiers should
begin with a lowercase letter.
 Declare private identifiers by using the (‘_’) underscore as their first letter.
 Don’t use ‘_’ as the leading and trailing character in an identifier. As Python built-in
types already use this notation.
 Avoid using names with only one character. Instead, make meaningful names.

For example – While i = 1 is valid, but writing iter = 1 or index = 1 would make more
sense.

 You can use underscore to combine multiple words to form a sensible name.

For example – count_no_of_letters.

Python Data Types:


Python has five standard Data Types:

 Numbers
 String
 List
 Tuple
 Dictionary
Python sets the variable type based on the value that is assigned to it. Unlike more
riggers languages, Python will change the variable type if the variable value is set to
another value.

For example:

var = 123 # This will create a number integer assignment

var = 'john' # the `var` variable is now a string type.

Numbers

Python numbers variables are created by the standard Python method:

var = 382

Most of the time using the standard Python number type is fine. Python will
automatically convert a number from one type to another if it needs. But, under certain
circumstances that a specific number type is needed (ie. complex, hexidecimal), the format
can be forced into a format by using additional syntax in the table below:

Type Format Description

int a = 10 Signed Integer

long a = 345L (L) Long integers, they can also be represented in octal and hexadecimal

float a = 45.67 (.) Floating point real values

complex a = 3.14J (J) Contains integer in the range 0 to 255.

Most of the time Python will do variable conversion automatically. You can also use
Python conversion functions (int(), long(), float(), complex()) to convert data from one type
to another. In addition, the type function returns information about how your data is
stored within a variable.
message = "Good morning"

num = 85

pi = 3.14159

print(type(message)) # This will return a string

print(type(n)) # This will return an integer

print(type(pi)) # This will return a float

String

Create string variables by enclosing characters in quotes. Python uses single quotes
' double quotes " and triple quotes """ to denote literal strings. Only the triple quoted
strings """ also will automatically continue across the end of line statement.

firstName = 'john'

lastName = "smith"

message = """This is a string that will span across multiple lines. Using newline characters

and no spaces for the next lines. The end of lines within this string also count as a newline
when printed"""

Strings can be accessed as a whole string, or a substring of the complete variable using
brackets ‘[]’. Here are a couple examples:

var1 = 'Hello World!'

var2 = 'RhinoPython'

print var1[0] # this will print the first character in the string an `H`

print var2[1:5] # this will print the substring 'hinoP`


Python can use a special syntax to format multiple strings and numbers. The string
formatter is quickly covered here because it is seen often and it is important to recognize
the syntax:

print "The item {} is repeated {} times".format(element,count))

The {} are placeholders that are substituted by the variables element and count in the
final string. This compact syntax is meant to keep the code more readable and compact.

Python is currently transitioning to the format syntax above, but python can use an older
syntax, which is being phased out, but is still seen in some example code:

print "The item %i is repeated %i times"% (element,count)

List

Lists are a very useful variable type in Python. A list can contain a series of values.
List variables are declared by using brackets [ ] following the variable name.

A=[ ] # This is a blank list variable

B = [1, 23, 45, 67] # this list creates an initial list of 4 numbers.

C = [2, 4, 'john'] # lists can contain different variable types.

All lists in Python are zero-based indexed. When referencing a member or the length of a
list the number of list elements is always the number shown plus one:

mylist = ['Rhino', 'Grasshopper', 'Flamingo', 'Bongo']

B = len(mylist) # This will return the length of the list which is 3. The index is 0, 1, 2, 3.

print mylist[1] # This will return the value at index 1, which is 'Grasshopper'

print mylist[0:2] # This will return the first 3 elements in the list.
You can assign data to a specific element of the list using an index into the list. The list
index starts at zero. Data can be assigned to the elements of an array as follows:

mylist = [0, 1, 2, 3]

mylist[0] = 'Rhino'

mylist[1] = 'Grasshopper'

mylist[2] = 'Flamingo'

mylist[3] = 'Bongo'

print mylist[1]

Lists aren’t limited to a single dimension. Although most people can’t comprehend more
than three or four dimensions. You can declare multiple dimensions by separating an with
commas. In the following example, the MyTable variable is a two-dimensional array:

MyTable = [[], []]

In a two-dimensional array, the first number is always the number of rows; the second
number is the number of columns.

Tuple

Tuples are a group of values like a list and are manipulated in similar ways. But,
tuples are fixed in size once they are assigned. In Python the fixed size is considered
immutable as compared to a list that is dynamic and mutable. Tuples are defined by
parenthesis ().

myGroup = ('Rhino', 'Grasshopper', 'Flamingo', 'Bongo')

Here are some advantages of tuples over lists:

 Elements to a tuple. Tuples have no append or extend method.


 Elements cannot be removed from a tuple.
 You can find elements in a tuple, since this doesn’t change the tuple.
 You can also use the in operator to check if an element exists in the tuple.
 Tuples are faster than lists. If you’re defining a constant set of values and all
you’re ever going to do with it is iterate through it, use a tuple instead of a list.
 It makes your code safer if you “write-protect” data that does not need to be
changed.

It seems tuples are very restrictive, so why are they useful? There are many data
structures in Rhino that require a fixed set of values. For instance a Rhino point is a list of
3 numbers [34.5, 45.7, 0]. If this is set as tuple, then you can be assured the original 3
number structure stays as a point (34.5, 45.7, 0). There are other data structures such as
lines, vectors, domains and other data in Rhino that also require a certain set of values
that do not change. Tuples are great for this.

Dictionary

Dictionaries in Python are lists of Key: Value pairs. This is a very powerful data type
to hold a lot of related information that can be associated through keys. The main
operation of a dictionary is to extract a value based on the key name. Unlike lists, where
index numbers are used, dictionaries allow the use of a key to access its members.
Dictionaries can also be used to sort, iterate and compare data.

Dictionaries are created by using braces ({}) with pairs separated by a comma (,)
and the key values associated with a colon (:). In Dictionaries the Key must be unique. Here
is a quick example on how dictionaries might be used:

room_num = {'john': 425, 'tom': 212}

room_num['john'] = 645 # set the value associated with the 'john' key to 645

print (room_num['tom']) # print the value of the 'tom' key.

room_num['isaac'] = 345 # Add a new key 'isaac' with the associated value

print (room_num.keys()) # print out a list of keys in the dictionary

print ('isaac' in room_num) # test to see if 'issac' is in the dictionary. This returns true.

Dictionaries can be more complex to understand, but they are great to store data that is
easy to access.
Python Variables
Creating Variables:

Unlike other programming languages, Python has no command for declaring a


variable.

A variable is created the moment you first assign a value to it:

x=5

y = "John"

print(x)

print(y)

Variables do not need to be declared with any particular type and can even change
type after they have been set:

x=4 # x is of type int

x = "Sally" # x is now of type str

print(x)

Variable Names:

A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)

Remember that variables are case-sensitive


Output Variables

The Python print statement is often used to output variables.

To combine both text and a variable, Python uses the + character:

x = "awesome"

print("Python is " + x)

You can also use the + character to add a variable to another variable:

x = "Python is "

y = "awesome"

z= x+y

print(z)

For numbers, the + character works as a mathematical operator:

x=5

y = 10

print(x + y)

If you try to combine a string and a number, Python will give you an error:

x=5

y = "John"

print(x + y)
Python Keywords
Python has a set of keywords that are reserved words that cannot be used as variable
names, function names, or any other identifiers:

METHOD DESCRIPTION
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed no
matter if there is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
with Used to simplify exception handling
yield To end a function, returns a generator
nonlocal To declare a non-local variable
while To create a while loop
Python Operators
Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical
operations:

OPERATOR NAME EXAMPLE


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y

Python Assignment Operators

Assignment operators are used to assign values to variables:

Operator Example Same As


= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Python Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Python Logical Operators

Logical operators are used to combine conditional statements:

Operator Description Example


and Returns True if both statements are x < 5 and x < 10
true
or Returns True if one of the statements is x < 5 or x < 4
true
not Reverse the result, returns False if the not(x < 5 and x < 10)
result is true

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Operator Description Example
is Returns true if both variables are the x is y
same object
is not Returns true if both variables are not x is not y
the same object

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Operator Description Example


in Returns True if a sequence with the x in y
specified value is present in the object
not in Returns True if a sequence with the x not in y
specified value is not present in the
object

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Name Description


& AND Sets each bit to 1 if both bits
are 1
| OR Sets each bit to 1 if one of two
bits is 1
^ XOR Sets each bit to 1 if only one of
two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in
from the right and let the
leftmost bits fall off
>> Signed right shift Shift right by pushing copies of
the leftmost bit in from the
left, and let the rightmost bits
fall off
Python Comments
When the program is getting bigger and more complicated, it is getting difficult to
read and maintain. For these reasons, it is a good practice to put some documentations or
notes into your code. These notes are called comments.

The code only can tell you how it does but cannot tell you why it does so. However,
your comment can do that. You use comments to explain the formulas, complex algorithms
and sophisticated business logic.

Python comment begins with a hash or pound (#) sign and continues to the end of
the line. It is important to note that Python interpreter ignores comments when it
interprets the code.

Python provides three kinds of comments including block comment, inline comment
and documentation string.

Python block comments

You use a block comment to explain the code that follows it. A block comment is
indented at the same level as the code block. To write a block comment, you start with a
single hash (# ) sign followed by a single space and comment.

The following code illustrates how to make a block:

# increase price to 5%

price = price * 1.05

Python inline comments

If a comment is placed on the same line as a statement, it is called an inline


comment. Similar to the block comment, an inline comment begins with a single hash (# )
sign and followed by a space and comment.

It is recommended that an inline comment should separate from the statement at


least two spaces. The following example demonstrates an inline comment.

salary = salary * 1.02 # increase salary 2% for the employee


Python documentation string or docstrings

A documentation string is a literal string that you put as the first statement in a
function, module, class, or method definition. Different from a regular comment,
documentation string can be accessed at run-time using obj.__doc__ attribute where obj
is the name of function, module or class, etc.

Documentation string is also used to generate documentation automatically.


Documentation string is also known as docstrings.

Python provides two kinds of docstrings: one-line docstrings and multi-line


docstrings.

One-line docstrings

One-line docstring fits in one line begins with triple quotes and ends with triple
quotes. There should not have a blank line either before or after the one-line docstring.

The following example illustrates one-line docstring in quicksort() function:

def quicksort():

""" sort the list using quicksort algorithm """

...

Multi-line docstrings

As its name implies, multi-line docstring can span multiple lines. Just like one-line
docstring, the first line of multi-line docstring is a summary, followed by a blank line and
of course more descriptions underneath.

The following example shows you how to use multi-line docstrings:

def increase_salary(sal,rating,percentage):

""" increase salary base on rating and percentage

rating 1 - 2 no increase

"""
Python multiline comments:

Python does not support multiline comments like C/C++ or Java. However there is
nothing to stop you to use multi-line docstrings as multiline comments. This is also
mentioned by Guido van Rossum, the creator of Python.

It is important to keep you comment clear, concise and explanatory. The ultimate
goal is to save time and energy for maintenance developers who will work on the code.

Python Functions
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function:

In Python a function is defined using the def keyword:

def my_function():

print ("Hello from a function")

Calling a Function:

To call a function, use the function name followed by parenthesis:

def my_function():

print("Hello from a function")

my_function()
Parameters

Information can be passed to functions as parameter.

Parameters are specified after the function name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma.

The following example has a function with one parameter (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full name:

def my_function(fname):

print(fname + " Refsnes")

my_function("Emil")

my_function("Tobias")

my_function("Linus")

Default Parameter Value

The following example shows how to use a default parameter value.

If we call the function without parameter, it uses the default value:

def my_function(country = "Norway"):

print("I am from " + country)

my_function("Sweden")

my_function("India")

my_function()

my_function("Brazil")

Return Values

To let a function return a value, use the return statement:


def my_function(x):

return 5 * x

print(my_function(3))

print(my_function(5))

print(my_function(9))

Recursion

Python also accepts function recursion, which means a defined function can call itself.

Recursion is a common mathematical and programming concept. It means that a function


calls itself. This has the benefit of meaning that you can loop through data to reach a
result.

The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of memory or
processor power. However, when written correctly recursion can be a very efficient and
mathematically-elegant approach to programming.

In this example, tri_recursion() is a function that we have defined to call itself


("recurse"). We use the k variable as the data, which decrements (-1) every time we
recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).

To a new developer it can take some time to work out how exactly this works, best way to
find out is by testing and modifying it.

Recursion Example:

def tri_recursion(k):

if(k>0):

result = k+tri_recursion(k-1)

print(result)

else:
result = 0

return result

print("\n\nRecursion Example Results")

tri_recursion(6)

Sample Hello World Program

Hello.py

def main ():

print (“Hello World”)

main()

Potrebbero piacerti anche