Kevin

Python Beginner Tutorial 6 - Exceptions and Loops

Recommended Posts

 

This tutorial covers exception handling in Python with try/except and introduces the concept of looping with the while loop. After watching this video you should feel conformable using the try except block to handle errors and using while loops.

Source Code:

def add(num1, num2):
    """Returns num1 plus num2."""
    return num1 + num2


def sub(num1, num2):
    """Returns num1 minus num2."""
    return num1 - num2


def mul(num1, num2):
    """Returns num1 times num2."""
    return num1 * num2


def div(num1, num2):
    """Returns num1 divided by num2."""
    return num1 / num2


def main():
    """Allows user to run basic calculator operations with two numbers."""
    validInput = False
    while not validInput:
        # Get user input
        try:
            num1 = int(input("What is number 1?"))
            num2 = int(input("What is number 2?"))
            operation = int(input("What do you want to do? 1. add, 2. subtract, 3. multiply, or 4. divide. Enter  number: "))
            validInput = True
        except:
            print("Invalid input. Try again.")
    # Determine operation
    if (operation == 1):
        print("Adding...")
        print(add(num1, num2))
    elif (operation == 2):
        print("Subtracting...")
        print(sub(num1, num2))
    elif (operation == 3):
        print("Multiplying...")
        print(mul(num1, num2))
    elif (operation == 4):
        print("Dividing...")
        print(div(num1, num2))
    else:
        print("I don't understand")


main()

 

Share this post


Link to post
Share on other sites

hi kevin, I have a question. Based on my picture, my calculator is looping itself no matter what. When i get the correct answer it goes back to asking the question "what is number 1". Can u tell me y, thanks!

Screen Shot 2017-08-22 at 5.58.34 PM.png

Screen Shot 2017-08-22 at 6.02.47 PM.png

Share this post


Link to post
Share on other sites
12 hours ago, Joshua said:

hi kevin, I have a question. Based on my picture, my calculator is looping itself no matter what. When i get the correct answer it goes back to asking the question "what is number 1". Can u tell me y, thanks!

Do you have another call to main() at the end of the function by any chance? Other than that I don't see anything that would cause that...

Can you post your entire file? When posting code use the button at the top that looks like this "< >". That is the code button. You can paste your code in there and set the language to python in the bottom right. Makes it much easier to help troubleshoot. 

Share this post


Link to post
Share on other sites

Tnx for tutorials.

Have a question about challenge. Everything is fine until I add lines 43-45, program finish with no error no matter what user input is.

def add(num1, num2):
    return num1 + num2

def sub(num1, num2):
    return num1 - num2

def mul(num1, num2):
    return num1 * num2

def div(num1, num2):
    return num1 / num2

def main():
    con1 = True
    while con1:
        validInput = False
        while not validInput:
            try:
                num1 = int(input("Enter number 1? "))
                num2 = int(input("Enter number 2? "))
                operation = int(input("What do you want to do? 1)Add 2)Sub 3)Mul 4)Div. Enter number: " ))
                validInput = True
            except:
                print("Invalid input")
        if(operation == 1):
            print("Adding...")
            print(add(num1, num2))
        elif(operation == 2):
            print("Subtracting...")
            print(sub(num1, num2))
        elif(operation == 3):
            print("Multiplying...")
            print(mul(num1, num2))
        elif(operation == 4):
            print("Dividing...")
            print(div(num1, num2))
        else:
            print("I don't understand")
        cont = input("Do you want to do another calculation? (Y/N)" )
        if(cont != "y"):
            con1 = False
            break
        elif(cont != "Y"):
            con1 = False
            break
        else:
            continue
main()

Even tried:

        if(cont != "y" or cont != "Y"):
            con1 = False
            break

but no luck. How can I use both "y" and "Y"? Can you explain what's going on here? Tnx

Share this post


Link to post
Share on other sites

Hello guys, can someone help me understand what have I done wrong here :D

