Python for Android Android’s Native Dialogs (SL4A)

Python for Android: Android’s Native Dialogs (SL4A)

Android has a range of built-in dialogs that allow apps to interact with users. They can be used to display things like spinners and progress bars, and can be used to prompt the user for some kind of input, like a date or string.

All of the methods for creating dialogs live in SL4A’s UI Facade, along with most of the methods you’ll ever need for managing them. The UI Facade also hosts methods for creating webviews and for working with the experimental FullScreenUI stuff.

SL4A and Native Dialogs

The normal flow when using dialogs is to first create the appropriate dialog object, then set any additional features you want it to have, then render it to the user. It takes a few calls, but it’s easy to do. Once it’s displayed, there are methods for getting results from a dialog and for dismissing it. You can also update progress dialogs while they’re being rendered.

Creating Android Dialogs

You create a new dialog using one of the dialogCreate* calls. The standard dialogs are AlertInputPasswordDatePickerSeekBarSpinnerProgress and HorizontalProgress.

For example, to create and render a date picker dialog, you’d do something like…

from android import Android
droid = Android()
droid.dialogCreateDatePicker()
droid.dialogShow()

Note that all interaction with the dialog is done by calling methods of droid. This is just a consequence of the way SL4A interfaces with the Android API; the droid object is a ‘god object’, so everything is a method of droid. For simplicity’s sake, there is only ever one instance of a dialog, so any dialogCreate* call will cause any existing dialog to be destroyed.

Customising Dialogs

You set any additional features of a dialog with the dialogSet* calls. What you can customise will depend on what kind of dialog you’ve created.

For example, you could set the positive button text on an alert dialog using dialogSetPositiveButtonText, and there’s matching methods for setting neutral and negative button texts. You can use any combination of the three on an alert dialog.

Displaying Dialogs

You display a dialog using dialogShow, and you can then dismiss the dialog with dialogDismiss.

Getting the Input

You can normally get any results using dialogGetResponse, which blocks until the user responds to the dialog. However, for certain types of dialogs, you may instead have to use the eventPoll method of the Events Facade to wait for a dialog event. Some dialogs, such as menus, are persistent features of an application, potentially generating multiple events over time, so they must be managed through the Events Facade.

If you create single-choice dialogs (radio buttons) or multi-choice dialogs (checklists), you must pass in a list of choices for the user to select from. You can find out which choices were selected using the dialogGetSelectedItems method. This method returns a list of integers, which map to the indices of the selected items in the list of choices you passed in. Obviously, for a single-choice dialog, there will only be one.

Say That Again in Python…

Let’s imagine we need to ask the user if they want to install a bunch of packages, then, assuming they do, we want to create a progress bar that shows how that installation process is doing. Let’s also say say we have 5 packages to install.

import sys
 
# Create the droid object
from android import Android
droid = Android()
 
# Create an alert, setting a title and message
droid.dialogCreateAlert(
    'Install Packages?',
    'You may want to use WiFi for this.'
)
 
# Set up a couple of buttons
droid.dialogSetPositiveButtonText('Yes')
droid.dialogSetNegativeButtonText('No')
 
# Now render the dialog to the user
droid.dialogShow()
 
# Get the result and dismiss the dialog
response = droid.dialogGetResponse().result
droid.dialogDismiss()
 
# Check to see if the user has pressed a button, as users can dismiss
# dialogs, and check if it was the positive one, otherwise we're done
if not 'which' in response or response['which'] != 'positive': sys.exit()
 
# Now the checks are done, create and render the new progress bar dialog,
# setting a title, message and a maximum progress of 5
droid.dialogCreateHorizontalProgress(
    'Installing Packages...',
    'This should just take a moment.',
    5
)
 
# Render the dialog
droid.dialogShow()
 
# Now do the installation, updating the progress bar along the way...
 
# Import a couple of parsimonyms
import some_package_installing_function as install
import some_list_of_packages as packages
 
# Install each of the packages, incrementing the progress bar on each
progress = 0
for package in packages:
    install(package)
    progress += 1
    droid.dialogSetCurrentProgress(progress)
 
# Tidy up and exit
droid.dialogDismiss()

The screenshots to the right show the confirmation dialog and the progress dialog. The actual look and feel will be slightly different from device to device of course.

The screenshots to the right show the confirmation dialog and the progress dialog. The actual look and feel will be slightly different from device to device of course. Say That Again in Python 1

Note that, if you only want to ask the user for some text input, like Python’s `input` function would, or a password, you can use the `dialogGetInput` and `dialogGetPassword` methods, which are just convenient wrappers, allowing you to get these inputs in a single call.

Event Based Dialogs

The above example pretty much covered all the basics of using dialogs with SL4A, and the API Reference covers all the finer details. The only real exception to the normal way of doing dialogs (create-customise-render-read-dismiss) is when using menu items. As mentioned before, menu items are added to the native menus of applications; generally they’re always available to the user and may be clicked at any point, any number of times, so they are managed a bit differently.

