Subscribe to DSC Newsletter

Comparative study note of Java and Python (II)

2.The control flow statements

Now we try to use the two languages to do a practice. The following, one in Java one in Python, are two programs with the same algorithm.

/*

 * program author: Yue Cai Zhu.

 * Finish date: 14/10/2013.

 * Program name: <Dive Scoring program> The program is used to calculate

 * the final result of a dive.

 */

import java.util.Scanner;

public class DiveScoring {

       public static void main(String[] args) {

              //Constants NUM_OF_SCORE and NUM_OF_DEGREE are used to specify the size of the array

              //which is used to store the scores and the degree of difficulty of a dive.

              final int NUM_OF_SCORE = 7, NUM_OF_DEGREE = 1,

              //Constants INDEX_OF_SCORE and INDEX_OF_DEGEE are used to denote the position of the corresponding data.

                           INDEX_OF_SCORE = 0, INDEX_OF_DEGEE = 1;

              //Constants DEGREE_UB and DEGREE_LB define the range of the degree of difficulty.

              final double  DEGREE_UB = 3.8, DEGREE_LB = 1.2, SCORE_UB = 10, SCORE_LB = 1,

                                 MULTIPLIER = 0.6;

//Constant MULTIPLIER is given to be 0.6

              double[][] diveResult = new double[2][];

//Declare the array diveResult.

              diveResult[INDEX_OF_SCORE] = new double[NUM_OF_SCORE];

//This sub array is used to store scores.

              diveResult[INDEX_OF_DEGEE] = new double[NUM_OF_DEGREE];

//This sub array is for the degree of difficulty.

//Variables largest and smallest are used to carry the highest and lowest //score which are being thrown out.

              double largest, smallest,

                        sum = 0, result = 0;

//sum carries the sum of the scores;result carries the final results.

              Scanner scoreInput = new Scanner(System.in);

//Out print the prompt message asking for the input of degree of difficulty.

              System.out.print("Please input the degree of difficulty: ");

              //assign the input value to the corresponding sub array.

              diveResult[INDEX_OF_DEGEE][0] = scoreInput.nextDouble();

//If condition to check whether the input value is valid. If not, then the program will be closed.

              if (diveResult[INDEX_OF_DEGEE][0] < DEGREE_LB

                           || diveResult[INDEX_OF_DEGEE][0] > DEGREE_UB) {

                     //Out print the closing message.

                     System.out.println("The input value is not valid. The system will shut down.");

                     System.exit(0);

              }

//The loop asks for the input of the 7 scores and stores the input value

//to the corresponding sub array.

              for (int i = 0; i < diveResult[INDEX_OF_SCORE].length; i++) {

                     System.out.print("Please input score " + (i + 1) + ": ");

                     diveResult[INDEX_OF_SCORE][i] = scoreInput.nextDouble();

//The while sub loop checks the validity of each input value.

//If the input is un valid, then the program keeps asking for a valid input.

                     while (diveResult[INDEX_OF_SCORE][i] < SCORE_LB

                                  || diveResult[INDEX_OF_SCORE][i] > SCORE_UB){

              System.out.println("The input value is not valid.");

              System.out.println("Please input a value between " + SCORE_LB " and " + SCORE_UB);

              diveResult[INDEX_OF_SCORE][i] = scoreInput.nextDouble();

                     }

              }

              scoreInput.close();//Close the Scanner instance scoreInput.

              //Initialize the variables largest and smallest.

              largest = diveResult[INDEX_OF_SCORE][0];

              smallest = diveResult[INDEX_OF_SCORE][0];

              //The for loop compares the scores, determines the highest and

              //lowest one, and sums up the scores.

              for (int i = 0; i < diveResult[INDEX_OF_SCORE].length; i++) {

                     sum += diveResult[INDEX_OF_SCORE][i];

                     if (largest < diveResult[INDEX_OF_SCORE][i])

                           largest = diveResult[INDEX_OF_SCORE][i];

                     if (smallest > diveResult[INDEX_OF_SCORE][i])

                           smallest = diveResult[INDEX_OF_SCORE][i];

              }

              //Calculate out print the final result.

            result = (sum - largest - smallest) * MULTIPLIER*diveResult[INDEX_OF_DEGEE][0];

            System.out.println("The highest score " + largest+" and the lowest score "+ smallest +" will be thrown out.");

            System.out.print("The final score is: ");

            System.out.printf("%.4f", result);

       }

}