In last part, when it asks "Do u want some more?" and instead of writing "1" or "2" you type some random shit everything is fine, but if you type "3", "4" etc. is says "Wrong" as it should be but then after asking again "Do you want some more" and pressing "1" it just shuts down without continuation.

Any suggestion would be more than welcome! :)

def main():
   exitInput = False
   while not exitInput:
         correctInput = False
         while not correctInput:
            try:
               num1 = int(input("Enter first number: "))
               num2 = int(input("Enter second number: "))
               operation = int(input("What you want to do: 1 to add , 2 to subtract , 3 to multiply , 4 to divide. Enter number: "))
               correctInput = True
            except:
               print("Invalid operation! Try again.")
         if (operation == 1):
            print("Result:")
            print(add(num1, num2))
         elif (operation == 2):
            print("Result:")
            print(sub(num1, num2))
         elif (operation == 3):
            print("Result:")
            print(multi(num1, num2))
         elif (operation == 4):
            print("Result:")
            print(div(num1, num2))
         else:
            print("You must enter valid operation")
         wtfInput = False
         while not wtfInput:
            try:
               exitingNote = int(input('Do u want some more? Type 1 for "Yes" or 2 for "No": '))
               if (exitingNote == 1):
                  print('Ok')
                  exitInput = False
                  break
               elif (exitingNote == 2):
                  print('Bye bye!')
                  continue
               else:
                  print("Wrong")
                  wtfInput = False
            except:
               print("wtf?")
               wtfInput = False
main()

Share this post


Link to post
Share on other sites

Im currently playing with array. Please let me know what i do wrong here. Thanks in advance.

 

def newlocation(direc):
    if (direc=='u' or direc=='U'):
        location[0] = location[0] -1
    if (direc=='d' or direc=='D'):
        location[0] = location[0] +1    
    if (direc=='l' or direc=='L'):
        location[1] = location[1] -1
    if (direc=='r' or direc=='R'):
        location[1] = location[1] +1
    return location

def main():
    direc = 0
    location = [5,6]
    invalidInput = False
    while (direc != "s"):
        print("you current location" , location[0] , location[1])
        while not invalidInput :
            try:
                direc = input("Where to go next (L/R/U/D)?")
                invalidInput = True
            except:
                print("invalid move. Try again")
        location.clear()
        location = newlocation(direc)
main()
 

Share this post


Link to post
Share on other sites
def add(num1, num2):
    """Returns num1 plus num2."""
    return num1 + num2


def sub(num1, num2):
    """Returns num1 minus num2."""
    return num1 - num2


def mul(num1, num2):
    """Returns num1 times num2."""
    return num1 * num2


def div(num1, num2):
    """Returns num1 divided by num2."""
    return num1 / num2


def main():
    """Allows user to run basic calculator operations with two numbers."""
    validInput = False
    while not validInput:
        # Get user input
        try:
            num1 = int(input("What is number 1?"))
            num2 = int(input("What is number 2?"))
            operation = int(input("What do you want to do? 1. add, 2. subtract, 3. multiply, or 4. divide. Enter  number: "))
            validInput = True
        except:
            print("Invalid input. Try again.")
    # Determine operation
    if (operation == 1):
        print("Adding...")
        print(add(num1, num2))
        con()
    elif (operation == 2):
        print("Subtracting...")
        print(sub(num1, num2))
        con()
    elif (operation == 3):
        print("Multiplying...")
        print(mul(num1, num2))
        con()
    elif (operation == 4):
        print("Dividing...")
        print(div(num1, num2))
        con()
    else:
        print("I don't understand")

def con():
    valid = False
    while not valid:
        try:
            cont = int(input(" do you want to continue? press 1 to continue, press other than 1 to exit "))
            if cont == 1:
                main()
                valid = True
            else:
                return
        except:
            return

hi kevin ty for the tutorials, is my code correct? tell me if there is a mistake please !!! ty

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...