For example, you can use addOptionsMenuItem to add an item to your application’s options menu. The method requires two arguments, a string that sets the text to display on the item, and a string that sets a name for the events that are produced whenever the item is clicked. You can optionally set the data that is passed with the events, and set an icon to be displayed on the menu item. Again, see the API docs for all the details.

If you’ve used the Events Facade before, this will already will make perfect sense. Either way, it’s not difficult to get started with. The following example will block, so it’d need another thread or something to be much use; this example just covers the SL4A API.

# addOptionsMenuItem takes two to four arguments:
# item_label, event_name, [event_data], [icon_name]
 
# The following calls add three items to the options menu...
droid.addOptionsMenuItem('Do A', 'a_event', 'Some event data.')
droid.addOptionsMenuItem('Do B', 'b_event', 'Some other data.')
droid.addOptionsMenuItem('Quit', 'kill', None, 'ic_menu_revert')
 
while True:
    # Block until an event happens, then grab the result
    res = droid.eventWait().result
    
    # If it's a kill event, exit the event loop
    if res['name'] == 'kill':
        break
 
    # Otherwise, print the event data
    print(res['data'])

శ్రీ సాయినాథ మహిమా స్తోత్రం

Hashing Strings with Python

Hashing Strings with Python

A hash function is a function that takes input of a variable length sequence of bytes and converts it to a fixed length sequence. It is a one way function. This means if f is the hashing function, calculating f(x) is pretty fast and simple, but trying to obtain x again will take years. The value returned by a hash function is often called a hash, message digest, hash value, or checksum. Most of the time a hash function will produce unique output for a given input. However depending on the algorithm, there is a possibility to find a collision due to the mathematical theory behind these functions.
Hashing Strings with PythonNow suppose you want to hash the string “Hello Word” with the SHA1 Function, the result is 0a4d55a8d778e5022fab701977c5d840bbc486d0.
Hashing Strings with Python 1

Hash functions are used inside some cryptographic algorithms, in digital signatures, message authentication codes, manipulation detection, fingerprints, checksums (message integrity check), hash tables, password storage and much more. As a Python programmer you may need these functions to check for duplicate data or files, to check data integrity when you transmit information over a network, to securely store passwords in databases, or maybe some work related to cryptography.

I want to make clear that hash functions are not a cryptographic protocol, they do not encrypt or decrypt information, but they are a fundamental part of many cryptographic protocols and tools.

Some of the most used hash functions are:

  • MD5: Message digest algorithm producing a 128 bit hash value. This is widely used to check data integrity. It is not suitable for use in other fields due to the security vulnerabilities of MD5.
  • SHA: Group of algorithms designed by the U.S’s NSA that are part of the U.S Federal Information processing standard. These algorithms are used widely in several cryptographic applications. The message length ranges from 160 bits to 512 bits.

The hashlib module, included in The Python Standard library is a module containing an interface to the most popular hashing algorithms. hashlib implements some of the algorithms, however if you have OpenSSL installed, hashlib is able to use this algorithms as well.

This code is made to work in Python 3.2 and above. If you want to run this examples in Python 2.x, just remove the algorithms_available and algorithms_guaranteed calls.

First, import the hashlib module:

import hashlib

Now we use algorithms_available or algorithms_guaranteed to list the algorithms available.

print(hashlib.algorithms_available)
print(hashlib.algorithms_guaranteed)

The algorithms_available method lists all the algorithms available in the system, including the ones available trough OpenSSl. In this case you may see duplicate names in the list. algorithms_guaranteed only lists the algorithms present in the module. md5, sha1, sha224, sha256, sha384, sha512 are always present.

MD5

import hashlib
hash_object = hashlib.md5(b'Hello World')
print(hash_object.hexdigest())

The code above takes the “Hello World” string and prints the HEX digest of that string. hexdigest returns a HEX string representing the hash, in case you need the sequence of bytes you should use digest instead.

It is important to note the “b” preceding the string literal, this converts the string to bytes, because the hashing function only takes a sequence of bytes as a parameter. In previous versions of the library, it used to take a string literal. So, if you need to take some input from the console, and hash this input, do not forget to encode the string in a sequence of bytes:

import hashlib
mystring = input('Enter String to hash: ')
# Assumes the default UTF-8
hash_object = hashlib.md5(mystring.encode())
print(hash_object.hexdigest())

SHA1

import hashlib
hash_object = hashlib.sha1(b'Hello World')
hex_dig = hash_object.hexdigest()
print(hex_dig)

SHA224

import hashlib
hash_object = hashlib.sha224(b'Hello World')
hex_dig = hash_object.hexdigest()
print(hex_dig)

SHA256

import hashlib
hash_object = hashlib.sha256(b'Hello World')
hex_dig = hash_object.hexdigest()
print(hex_dig)

SHA384

import hashlib
hash_object = hashlib.sha384(b'Hello World')
hex_dig = hash_object.hexdigest()
print(hex_dig)

SHA512

import hashlib
hash_object = hashlib.sha512(b'Hello World')
hex_dig = hash_object.hexdigest()
print(hex_dig)

Using OpenSSL Algorithms

