Evaluation of PYTHON code

Evaluation of PYTHON code
0

#1
import re
cone_type = {'Plain Cone':1.5,
             'Waffle Cone':2,
             'Cup':1}

Scoop_Flavours = ['Vanilla', 'Strawberry', 'Chocolate', 'Caramel', 'Mint', 'Rainbow', 'Coffee', 'Bubble gum']
Topping_Choices = {'Peanuts':0.75,
                   'Caramel Sauce':0.5,
                   'Rainbow Sprinkles':0.5,
                   'Pecan':1,
                   'Chocolate Sprinkles':0.5}

#To check Inout value is only alphabets
def ValidateString(inputString):
    if not re.match("^[a-zA-Z ]*$", inputString):
        return False
    else:
        return True

#Function to get customer Name
def getCustName(): 
    #Get the customer Name
    name = input("Enter the customer Name: ")
    #check If its only of alphabets.If Not Asks the user to Enter the customer Name until its valid
    if not ValidateString(name):
        print("Name should consist of letters only")
        getCustName()
    return name

#Function to Get No of ICe Cream
def getNoOfIceCreams():
    count = 0
    while True:
        #Get the No of IceCreams from customer and Enter it
        NoOfIceCreams = input("Enter the No of IceCreams:")
        try:
            #Validate If its only Integer.
            count = int(NoOfIceCreams)
        #If Not Asks the user to Enter the value until its valid Integer
        except ValueError:
            print("%s is not an integer.\n" % NoOfIceCreams)
            continue
        #Validate If the value is not less than 1.
        if count < 1:
            print("Enter a valid number")
            continue
        else:
            break
    return count


#Function To Get the Cone Type
def getConeType():
    while True:
        #Get the cone type from customer and Enter it
        cone = input("Enter the preferred cone Type:")
        #Validate the value is only Alphabets.If Not Asks the user to Enter the value until its valid
        if not ValidateString(cone):
            print("Cone Type is not valid")
            continue
        else:
            #Validate the Value Entered is in the Menu
            check = None
            for ct in cone_type:
                if len(cone) != 0:         
                    if (ct.lower() == cone.lower()):
                        check = True
                        return ct
                        break
                else:
                    check = False
            #If the Value is not in the Menu Ask the user to Enter the value until its valid
            if not check:
                print("Please Choose the cone Type available in the Menu")
                continue
        
#Function To Get the flavor
def getFlavour():  
    while True:
    #Get the flavor from customer and Enter it
        flavourtype = input("Enter the preferred flavor:")
        #Validate the value is only Alphabets.If Not Asks the user to Enter the value until its valid.
        if not ValidateString(flavourtype):
            print("Flavor Type is not valid")
            continue
        else:
            #Validate the Value Entered is in the Menu
            check = None
            for ft in Scoop_Flavours:
                if ft.lower() == flavourtype.lower():
                    check = True
                    flavourtype=ft
                    return flavourtype
                    break
                else:
                    check = False
            #If the Value is not in the Menu Ask the user to Enter the value until its valid
            if not check:
                print("Please Choose the flavour  available in the Menu")
                continue
    

#Function To Get the Scoop Count
def getScoopCount():  
    count = 0
    while True:
        #Get the Scoop count from customer and Enter it
        scoopcount = input("Enter the No Of Scoop(The max no.of scoops per ice cream is 3):")
        #Validate the value is only Integre.If Not Asks the user to Enter the value until its valid.
        try:
            count = int(scoopcount)
        except ValueError:
            print("%s is not an integer.\n" % scoopcount)
            continue
        #Validate the value is less than 3.If Not Asks the user to Enter the value until its valid.
        if count < 1 or count > 3:
            print("Scoop Count should be less between 1 and 3")
            continue
        else:
            break
    return count

