Thread: Repeat code

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2013
    Posts
    12
    Rep Power
    0

    Repeat code


    I am messing around with python, creating small practice programs for myself, and i ran into a problem: i have an if, elif, else statement that i need to repeat if the desired input is not put in.
    Here's the code:
    ____________________________________________________
    transaction_type = raw_input("Deposit or Withdrawal? ")

    if transaction_type.lower() == "deposit":
    >>> truefalse = True
    elif transaction_type.lower() == "withdrawal":
    >>> truefalse = False
    else:
    >>> print ("Please try again")
    >>> # This is where I would want it to go back to the top
    >>> # This is only a small part of my code
    _____________________________________________________

    would i use a loop here? if so how would i set it up in this scenario? thanks for any help.

    ** The forum formatted my code to the left, thats why i used the carrots to represent indentions.
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Location
    39N 104.28W
    Posts
    158
    Rep Power
    3
    In this type of thing I would use a "while..." loop. I don't really know what you're doing in this case (as you say, this is just an exemplary snippet) but consider this:
    Code:
    loop=true
    while loop:
        transaction_type = raw_input("Deposit or Withdrawal? ")
        loop=false
        if...
        elif...
        else: loop=true
  4. #3
  5. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    610
    Rep Power
    65
    Something like this will do ...
    Code:
    while True:
        transaction_type = raw_input("Deposit or Withdrawal? ")
        if transaction_type.lower() == "deposit":
            truefalse = True
            break
        elif transaction_type.lower() == "withdrawal":
            truefalse = False
            break
        else:
            print ("Please try again")
    
    print(truefalse)  # test
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

IMN logo majestic logo threadwatch logo seochat tools logo