Now suppose you need an algorithm provided by OpenSSL. Using algorithms_available, we can find the name of the algorithm you want to use. In this case, “DSA” is available on my computer. You can then use the new and update methods:

import hashlib
hash_object = hashlib.new('DSA')
hash_object.update(b'Hello World')
print(hash_object.hexdigest())

Practical example: hashing passwords

In the following example we are hashing a password in order to store it in a database. In this example we are using a salt. A salt is a random sequence added to the password string before using the hash function. The salt is used in order to prevent dictionary attacks and rainbow tables attacks. However, if you are making real world applications and working with users’ passwords, make sure to be updated about the latest vulnerabilities in this field. I you want to find out more about secure passwords please refer to this article

Python 3.x

import uuid
import hashlib
 
def hash_password(password):
    # uuid is used to generate a random number
    salt = uuid.uuid4().hex
    return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt
    
def check_password(hashed_password, user_password):
    password, salt = hashed_password.split(':')
    return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()
 
new_pass = input('Please enter a password: ')
hashed_password = hash_password(new_pass)
print('The string to store in the db is: ' + hashed_password)
old_pass = input('Now please enter the password again to check: ')
if check_password(hashed_password, old_pass):
    print('You entered the right password')
else:
    print('I am sorry but the password does not match')

Python 2.x

import uuid
import hashlib
 
def hash_password(password):
    # uuid is used to generate a random number
    salt = uuid.uuid4().hex
    return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt
    
def check_password(hashed_password, user_password):
    password, salt = hashed_password.split(':')
    return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()
 
new_pass = raw_input('Please enter a password: ')
hashed_password = hash_password(new_pass)
print('The string to store in the db is: ' + hashed_password)
old_pass = raw_input('Now please enter the password again to check: ')
if check_password(hashed_password, old_pass):
    print('You entered the right password')
else:
    print('I am sorry but the password does not match')

Also Read: Theory of Computation Handwritten Notes

Python Modules Urllib2 User Agent

Python Modules Urllib2 User Agent

Overview

This post will show how to add headers to a HTTP request. By default urllib2 identifies itself as Python-urllib/2.7 : GET / HTTP/1.1″ 200 151 “-” “Python-urllib/2.7” That can sometimes be confusing for certain sites. With the user_agent header in Python, it’s possible to alter that and specify any identity you like. The example below, use the Mozilla 5.10 as a User Agent, and that is also what will show up in the web server log file.

Also Read: Python Program to Calculate Age in Days from Date of Birth

import urllib2

req = urllib2.Request('http://192.168.1.2/')

req.add_header('User-agent', 'Mozilla 5.10')

res = urllib2.urlopen(req)

html = res.read()

This is what will show up in the log file.

"GET / HTTP/1.1" 200 151 "-" "Mozilla 5.10"
Command Line speedtest.net via tespeed

Command Line speedtest.net via tespeed

Overview

While looking around for a command line tool to check my network speed,
I stumbledupon a post on lowendtalk.com.

What is it?

It’s a command line interface to the speedtest.net servers and can be found here:
https://github.com/Janhouse/tespeed

What is Speedtest?

Speedtest.net is a connection analysis website where users can test their internet speed against hundreds of geographically dispersed servers around the world.

At the end of each test,users are presented with their download (the speed of data from the server to their computer) and upload (the speed of sending data from the user’s computer to the server) bandwidth speeds.

Requirements

This script requires lxml and argparse, so make sure you install that first.

See this link for a howto.

In most cases it’s enough to run this command from a terminal: pypm install lxml

How does the script work?

See the this url for how to use the program

Running the script

After downloading the requirements I decided to give this program a chance.

Copy and paste the code from here.

Run the script

Open up your editor, copy and paste the above code and save the file as speed.py

To execute the program, type python and the file name in the shell.
$python speed.py

How to Best Use Try-Except in Python

How to Best Use Try-Except in Python

Exception handling allows us to enforce constraints on variables to implement our business logic in the computer program and it also enables us to write a robust program that can handle different types of errors occurred during execution. In python, we use try-except blocks to implement exception handling. In this article, we will look at some ways to write an efficient python program by looking at illustrations to best use try-except in python. So, let’s dive into it.

Read Also: Java Program to Compute 2(a2+b2) where Value of a and b are Given

Raising Exceptions Manually using raise keyword

A python program throws inbuilt exceptions automatically when an error occurs but we can also raise inbuilt exceptions manually using raise keyword. By throwing inbuilt exceptions using the raise keyword, we can use the inbuilt exceptions to enforce constraints on the variables to make sure that program is correct logically. Here the point to keep in mind is that a program may not throw any error but it may give an unrealistic value as output when proper constraints are not applied to the variables. Hence we may use raise keyword to throw exceptions in the python try-except block to enforce the constraints.

For example, suppose we want to calculate the year of birth of a person from their age, we can do it as follows:

age= 10
print("Age is:")
print(age)
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)

Output:

Age is:
10
Year of Birth is:
2011

We can see that the program has given correct output for a person of age 10. Now we will try to give a negative age as input to the program and see what happens.

age= -10
print("Age is:")
print(age)
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)

