lichade
lichade

Reputation: 13

try/except statements python

How can I include a restriction into this following loop with a minimal amount of coding? I'm using try and except but I can't figure out a way so that it will include only positive numbers. How can I achieve this?

dome_loop = 1
    while dome_loop == 1:
        dome = input("Enter in the radius of your dome in cm: ")
        try:
            dome = float(dome)
            break
        except ValueError :
                print("Please enter a value greater than 45!")
    tunnel_loop = 2
    while tunnel_loop == 2:
        tunnel = input("Enter the length of your igloo's tunnel in cm: ")
        try:
            tunnel = float(tunnel)
            break
        except ValueError:
            print ("Please enter in a positive number!")

This is my entire code:

import sys
import math


def iglooSelect(selection):
#Introduce selection
    if str(selection) == "budget" or selection == "1":
        print ("\nYou have selected (1) Budget ")
        x=45+15; y=45*25
    elif str(selection) == "superior" or selection == "2":
        print ("\nYou have selected (2) Superior")
        x=45+20; y=45*25
    elif str(selection) == "luxury" or selection == "3":
        print ("\nYou have selected (3) Luxury")
        x=45+25; y=30*20

    print ("NOTE tunnel radius is 45cm(fixed)")
#Restrictions: Dome radius must be over 45.
    dome_loop = 1
    while dome_loop == 1:
        dome = input("Enter in the radius of your dome in cm: ")
        try:
            dome = float(dome)
            break
        except ValueError :
                print("Please enter a value greater than 45!")
    tunnel_loop = 2
    while tunnel_loop == 2:
        tunnel = input("Enter the length of your igloo's tunnel in cm: ")
        try:
            tunnel = float(tunnel)
            break
        except ValueError:
            print ("Please enter in a positive number!")



##    while tunnel!=(45):
##        tunnel = float(input("\nEnter the length of your igloo's tunnel in cm: "))
    tunnelarea = math.pi*tunnel*45 + math.pi*45**2                                                                                                                                                                                                                                                                                 
    domearea = 2*math.pi*dome**2 - 0.5*math.pi*x**2
    bricksrequired = (tunnelarea + domearea) /y
    print ("\nThis program will now calculate the number of bricks required", bricksrequired)
    print ("\nYou will require:",math.ceil(bricksrequired),"bricks")

    return None

def program(start):
    print ("Hello Eric the builder")
    print ("This program will calculate how mny bricks are required to build an igloo")
    # Start, print brick types
    start = input("Enter YES to start: ")
    if start == "yes":
        print ("(1) Budget - length: 45cm x height: 25cm x depth: 15cm")
        print ("(2) Superior - length: 35cm x height: 25cm x depth: 20cm")
        print ("(3) Luxury - length: 30cm x height: 20cm x depth: 25cm")
    else:
        print ("Error. This program will now exit")
        sys.exit()

    selection = input("Select your brick type: ")
    while selection not in [str(1),str(2),str(3)]:
        selection = input("You can only choose 1,2 or 3: ")

    iglooSelect(selection)
    restart = input("Enter YES to restart")
    return restart


    #Bricks rounded to nearest integer

start="yes"
while start == "yes":
    start=program(start)

print ("Error. This program will now exit")
sys.exit()

Upvotes: 0

Views: 80

Answers (2)

paxdiablo
paxdiablo

Reputation: 881113

You're probably looking for something like:

dome = -1
while dome <= 45:
    try:
        dome = float(input("Enter in the radius of your dome in cm: "))
    except ValueError:
        dome = -1
    if dome <= 45:
        print ("Please enter a valid value greater than 45!")

This initially sets dome to an illegal value so that the loop is entered.

The loop then attempts to set it to something based on what the user enters but, if that wasn't a valid floating point number, forces it back to an illegal value. Entry of a valid floating point value like 17 is still considered illegal.

So the only way to exit the loop is to enter a valid floating point value that is also greater than forty-five.

A similar method can be used to ensure that tunnel is valid and non-negative:

tunnel = -1
while tunnel < 0:
    try:
        tunnel = float(input("Enter the length of your igloo's tunnel in cm: "))
    except ValueError:
        tunnel = -1
    if tunnel < 0:
        print ("Please enter a valid positive number!")

With those changes, your complete script now looks like:

import sys
import math

