vendredi 27 novembre 2015

if statement in python won't run even though conditions are true

made a program to simulate how life began on Earth in it's simplest form; the bigger number in the array (species[]) eats a smaller number beside it in the array and makes that number smaller. I have made an if statement which says if num > 0 & length > 1, then do whatever where num is the number of cycles the program runs and length is the length of the array, species[]. I have tested both variables and they are both more than 1. Even still, the if statement isn't running, the else is making it break out of the while loop. Any ideas on how could fix it? please explain in a simple way, I just started coding recently. Heres my code:

# Import Packages
import random

# Author
__author__ = 'VectorImage'

# Defaults
print('DEFAULTS')
print('Starting Size = 10')
print('Chance Of New Species = 1')
print('New Species Size = 5')
print('Number of Cycles = 100')
print('\n\n');


# Variables
print('SET VARIABLES')
choice = input('CUSTOM or DEFAULT: ')
p3 = 11

while p3 > 10:
    if choice == 'CUSTOM':
        p1 = int(input('Starting Size: '))
        p2 = int(input('Chance Of New Species (lower number means higher chance): '))-1
        p3 = int(input('New Species Size: '))-1
        p4 = int(input('Number of Cycles: '))
    elif choice != 'CUSTOM':
        p1 = 10
        p2 = 0
        p3 = 5
        p4 = 100
    else:
        print('species size cannot be more than x10')
species = [p1, p1, p1]
length = None
l = None
new_species = None
chance = None
num_range = None
temp_num = None
num = None
print('\n\n')


# Program
def main():
    print('PROGRAM')
    length = len(species)
    if length > 2:
        l = 0
        num = p4
        while 1 < 2:
            print(species)
            if num > 0 & length > 1:
                length = len(species)
                num_range = int(round(random.random()*(p3+1)))
                new_species = int(round(random.random()*p2))
                chance = int(round(random.random()))
                if new_species == 0:
                    if chance == 0:
                        species.insert(len(species) + num_range, length)
                    else:
                        species.insert(len(species) - num_range, length)
                l += 1
                num -= 1
                print('Cycle #', p4-num)
                print(length, ' species')
            else:
                break
            if species[length-1] > species[length-2]:
                temp_num = species[length-1] - num_range * (1 + p3)
                species[length-2] -= temp_num
                species[length-1] += temp_num
            else:
                temp_num = species[length-1] - (num_range * (1 + p3))
                species[length-1] += temp_num
                species[length-2] -= temp_num
            if species[length-1] <= 0:
                del species[length-1]
            elif species[length-2] <= 0:
                del species[length-2]

# RUN
main()

Xsl if statement inside xsl for each statement: how?

i have an xml:

<newsletter country="nl">
<shop id="1">
<primaryOffer type="hunt">

Now i have an xslt:

<xsl:for-each select="//shop[@id='1']">
< do A>
</xsl:for-each>

now i am looking for an if statement, inside the xsl for each statement, which says: if primaryOffer type="hunt" do A, else do B

How do i do this?

I tried

<xsl:for-each select="//shop[@id='1']">
<xsl:if select="//primaryOffer[@type='hunt']">A</xsl:if>
B
</xsl:for-each>

Here is the xml: http://ift.tt/1XwPJX0

Thanks!

Python Class If Statement Not Working

Whenever I run this class (included the applicable section of code):

def setLevel(self, level):
    if (self.__level == "Freshman" or self.__level == "Sophomore" or self.__level == "Junior" or self.__level == "Senior"):
        self.__level = level
    else:
        raise ValueError("Level must be Freshman, Sophomore, Junior, or Senior")

through this section of the driver class.

undergraduate = Undergraduate("Jonathan", "Zhang", "214-000-0000", Address("611 Leon", "Austin", "Texas", 78705), "234-56-7890", "student@utexas.edu", 2300106, "Management Information Systems", 3.95, "Loser")

I am allowed to use a string not included in the if statement. If I need to post anymore parts of the code, I can.

Best way to inverse if-else based on a condition

I wanted an if-else clause to behave based on an input that would leave the statements as is, or switch statements between if and else.

For example:

if (condition)
   do A;
   do B;
else
   do C;

If I have an input that indicates reverse, this should happen:

if (reverse)
   do C;
else
   do A;
   do B;

What is the best way to merge the two if-else statements above? Thanks.

if/or function doesn't work properly

i am working on a very simple code, just starting with python actually, but this one problem keeps popping up. i have this code, and many in a similar structure:

if input() == "no" or  input() == "i said no" or  input() == "I said no." or  input() == "No.":
        print("Okay! Would you like to teach me more words or quit?")

and when i run it, it works but i have to input the answer 4 times for it to register. same with others - i have to input as many times as i have my input in the if function. i tried adjusting the code like this:

if (input() == "no" or  input() == "i said no" or  input() == "I said no."  or  input() == "No."):
        print("Okay! Would you like to teach me more words or quit?")

but it still didn't work. how can i solve this issue?

How to write an expression for if that is always true?

How to write an if condition without using variables and operators? The condition should always be true.

Trying to stop an ActionPerformed from executing certain code if an exception is thrown

I have been working on this code for a few days now and cant figure out how to fix one specific thing about it. I want to be able to stop the code from executing below the

this.errors();

if (error == false) {

//this.errors();

//Part of the code. 


private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
    errorTextArea.setText(null);
    try {
        String stringLength = lengthTextField.getText();
        lengthInMeters = Double.parseDouble(stringLength);

        String stringDiameter = diameterTextField.getText();
        diameterInInches = Double.parseDouble(stringDiameter);

        String quantity = quantityTextField.getText();
        finalQuantity = Integer.parseInt(quantity);

        this.errors();
        if (error == false) {
            //this.errors();
       } else {

            /**
             * Checks which check boxes and radio buttons are selected and
             * returns true.
             *
             */
            if (chemicalResistanceCheckBox.isSelected()) {
                chemical = true;
            }

            if (outerReinforcementCheckBox.isSelected()) {
                outerReinforcement = true;
            }

            if (innerInsulationCheckBox.isSelected()) {
                innerInsulation = true;
            }
            if (zeroColourRadioButton.isSelected()) {
                colourInput = 0;
            }
            if (oneColourRadioButton.isSelected()) {
                colourInput = 1;
            }
            if (twoColourRadioButton.isSelected()) {
                colourInput = 2;
            }
            // Creates pipe, gets the size then returns a quote.
            this.createPipe();
            double sizeOfPipe = this.orderedSize(lengthInMeters, diameterInInches);

            // Prints to the text areas.
            double costOfSelectedPipe = quote * sizeOfPipe;
            cartTextArea.setText(cartTextArea.getText() +"\n"+ "Pipe price:  " + df.format(costOfSelectedPipe) + "\n");
            double costOfSelectedOrder = costOfSelectedPipe * finalQuantity;
            prices.add(costOfSelectedOrder);
            currentOrderTotal.add(costOfSelectedOrder);
            cartTextArea.append("Total: " + df.format(costOfSelectedOrder) + "\n");
            grandTotal = this.finalTotal();
            orderTotal = this.currentTotal();

            currentOrderPriceLabel.setText("£"+df.format(orderTotal));
            totalPriceLabel.setText("£"+df.format(grandTotal));

        }
    } catch (NumberFormatException e) {
        errorTextArea.append("Please input numeric characters");
    }

} 

Below this we have a method for error messages we would like to be called if the try catch throws an exception. Currently if you set the value of error to be true it will work perfectly but not print out the specific error messages we want, and if you set it to false when you try and use the submit button to on the gui we have created nothing will happen at all it seems to get stuck.

private void errors(){

    if (lengthInMeters > 6.0 || lengthInMeters < 0.10) {
            errorTextArea.append("\n" +"Input a length between 0.1m to 6m, please.");
            error = true;
    }
    if (diameterInInches < 1 || diameterInInches > 30) {
            errorTextArea.append("\n" +"Please input a diameter between 1 and 30 inches");
            error = true;
        }
    if (finalQuantity > 300 || finalQuantity < 1) {
            errorTextArea.append("\n" +"Please order at least one pipe, but less than 300");
            error = true;
        }

}      

I have a link to github with all the code in it, if that would make it easier id very much appreciate some help here if anyone has anything. even if I am just plain wrong in what it is I am trying to do.

http://ift.tt/1TblOT3

example of the program working

enter image description here