Output:

Age is:
-10
Year of Birth is:
2031

In the above output, we can see that the program has executed successfully and has given an output which is logically impossible because no person can have his year of birth in future. So, we will use try-except error handling code to raise an error manually when age is negative and then we will show the proper output as follows.

Raising Exceptions Manually using raise keyword

try:
    age= -10
    print("Age is:")
    print(age)
    if age<0:
        raise ValueError
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except ValueError:
    print("Input Correct age.")

Output:

Age is:
-10
Input Correct age.

Here, we can see that when the input age is a negative value, the program raises ValueError manually and the error is handled by the code in except block. We can also define custom exceptions on our own to implement the constraints as discussed in the following section.

Using custom exceptions

To enforce the constraints we can declare our own exceptions by defining classes which should be sub classes of any inbuilt exception. In this way we can create an exception with a name more meaningful to our constraints and then we can enforce the constraints on the variables by checking and raising custom exceptions.

In the following example, we define NegativeAgeError exception class by inheriting the python Exception class . Whenever the value of age in input is negative, the custom error named as NegativeAgeError is raised and then it is handled by the code in the except block. Whenever positive value of age is given as input, the program will work normally.

Using custom exceptions 

class NegativeAgeError(Exception):
    pass
try:
    age= -10
    print("Age is:")
    print(age)
    if age<0:
        raise NegativeAgeError
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except NegativeAgeError:
    print("Input Correct age.")

Output:

Age is:
-10
Input Correct age

Differentiating between different types of errors using try-except in python

There may be many situations where we want to handle different runtime and custom exceptions differently. We may want to find out which exception is occurring during execution of a program or we may want to execute different tasks when different exceptions occur. In these cases we can catch each exception separately by giving the exception name as an argument to except block as given in the following example and then we can execute the statements given in the  except block for that specific exception.

Differentiating between different types of errors using try-except in python 3

try:
    age= -10
    print("Age is:")
    print(age)
    assert age>0
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except AssertionError:
    print("Input Correct age.")
except ValueError:
    print("ValueError occured")
except NameError:
    print("NameError occurred")
except:
    print("Some other exception occurred")

In the above program, we have explicitly differentiated AssertionErrorValueError and NameError from other types of exceptions and we have handled them explicitly. One has to be kept in mind while differentiating exceptions is that the most general exception has to be written last in the except block and most specific exception has to be written first in the except block. Otherwise unreachable code will be generated and will cause error.

For example, following way of using try-except in python to differentiate exceptions is wrong.

Differentiating between different types of errors using try-except in python 4

try:
    age= -10
    print("Age is:")
    print(age)
    raise IOError
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except:
    print("Some other exception occurred")
except AssertionError:
    print("Input Correct age.")
except ValueError:
    print("ValueError Occured")
except NameError:
    print("NameError occurred")

Output:

Differentiating between different types of errors using try-except in python out put

File "/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py", line 3331, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-4-f6b48848354a>", line 1, in <module>
    runfile('/home/aditya1117/untitled0.py', wdir='/home/aditya1117')

  File "/usr/lib/python3/dist-packages/spyder_kernels/customize/spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "/usr/lib/python3/dist-packages/spyder_kernels/customize/spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/home/aditya1117/untitled0.py", line 8
    print(yearOfBirth)
    ^
SyntaxError: default 'except:' must be last

We can see that syntax error occurs in the program when we use more general except block before the specific exceptions.

Grouping Exceptions using try-except in python

While writing programs, there may be many situations where we want to handle two or more exceptions in the same way. We can group certain types of exceptions at one place in python and then they can be handled by the same error handling code by passing each exception of a group as an argument to the except block.

In the example below, we have grouped AssertionErrorValueError and NameError in a single except block and same code will be executed when any of the error occurs.

Grouping Exceptions using try-except in python

try:
    age= -10
    print("Age is:")
    print(age)
    raise ValueError
    yearOfBirth= 2021-age
    print("Year of Birth is:")
    print(yearOfBirth)
except (AssertionError,ValueError,NameError):
    print("AssertionError or ValueError or NameError has occurred.")
except:
    print("Some other exception occurred")

The finally block

In a program, there may be some statements to execute each time before the program terminates no matter what the situation is. In that case we can put the statements in Finally block. The Finally block executes each time whether or not any error/exception occurs in the try block. When an exception is thrown by the try block, the code in the except block executes first and then the code in the finally block is executed. Otherwise Finally block is executed after the try block when any error doesn’t occur.

For example, when we perform python write to file operation, the file always needs to be closed before termination of the program so that the data doesn’t get lost. We can write code to close the file in the Finally block in this case as follows.

The finally block

try:
    file_ptr=open("filename.txt","w")
    file_ptr.write("This is PythonForBeginners.com")
    
except (IOError):
    print("IOError has occurred.")
except:
    print("Some other exception occurred")
finally:
    file_ptr.close()

Conclusion

In this article, we have seen how we can best use try-except in Python by application of methods like custom exceptions, grouping the exceptions, and differentiating the exceptions from each other. Stay tuned for more informative articles.

