Sunday, August 19, 2018

Top 50 Python proggraming examples with logic

Python Programming Examples

The best way to learn any programming language is by practicing examples on your own.
You are advised to take references of these examples and try them on your own.
All programs in this page are tested and should work on almost all Python3 compilers.
Feel free to use the source code on your system.

Popular examples:

python module

What is a Module?

Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.

Create a Module

To create a module just save the code you want in a file with the file extension .py:

Example

Save this code in a file named mymodule.py
def greeting(name):
  print("Hello, " + name)

Use a Module

Now we can use the module we just created, by using the import statement:

Example

Import the module named mymodule, and call the greeting function:
import mymodule

mymodule.greeting("Jonathan")
Run example »
Note: When using a function from a module, use the syntax: module_name.function_name.

Variables in Module

The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):

Example

Save this code in the file mymodule.py
person1 = {
  "name""John",
  "age"36,
  "country""Norway"
}

Example

Import the module named mymodule, and access the person1 dictionary:
import mymodule

a = mymodule.person1["age"]
print(a)
Run example »


Naming a Module

You can name the module file whatever you like, but it must have the file extension .py

Re-naming a Module

You can create an alias when you import a module, by using the as keyword:

Example

Create an alias for mymodule called mx:
import mymodule as mx

a = mx.person1["age"]
print(a)
Run example »

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

Example

Import and use the platform module:
import platform

x = platform.system()
print(x)
Run example »

Using the dir() Function

There is a built-in function to list all the function names (or variable names) in a module. The dir() function:

Example

List all the defined names belonging to the platform module:
import platform

x = dir(platform)
print(x)
Run example »
Note: The dir() function can be used on all modules, also the ones you create yourself.

Import From Module

You can choose to import only parts from a module, by using the from keyword.

Example

The module named mymodule has one function and one dictionary:
def greeting(name):
  print("Hello, " + name)

person1 = {
  "name""John",
  "age"36,
  "country""Norway"
}

Example

Import only the person1 dictionary from the module:
from mymodule import person1

print (person1["age"])
Run example »
Note: When importing using the from keyword, do not use the module name when referring to elements in the module. Example: person1["age"]not mymodule.person1["age"]

Python classes & object


Python Classes/Objects

Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.
A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the keyword class:

Example

Create a class named MyClass, with a property named x:
class MyClass:
  x = 5
Run example »

Create Object

Now we can use the class named myClass to create objects:

Example

Create an object named p1, and print the value of x:
p1 = MyClass()
print(p1.x)
Run example »

The __init__() Function

The examples above are classes and objects in their simplest form, and are not really useful in real life applications.
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being initiated.
Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created:

Example

Create a class named Person, use the __init__() function to assign values for name and age:
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John"36)

print(p1.name)
print(p1.age)
Run example »
Note: The __init__() function is called automatically every time the class is being used to create a new object.

Python function


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:

Example

def my_function():
  print("Hello from a function")

Calling a Function

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

Example

def my_function():
  print("Hello from a function")

my_function()
Run example »

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:

Example

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:

Example

def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Run example »

Return Values

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

Example

def my_function(x):
  return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Run example »

Python For loop


Python For Loops

for loop is used for iterating over a sequence (that is either a list, a tuple or a string).
This is less like the for keyword in other programming language, and works more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Example

Print each fruit in a fruit list:
fruits = ["apple""banana""cherry"]
for in fruits:
  print(x)
Run example »
The for loop does not require an indexing variable to set beforehand, as the for command itself allows for this.

The break Statement

With the break statement we can stop the loop before it has looped through all the items:

Example

Exit the loop when x is "banana":
fruits = ["apple""banana""cherry"]
for x in fruits:
  if x == "banana":
    break
  print(x)
Run example »

The continue Statement

With the continue statement we can stop the current iteration of the loop, and continue with the next:

Example

Do not print banana:
fruits = ["apple""banana""cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)
Run example »

The range() Function

To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

Example

Using the range() function:
for x in range(6):
  print(x)
Run example »
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):

Example

Using the start parameter:
for x in range(26):
  print(x)
Run example »
The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):

Example

Increment the sequence with 3 (default is 1):
for x in range(2303):
  print(x)
Run example »

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 kvariable 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.

Example

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)

Top 50 Python proggraming examples with logic

Python Programming Examples The best way to learn any programming language is by practicing examples on your own. You are advised ...