def iglooSelect(selection):
#Introduce selection
    if str(selection) == "budget" or selection == "1":
        print ("\nYou have selected (1) Budget ")
        x=45+15; y=45*25
    elif str(selection) == "superior" or selection == "2":
        print ("\nYou have selected (2) Superior")
        x=45+20; y=45*25
    elif str(selection) == "luxury" or selection == "3":
        print ("\nYou have selected (3) Luxury")
        x=45+25; y=30*20

    print ("NOTE tunnel radius is 45cm(fixed)")

#Restrictions: Dome radius must be over 45.
    dome = -1
    while dome <= 45:
        try:
            dome = float(input("Enter in the radius of your dome in cm: "))
        except ValueError:
            dome = -1
        if dome <= 45:
            print ("Please enter a valid value greater than 45!")

    tunnel = -1
    while tunnel < 0:
        try:
            tunnel = float(input("Enter the length of your igloo's tunnel in cm: "))
        except ValueError:
            tunnel = -1
        if tunnel < 0:
            print ("Please enter a valid positive number!")

##    while tunnel!=(45):
##        tunnel = float(input("\nEnter the length of your igloo's tunnel in cm: "))
    tunnelarea = math.pi*tunnel*45 + math.pi*45**2
    domearea = 2*math.pi*dome**2 - 0.5*math.pi*x**2
    bricksrequired = (tunnelarea + domearea) /y
    print ("\nThis program will now calculate the number of bricks required", bricksrequired)
    print ("\nYou will require:",math.ceil(bricksrequired),"bricks")

    return None

def program(start):
    print ("Hello Eric the builder")
    print ("This program will calculate how mny bricks are required to build an igloo")
    # Start, print brick types
    start = input("Enter YES to start: ")
    if start == "yes":
        print ("(1) Budget - length: 45cm x height: 25cm x depth: 15cm")
        print ("(2) Superior - length: 35cm x height: 25cm x depth: 20cm")
        print ("(3) Luxury - length: 30cm x height: 20cm x depth: 25cm")
    else:
        print ("Error. This program will now exit")
        sys.exit()

    selection = input("Select your brick type: ")
    while selection not in [str(1),str(2),str(3)]:
        selection = input("You can only choose 1,2 or 3: ")

    iglooSelect(selection)
    restart = input("Enter YES to restart")
    return restart


    #Bricks rounded to nearest integer

start="yes"
while start == "yes":
    start=program(start)

print ("Error. This program will now exit")
sys.exit()

And here's a sample run to show it in action:

Hello Eric the builder
This program will calculate how mny bricks are required to build an igloo
Enter YES to start: yes
(1) Budget - length: 45cm x height: 25cm x depth: 15cm
(2) Superior - length: 35cm x height: 25cm x depth: 20cm
(3) Luxury - length: 30cm x height: 20cm x depth: 25cm
Select your brick type: 1

You have selected (1) Budget
NOTE tunnel radius is 45cm(fixed)
Enter in the radius of your dome in cm: 40
Please enter a valid value greater than 45!
Enter in the radius of your dome in cm: 46
Enter the length of your igloo's tunnel in cm: hello
Please enter a valid positive number!
Enter the length of your igloo's tunnel in cm: -7
Please enter a valid positive number!
Enter the length of your igloo's tunnel in cm: 4

This program will now calculate the number of bricks required 12.948946786396329

You will require: 13 bricks
Enter YES to restart
Error. This program will now exit

Upvotes: 1

Marcin
Marcin

Reputation: 238081

You could do as follows:

def is_float(in_str):    
    try:
        a_float = float(in_str)
        return True        
    except ValueError :    
        return False


while dome_loop == 1:
    dome = input("Enter in the radius of your dome in cm: ")
    if not is_float(dome): 
        print("Not a number!")
        continue    

    dome = float(dome)

    if dome < 45:
        print("Please enter a value greater than 45!")
        continue

    break # everything OK, so we break out of the loop



tunnel_loop = 2

while tunnel_loop == 2:
    tunnel = input("Enter the length of your igloo's tunnel in cm: ")
    if not is_float(tunnel): 
        print("Not a number!")
        continue    

    tunnel = float(tunnel)

    if tunnel < 0:
        print("Please enter in a positive number!")
        continue

    break # everything OK, so we break out of the loop

The code defines generic helper function is_float. Once this test passes in the loops, you can start checking for any other conditions.

Upvotes: 0

Related Questions