Must Read:

GUJGASLTD Pivot Point Calculator

Introduction to Python Classes (Part 1 of 2)

Introduction to Python Classes (Part 1 of 2)

Classes are a way of grouping related bits of information together into a single unit (also known as an object), along with functions that can be called to manipulate that object (also known as methods). For example, if you want to track information about a person, you might want to record their name, address, and phone number, and be able to manipulate all of these as a single unit.

Python has a slightly idiosyncratic way of handling classes, so even if you’re familiar with object-oriented languages like C++ or Java, it’s still worth digging into Python classes since there are a few things that are different.

Before we start, it’s important to understand the difference between a class and an object. A class is simply a description of what things should look like, what variables will be grouped together, and what functions can be called to manipulate those variables. Using this description, Python can then create many instances of the class (or objects), which can then be manipulated independently. Think of a class as a cookie-cutter – it’s not a cookie itself, but it’s a description of what a cookie looks like, and can be used to create many individual cookies, each of which can be eaten separately. Yum!

Defining a Python Class

Let’s start off by defining a simple class:

class Foo:
    def __init__(self, val):
        self.val = val
    def printVal(self):
        print(self.val)

The class is called Foo and as usual, we use indentation to tell Python where the class definition starts and ends. In this example, the class definition consists of two function definitions (or methods), one called __init__ and the other printVal. There is also one member variable, not explicitly defined, but we’ll explain below how it gets created.

Defining a Python Class

The diagram shows what the class definition looks like – 2 methods and 1 member variable. Using this definition, we can then create many instances of the class.

You can see that both methods take a parameter called self. It doesn’t have to be called self but this is the Python convention and while you could call it this or me or something else, you will annoy other Python programmers who might look at your code in the future if you call it anything other than self. Because we can create many instances of a class, when a class method is called, it needs to know which instance it is working with, and that’s what Python will pass in via the self parameter.

__init__ is a special method that is called whenever Python creates a new instance of the class (i.e. uses the cookie cutter to create a new cookie). In our example, it accepts one parameter (other than the mandatory self), called val, and takes a copy of it in a member variable, also called val. Unlike other languages, where variables must be defined before they are used, Python creates variables on the fly, when they are first assigned, and class member variables are no different. To differentiate between the val variable that was passed in as a parameter and the val class member variable, we prefix the latter with self. So, in the following statement:

self.val = val

self.val refers to the val member variable belonging to the class instance the method is being called for, while val refers to the parameter that was passed into the method.

This is all a bit confusing, so let’s take a look at an example:

obj1 = Foo(1)

This creates an instance of our class (i.e. creates a new cookie using the cookie cutter). Python automatically calls the __init__ method for us, passing in the value we specified (1). So, we get one of these:

Defining a Python Class 1

Let’s create another one:

obj2 = Foo(2)

Exactly the same thing happens, except that 2 gets passed in to the __init__ method.

We now have two independent objects, with different values for the val member variable:

Defining a Python Class 2

If we call printVal for the first object, it will print out the value of its member variable:

>>> obj1.printVal()
1

And if we call printVal for the second object, it will print out the value of its member variable:

>>> obj2.printVal()
2

Standard Python Class Methods

Python classes have many standard methods, such as __init__ which we saw above, that gets called when a new instance of the class is created. These are some of the more commonly-used ones:

  • __del__: Called when an instance is about to be destroyed, which lets you do any clean-up e.g. closing file handles or database connections
  • __repr__ and __str__: Both return a string representation of the object, but __repr__ should return a Python expression that can be used to re-create the object. The more commonly used one is __str__, which can return anything.
  • __cmp__: Called to compare the object with another object. Note that this is only used with Python 2.x. In Python 3.x, only rich comparison methods are used. Such as __lt__.
  • __lt____le____eq____ne____gt__ and __ge__: Called to compare the object with another object. These will be called if defined, otherwise Python will fall-back to using __cmp__.
  • __hash__: Called to calculate a hash for the object, which is used for placing objects in data structures such as sets and dictionaries.
  • __call__: Lets an object be “called” e.g. so that you can write things like this: obj(arg1,arg2,...).