//End

# This is a the DiveScoring coding in Python

# program author: Yue Cai Zhu.

# Finish date: 14/10/2013.

# Program name: <Dive Scoring program> The program is used to calculate

# the final result of a dive.

#Declare and initialize the variables.

NUM_OF_SCORE = 7; MULTIPLIER = 0.6

DEGREE_UB = 3.8; DEGREE_LB = 1.2

SCORE_UB = 10.0 ; SCORE_LB = 1.0

score = []#Declare the list score

largest = SCORE_LB

smallest = SCORE_UB

result = 0.0

#for loop asks for input, and append the input value to the list score.

for k in range(NUM_OF_SCORE):

    score.append(float(raw_input("Please input the score %d" % (k + 1))))

    #while loop checks validity and keep asking for a valid input.

    while score[k] < SCORE_LB or score[k] > SCORE_UB :

        score[k] = float(raw_input("The value input is out of range. \nPlease input a valid value."))

    #if condition compares the input value and determines the largest and smallest.

    if largest <= score[k]:

        largest = score[k]

    if smallest >= score[k]:

        smallest = score[k]

    result += score[k]#sum up the scores to the variable result.

#Ask for an input of the degree of difficulty and name the value input difficultDegree.

difficultDegree = float(raw_input("Please input the degree of difficulty."))

#while loop checks the validity of difficultDegree and keep asking for a valid input.

while difficultDegree < DEGREE_LB or difficultDegree > DEGREE_UB :

    difficultDegree = float(raw_input("The input is not valid. \nPlease input the degree of difficulty."))

result = (result - largest - smallest) * MULTIPLIER *difficultDegree

#Calculate the final result

#Print the required messages.

print "The largest score being thrown out is " + str(largest)

print"The smallest score being thrown out is " + str(smallest)

print "The final result is " + str(result)

print score

#End       

   

       

       

I: conditioning statement. 

There are two conditioning statements in Java :

1: if (condition1) {

Body;

}

    else if (condition2)//optional

    else (condition3) //optional

2: switch (variable){

    case value1:

     statements;

    break;//optional, but you’d better use it if you don’t want any troubles.

   Case value 2:

 …..

   default ://optional

  

Someone told me that a good programmer should avoid using “break” statement, so we mainly use “if..  else if …..else “.

In Python, there is only one conditioning statement:  if …elif….else…. . The application of the ‘if’ statement is the same in Python as in Java.

II: looping

1: “for”  loop

In Java we usually cast the “for” loop like this:

 for (int i=0; i < someValue; i++){

   body}

In Python:

for  element in sequence_Name :

    statement1

    statement2

    ….

The sequence could be a dictionary type or any of the sequence types in Python. This feature makes the “for” loop very convenience combining the ease of creating sequence types in Python.  

2: “while” loop

The ways of using “while” loop in both languages are very similar. In Java, there is a complement: ”do…while” loop with which the looping body will be executed at least once. In Python there is an optional “else” statement which will be executed when the looping finishes cleanly.

Now here comes the thing. In Java, the indentation is not very important( at least for the compiler). Because we use “;” to indicate that a statement is finished , and use “{}” to indicate a block. In Python, the indentation is very important, because it uses indentation to indicate a block. For example, in Python:

if a<b:

    a+=b

    d=a+b

is different from:

if a<b:

    a+=b

d=a+b

For the upper one, there are two statements in the block, for the lower one there is only one. Thus we have to be very careful about the indentation when writing code in Python. You don’t want to check the indentation mistakes when you are writing a program with a bunch of looping and conditioning.

Views: 964

Comment

You need to be a member of AnalyticBridge to add comments!

Join AnalyticBridge

On Data Science Central

© 2019   AnalyticBridge.com is a subsidiary and dedicated channel of Data Science Central LLC   Powered by

Badges  |  Report an Issue  |  Privacy Policy  |  Terms of Service