#Function To Get the list of topping
def getToppings():
    topppingList = []
    topppingList = input("Enter List of Toppings, SEPERATED by Comma:")
    #split the Comma separated Input and make it is a list 
    topppingList = topppingList.split(",")
    toBeRemoved = []
    while True:    
        #Check the only 4 Toppings are choose. IF not remove the Excess Toppings     
        if len(topppingList) > 4:
                print("MAximum Topping Allowed is 4")
                remove_top = input("Enter the Toping to remove:")
                topppingList.remove(remove_top)
                
        if len(topppingList) <= 4:
            toping = 0
            for i,toping in enumerate(topppingList):
                #check all the topping are only alphabet. else add it to the List of topings to be removed finally           
                if not ValidateString(toping):
                    toBeRemoved.append(toping)              
                else:
                    #check all the topping are in menu.
                    check = None
                    for tc in Topping_Choices:
                        if tc.lower() == toping.lower():
                            check = True
                            topppingList[i]=tc
                            break
                        else:
                            check = False
                    #Add the Toppings not in the menu to the List of toppings to be removed finally
                    if not check:
                        toBeRemoved.append(toping)
            if len(toBeRemoved) == 0:
                break
            else:
                print("Topings", toBeRemoved, "is not Valid or not in the Menu")
                #Ask the customer for the new value from menu and add the toppings list
                new_topings = input("Please enter Toping from the Menu:")
                new_topings = new_topings.split(",")
                #Remove the invlaid toppings from the List
                for delToping in toBeRemoved:
                    topppingList.remove(delToping)
                topppingList = topppingList + new_topings
                del toBeRemoved[:]
                continue
    print("Toppings:",topppingList)
    return topppingList
    

#Function To Print the Items in the Menu
def printmenu():
    print(20 * "*", "ICE CREAM MENU",20 *"*")
    print(20 * " ", 15 * "*")
    print("CONE TYPE")
    print("---------")
    for ct in cone_type:
        print(ct, " - ", "$", cone_type[ct])
    print("---------")
    print("Scoop Flavours(Each scoop $5)")
    print("--------------")
    for sf  in Scoop_Flavours:
        print(sf)
    print("--------------")
    print("Topping Choices")
    print("--------------")
    for tc  in Topping_Choices:
        print(tc, " - ", "$", Topping_Choices[tc])
    print("--------------")
    print(20 * "*", "END OF MENU",22*"*",'\n','\n')

# Main Function
printmenu()
Customer_Name = getCustName()
No_Of_Ice_Creams = getNoOfIceCreams()
orderList = []
totalPrice = 0
for i in range(1, No_Of_Ice_Creams + 1):
    print("Ice Cream:", i)
    print("---------:")
    conetype = getConeType()
    coneprice = cone_type[conetype]
    flavour = getFlavour()
    scoopcount = getScoopCount()
    scoopprice = scoopcount * 5
    toppings = getToppings()
    toppingprice = 0
    for n in toppings:
        toppingprice = toppingprice + Topping_Choices[n]
    #Calculate Amount for Each Cream 
    price_per_iceCream = coneprice + scoopprice + toppingprice
    orderList.append([conetype, flavour, scoopcount, '/'.join(toppings), price_per_iceCream])
    #Calculate the Total Amount
    totalPrice = totalPrice + price_per_iceCream
    #print(orderList)


print(20 * " ", "FINAL BILL")
print("CUSTOMER NAME:", Customer_Name)
print("NO OF ICE CREAMS ORDERED:", No_Of_Ice_Creams)
print("SI.NO",5*" ", "ICE CREAM DETAIL",65*" "+"PRICE")
print(5*"-",5*" ",24*"-",56*" ",5*"-")
for j in range(0, len(orderList)):
    ice_cream_detail = ("Ice Cream " + str((j+1)) + ":" + '\n' +16*" "+ "Cone Type:" + orderList[j][0] + '\n' +16*" "+ 
                        "flavor:" + orderList[j][1] + '\n' +16*" "+"No.of Scoop:" + str(orderList[j][2]) + '\n' + 
                        16*" "+"Toppings:" + orderList[j][3] + 20*" " +"$"+str(orderList[j][4]) )
    print(j+1, "         ", ice_cream_detail, "    ")
print('\n',"Total Amount :"," $", totalPrice)

so can u guys help me to make it shorter.


#2

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


#3

You don’t really need all of those comments. Comments should only explain why you do something and not what a particular section of code does.

Plus, you have asked how to make this shorter without explaining what you expect your code to do.


#4

I think you spent a lot of time on this. Perhaps the if then statements can be simplified but can you let us know what is the issues?

Is length part of the grade?


#5

No sir, length doesn’t matter. I want this code to be written in less lines. Is there any way we can do it?


#6

This code is for creating an ordering system for a ice cream shop, where it should handle the possible errors of incorrect data entered. We were given a table where the prices were provided for each cone type and toppings.


#7

Not bad IMO. Too many people worry on shortening up the code when it cannot be shortened up further. Maybe you could remove those if-else statements in the middle, and you certainly need to clean up those comments; they’re making your script unnecessarily long. Lastly, it would be nice to use some more spaces between commands, it will make your code look cleaner, easier to read and hurt the eyes less.