Python also lets you define methods that let an object act like an array (so you can write things like this: obj[2] = "foo"), or like a numeric type (so you write things like this: print(obj1 + 3*obj2).

Python Class Example

Here’s a simple example of a class in action that models a single card in a deck of playing cards.

Python 3.x

class Card:
    # Define the suits
    DIAMONDS = 1
    CLUBS = 2
    HEARTS = 3
    SPADES = 4
    SUITS = {
        CLUBS: 'Clubs',
        HEARTS: 'Hearts',
        DIAMONDS: 'Diamonds',
        SPADES: 'Spades'
    }
 
    # Define the names of special cards
    VALUES = {
        1: 'Ace',
        11: 'Jack',
        12: 'Queen',
        13: 'King'
    }
 
    def __init__(self, suit, value):
        # Save the suit and card value
        self.suit = suit
        self.value = value
 
    def __lt__(self, other):
        # Compare the card with another card
        # (return true if we are smaller, false if
        # we are larger, 0 if we are the same)
        if self.suit < other.suit:
            return True
        elif self.suit > other.suit:
            return False
 
        if self.value < other.value:
            return True
        elif self.value > other.value:
            return False
 
        return 0
 
    def __str__(self):
        # Return a string description of ourself
        if self.value in self.VALUES:
            buf = self.VALUES[self.value]
        else:
            buf = str(self.value)
        buf = buf + ' of ' + self.SUITS[self.suit]
 
        return buf

Python 2.x

class Card:
    # Define the suits
    DIAMONDS = 1
    CLUBS = 2
    HEARTS = 3
    SPADES = 4
    SUITS = {
        CLUBS: 'Clubs',
        HEARTS: 'Hearts',
        DIAMONDS: 'Diamonds',
        SPADES: 'Spades'
    }
 
    # Define the names of special cards
    VALUES = {
        1: 'Ace',
        11: 'Jack',
        12: 'Queen',
        13: 'King'
    }
 
    def __init__(self, suit, value):
        # Save the suit and card value
        self.suit = suit
        self.value = value
 
    def __cmp__(self, other):
        # Compare the card with another card
        # (return <0 if we are smaller, >0 if
        # we are large, 0 if we are the same)
        if self.suit < other.suit:
            return -1
        elif self.suit > other.suit:
            return 1
        elif self.value < other.value:
            return -1
        elif self.value > other.value:
            return 1
        else:
            return 0
 
    def __str__(self):
        # Return a string description of ourself
        if self.value in self.VALUES:
            buf = self.VALUES[self.value]
        else:
            buf = str(self.value)
        buf = buf + ' of ' + self.SUITS[self.suit]
 
        return buf

We start off by defining some class constants to represent each suit, and a lookup table that makes it easy to convert them to the name of each suit. We also define a lookup table for the names of special cards (Ace, Jack, Queen and King).

The constructor, or __init__ method, accepts two parameters, the suit and value, and stores them in member variables.

The special __cmp__ method is called whenever Python wants to compare a Card object with something else. The convention is that this method should return a negative value if the object is less-than the other object, a positive value if it is greater, or zero if they are the same. Note that the other object passed in to be compared against can be of any type but for simplicity, we assume it’s also a Card object.

The special __str__ method is called whenever Python wants to print out a Card object, and so we return a human-readable representation of the card.

Here is the class in action:

>>> card1 = Card(Card.SPADES, 2)
>>> print(card1)
2 of Spades
>>> card2 = Card(Card.CLUBS, 12)
>>> print(card2)
Queen of Clubs
>>> print(card1 > card2)
True

Note that if we hadn’t defined a custom __str__ method, Python would have come up with its own representation of the object, something like this:

<__main__.Card instance at 0x017CD9B8>

So, you can see why it’s a good idea to always provide your own __str__ method. ????

Private Python Class Methods and Member Variables

In Python, methods and member variables are always public i.e. anyone can access them. This is not very good for encapsulation (the idea that class methods should be the only place where member variables can be changed, to ensure that everything remains correct and consistent), so Python has the convention that a class method or variable that starts with an underscore should be considered private. However, this is only a convention, so if you really want to start mucking around inside a class, you can, but if things break, you only have yourself to blame!

Class methods and variable names that start with two underscores are considered to be private to that class i.e. a derived class can define a similarly-named method or variable and it won’t interfere with any other definitions. Again, this is simply a convention, so if you’re determined to poke around in another class’s private parts, you can, but this gives you some protection against conflicting names.

We can take advantage of the “everything is public” aspect of Python classes to create a simple data structure that groups several variables together (similar to C++ POD’s, or Java POJO’s):

class Person
    # An empty class definition
    pass
>>> someone = Person()
>>> someone.name = 'John Doe'
>>> someone.address = '1 High Street'
>>> someone.phone = '555-1234'

We create an empty class definition, then take advantage of the fact that Python will automatically create member variables when they are first assigned.

Also Read: Java Program to Print Heart Star Pattern

How to Calculate Exponents using Python

Using Exponents in Python | How to Calculate Exponents using Python? | Python math.exp() Method

Are you wondering about using exponents? Do you need help in programming exponents logic using python? Then, here is the perfect answer for all your queries. The tutorial on how to calculate exponents in python will make you understand clearly about using exponents in python. There are few ways to calculate exponents using python. Want to explore what are they? get into this tutorial and understand calculating the exponential value in python.

How to Calculate Exponents using Python?

In multiple ways, python permit users to calculate the exponential value of a number. Let’s take a look at them in a detailed way:

1. Calculate Python exponents with the ** Operator

To raise a number to the power of another number, you need to use the “**” operator. Where multiplying two numbers only uses one * symbol, the operator for raising one number to the power of another uses two: **.

Let’s see an illustration. To obtain 4 squared (4 raised to the power of two is another way of saying it), your code would look like this:

4**2

Easy, right?

To print the results of the equation above, don’t forget to use the print command.:

print(4**2)

The output of the code would be:

16

The following snippet will furnish you with an example of how we would use exponents in a real context. In the snippet, we raise two to the power of the numbers 0-5 using an anonymous function (lambda) and print the results.

squares = 5

result = list(map(lambda x: 2 ** x, range(terms)))

for i in range(squares):
print("2 raised to the power of",i,"is",result[i])

So the output of the snippet above would be:

2 raised to the power of 0 is 1
2 raised to the power of 1 is 2
2 raised to the power of 2 is 4
2 raised to the power of 3 is 8
2 raised to the power of 4 is 16
2 raised to the power of 5 is 32

Also Check: Python Code Snippets Solving Quadratic Equation

2. Calculate Python exponents with the pow() function

One more way to calculate the exponent values is by using the built-in pow() function. It takes two arguments, the first is the base and the second one is the exponent to use. This pow() function always computes an exact integer power.

The syntax for using the pow() function is: pow(base, exponent)

The example of pow() function

Let’s take a look at the following example python program to see how it works:

base = 3
exponent = 4
print "Exponential Value is: ", pow(base, exponent)

Output: 

Exponential Value is: 81

3. Using Python math.exp() Method

Themath.exp()method returns E raised to the power of x (Ex). ‘E’ is the base of the natural system of logarithms (approximately 2.718282) and x is the number passed to it.

Syntax: math.exp(x)

Example – Calculating exponential value using math.exp() method in python

#Import math Library
import math

#find the exponential of the specified value
print(math.exp(65))
print(math.exp(-6.89))

Output: 

1.6948892444103338e+28
0.0010179138409954387

4. Using Python Math Module’s pow() Function

For getting the exponent, math’s pow() is also the best way and it allows not only two arguments which is the biggest difference between the two pow() functions.

The syntax for using the math’s pow() function is math.pow(x, y) and it converts both its arguments to type float.

Example:

The following program will make you understand how it works:

import math

 
m_pow1 = math.pow(2, 3)
 
m_pow2 = math.pow(4.5, 3)
 
m_pow3 = math.pow(3, 2.5)
 
print("The result ofpow(2, 3,3) = " ,m_pow1)
 
print("The result of pow(4, 2, 4) = " ,m_pow2)
 
print("The result of pow(5, 3, 6) = " ,m_pow3)

Output: 

The result of math.pow(2, 3) = 8.0
The result of math.pow(4.5, 3) = 91.125
The result of math.pow(3, 2.5) = 15.588457268119896

If you’re looking for a way to understand how to handle exponents properly in Python, the above-explained code snippets are a great option for exploring that skill.

Try More:

Gift Nifty

Using math in python

Using math in python

Math in Python

The Python distribution includes the Python interpreter, a very simple development environment, called IDLE, libraries, tools, and documentation.

Python is preinstalled on many (if not all) Linux and Mac systems, but it may be an old version.

Read Also: Python Program to Find Number of Rectangles in N*M Grid

Calculator

To begin using the Python interpreter as a calculator, simple type python in the shell.

>>> 2 + 2
4

>>> 4 * 2
8

>>> 10 / 2
5

>>> 10 - 2
8

Counting with variables

Put in some values into variables to count the area of a rectangle

>>> length = 2.20
>>> width = 1.10
>>> area = length * width
>>> area
2.4200000000000004

Counter

Counters are useful in programming to increase or decrease a value everytime it runs.

>>> i = 0
>>> i = i + 1
>>> i
1
>>> i = 1 + 2
>>> i
3

Counting with a While Loop

Here is an example showing when it’s useful to use counters

>>> i = 0
>>> while i < 5:
...     print i
...     i =  i + 1
... 
0
1
2
3
4

The program counts from 0 to 4. Between the word while and the colon, there is an expression that at first is True but then becomes False.

As long as the expression is True, the following code will run.

The code that needs to be run has to be indented.

The last statement is a counter that adds 1 to the value for everytime the loop runs.

Multiplication table

Making a multiplication table in Python is simple.

table = 8
start = 1
max = 10
print "-" * 20
print "The table of 8"
print "-" * 20
i = start
while i <= max:
    result = i * table
    print i, " * ", table, " =" , result
    i = i + 1
print "-" * 20
print "Done counting..."
print "-" * 20

>>Output:

——————–
The table of 8
——————–
1 * 8 = 8
2 * 8 = 16
3 * 8 = 24
4 * 8 = 32
5 * 8 = 40
6 * 8 = 48
7 * 8 = 56
8 * 8 = 64
9 * 8 = 72
10 * 8 = 80
——————–
Done counting…

Try More:

Nr4 And Nr7

Python Program to Calculate the Average Score

Python Program to Calculate the Average Score

Overview

This script will calculate the average of three values.

Make sure to put in "int" before the raw_input function, since we are using integers.
# Get three test score
round1 = int(raw_input("Enter score for round 1: "))

round2 = int(raw_input("Enter score for round 2: "))

round3 = int(raw_input("Enter score for round 3: "))
   
# Calculate the average
average = (round1 + round2 + round3) / 3

# Print out the test score
print "the average score is: ", average
Happy Scripting

Must Try:

GRASIM Pivot Point Calculator

Quick Sort A Tutorial and Implementation Guide

Quick Sort: A Tutorial and Implementation Guide

Prerequisites

To learn about Quick Sort, you must know:

  1. Python 3
  2. Python data structures – Lists
  3. Recursion

What is Quick Sort?

We are in the fifth and final tutorial of the sorting series. The previous tutorial talks about Bubble Sort, Insertion Sort, Selection Sort, and Merge Sort. If you haven’t read that, please do as we will be building off of those concepts. Like all sorting algorithms, we consider a list to be sorted only if it is in ascending order. Descending order is considered the worst unsorted case.

Quick Sort is quite different and complicated from the sorting techniques we have seen so far. In this technique, we select the first element and call it the pivot. The idea is to group elements such that elements to the left of the pivot are smaller than the pivot and the elements to the right of the pivot are larger than the pivot.

This is done by maintaining two pointers left and right. The left pointer points to the first element after the pivot. Let us refer to the element pointed by left as lelement. Similarly, the right pointer points to the farthest element on the right side of the list. Let us call this element as relement. At each step, compare lelement with pivot and relement with pivot.

Remeber lelement < pivot and relement > pivot. If these conditions are not satisfied, the lelement and relement are swapped. Else, left pointer is incremented by 1 and the right pointer is decremented by 1.

When left >= right, the pivot is swapped with either the lelement or relement. The pivot element will be in its correct position. Then continue the quick sort on the left half and the right half of the list.

Let us see this using an example, alist = [5,9,6,2,7,0]

PivotLeftRightCompareActionalist
59 [1]0 [5]9>5

0<5

 

Swap 0 and 9

Increment left by 1

Decrement right by 1

[5,0,6,2,7,9]
56 [2]7[4]6>5

7>5

Decrement right by 1 pointer and leave left pointer as it is[5,0,6,2,7,9]
56 [2]2[3]6>5

2<5

Swap 2 and 6

Increment left by 1

Decrement right by 1

[5,0,2,6,7,9]
56[3]2[2]Stop (since left>right)Swap 5 and 2[2,0,5,6,7,9]

Similarly, perform Quick Sort on the left half – [2,0] and on the right half [6,7,9]. Repeat this process until the whole list is sorted. Even though we can see that the right half is already sorted, the algorithm has no way of knowing this.

See this animation for better understanding.

How to implement Quick Sort?

Now that you have a fair understanding of what Quick Sort is, let us take a look at the algorithm and its code.

Algorithm

  1. Choose a pivot
  2. Set a left pointer and right pointer
  3. Compare the left pointer element (lelement) with the pivot and the right pointer element (relement) with the pivot.
  4. Check if lelement<pivot and relement>pivot:
    1. If yes, increment the left pointer and decrement the right pointer
    2. If not, swap the lelement and relement
  5. When left >= right, swap the pivot with either left or right pointer.
  6. Repeat steps 1 – 5 on the left half and the right half of the list till the entire list is sorted.

Code

def quickSort(alist):

  quickSortHelper(alist,0,len(alist)-1)

def quickSortHelper(alist,first,last):

  if first<last:
      splitpoint = partition(alist,first,last)
      quickSortHelper(alist,first,splitpoint-1)
      quickSortHelper(alist,splitpoint+1,last)

def partition(alist,first,last):

  pivotvalue = alist[first]
  leftmark = first+1
  rightmark = last
  done = False

  while not done:
      while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
          leftmark = leftmark + 1

      while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
          rightmark = rightmark -1

      if rightmark < leftmark:
          done = True
      else:
          temp = alist[leftmark]
          alist[leftmark] = alist[rightmark]
          alist[rightmark] = temp

  temp = alist[first]
  alist[first] = alist[rightmark]
  alist[rightmark] = temp

  return rightmark

alist = [54,26,93,17,77,31,44,55,20]
quickSort(alist)
print(alist)

Courtesy of the code is Interactive Python.

How to choose a pivot?

Choosing the pivot is very crucial as it determines the efficiency of this algorithm. If we get an already sorted list and we choose the first element as pivot then it will be a disaster! This is because there will be no element greater than the pivot and this drastically brings down the performanceTo avoid this, several methods are available to select the pivot value. One such method is the median method. In this, we choose the first element, the last element, and the middle element. After comparing these three elements, we choose the one with the median value. Let us see this with an example, alist = [5,6,9,0,3,1,2]

First element is 5, last element is 2 and the middle element is 0. Comparing these values, it is clear that 2 is the median value and this selected as pivot. Methods such as this ensure that we don’t end up with the worst choice as our pivot. Remember the worst choice for pivot is the smallest or the largest value in the list.

Conclusion

Quick Sort works best with small and large number of elements. The worst case runtime complexity of Quick Sort is O(n2) similar to that of Insertion and Bubble Sort but it can be improved to O(nlog(n)) as discussed in the previous section. Unlike Merge Sort this doesn’t have the disadvantage of using extra memory or space. That is why this is one of the most commonly used sorting techniques. That’s all for this tutorial. Happy Pythoning!

You can Also Check: