CobraCoder
CobraCoder

Reputation: 35

Python - How do I make it so that my other program only executes when an if statement is in agreement?

My program is meant to make some sort of online cookbook and depending on what I want to make, I can choose which program to execute. In order to finally have got it to work, the integer I type in will correspond to the code that I want to run:

enter code here

cookbook = int(input("What recipe would you like to make? (Please state the number)\n"))
if cookbook == 1:
    import mymodule as mx
    mx.greeting("Nana")

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

    mx.omin(2)

    mx.tmin(4)

    mx.cmin(10)

    mx.smallest(0)
else:
    print("Updates pending")

Upvotes: 1

Views: 86

Answers (2)

CobraCoder
CobraCoder

Reputation: 35

What helps is that instead of using words to select which option is to be imported, use numbers and tell the user that in the question. Functions don't seem to be able to process user input, so input it in the code before running as in "mx.omin(2)".

cookbook = int(input("What recipe would you like to make? (Please state the number)\n"))
if cookbook == 1:
    import mymodule as mx
    mx.greeting("Nana")

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

    mx.omin(2)

    mx.tmin(4)

    mx.cmin(10)

    mx.smallest(0)
elif cookbook == 2:
    import sauce as mx
    mx.greeting("Nana")

    mx.cabmin(0.6666)

    mx.carmin(2)

    mx.cookmin(200)

    mx.smallest(0)

    mx.confidence("OK")

    mx.final("sauce")
else:
    print("Updates pending")


Upvotes: 0

001001
001001

Reputation: 588

It seems you want to change which python file you are going to run. You could do this simply by changing the namespace from the imports.

cookbook = input("What recipe would you like to make?")
if cookbook == "pepper":
    import pepper as recipe # This is the name of the file I want to execute
elif cookbook == "pasta":
    import pasta as recipe

recipe.run()

There can be more elegant ways to do it, and use the name itself to load the file directly, but I think this is closest to what you were trying to do.

Here is an example with 3 files, as I understand what you are trying:

cookbook.py

cookbook = input("What recipe would you like to make? ")
if cookbook == "pepper":
    import pepper as recipe
elif cookbook == "pasta":
    import pasta as recipe

recipe.run()

pepper.py

def run():
    print('\n1: Grow plant')
    print('\n2: Get pepper')

pasta.py

def run():
    print('\n1: Mix water with flour and egg')
    print('\n2: Flatten')
    print('\n2: Boil in water')

You then run cookbook.py and type either 'pepper' or 'pasta'

Upvotes: 2

Related Questions