How to assign a numerical value to a user string input in Python

How to assign a numerical value to a user string input in Python

python input integer
how to assign a value to a variable in python
how to assign numbers to words in python
how to assign numeric value to text in python
replace string with integer python
python how to assign numbers to letters
python machine learning convert string to number
python variable in string

I have a school assignment, where it requests a number of user inputs determining whether the user wants milk, juice, its size For example, milk costs $4.00, upgrading to large costs $0.40,. At the end, the output should read for ex.

Large Milk,cost: $4.55

My issue is, how do I assign a value to each corresponding string input? At the end of the following code, the cost just spits out for sum of strings, as opposed to actually adding up the cost of each and spitting out the total number value. I just can't seem to figure out what I should be doing here.


In your final line to compute cost:

subtotal=(askSize + askBeverage + askFlav)

You do not sum the variables you defined at the top of your file (with costs), but you concatenate the strings that the user typed instead. For instance askSize can be the string "small". So, what you do here could be written as:

subtotal=("small" + "tee" + "lemon")

In Python, using + between strings will concatenate them. It means it will add the strings one after another to make a larger one. Example: "foo" + "bar" = "foobar".

If you want to refer to the cost of each option, one solution (but there are other ones) would be to use a dictionary to store costs instead of several variables as you did:

# Dictionary of costs
costs = {"tea": 1.50,
         "coffee": 1.50,
         "small": 0,
         "medium": 0.75,
         "large": 1.75,
         "mint": 0.50,
         "lemon": 0.25,
         "chocolate": 0.75,
         "vanilla": 0.25,
         "none": 0
         }

Then, to get the number corresponding to a string, you get items from the dictionary:

tea_cost = costs["tea"]  # tea_cost will be equal to 1.50
ask_size_cost = costs[askSize]  # ask_size_cost will be equal to the cost of the asked size

Now, it is easy to get your total cost:

total_cost = costs[askSize] + costs[askBeverage] + costs[askFlav]

Of course, take care of string cases, everything must be lowercase in my example.

Hope it helps !

NB: You can do many improvements to the rest of your code, do not hesitate to read some Python code on the internet to get it better.

String Tutorials & Notes | Python, How do you assign a value to a string in Python? Also, Other than user input If you want to check whether the Python variable is a number or string use isinstance() function. Python Program to only accept numbers as input. Let’s write a simple program to accept only number input from the user. The program will stop only when the user enters the number input.


You need a subtotal variable you never declared, and then after every option selection you want to += increment it:

subtotal = 0

askName = str(input("What is your name?")).title()
askBeverage = str(input("What type of beverage would you like?")).title()

if askBeverage.lower() in ("t", "tea"): #ensures any variation of upper/lowercase will work

    subtotal += 1.50

    askSize = str(input("Would you like a small, medium, or large Tea?")).title() # SIZE

    if askSize.lower() in ("small", "s"):
        subtotal += 0
    elif askSize.lower() in ('medium', 'm'):
        subtotal += .75
    elif askSize.lower() in ('large', 'l'):
        subtotal += 1.75
    else:
        print("Invalid size specified.")
        sys.exit()

    askFlav =str(input("Any flavourings for your Tea? Your options are mint, lemon, or none")).title() # FLAVOURING

    if askFlav.lower() in ("m", "mint"):
        subtotal += .50
    elif askFlav.lower() in ("l", "lemon"):
        subtotal += .25
    elif askFlav.lower() in ('none', 'n'):
        subtotal += 0
    else:
        print("Invalid flavour specified.")
        sys.exit()

Input and Output Tutorials & Notes | Python, How do you get integer input from user in Python? With a dict, the OP can further assign the same or different codes to the upper case values; special codes for punctuation; and can check for validity with if ch in ch2valuedict: instead of nasty old if ord('a') <= ch <= ord('z'): etc. Our Python has dicts, we should use them, and we should lead beginners to them when they are so appropriate.


Your askSize, askBeverage, askFlav are strings, so you cannot add them without turning into numbers. Most straight forward solution is to change them into float. subtotal=float(askSize) + float(askBeverage) + float(askFlav) print("For {}, a {} {}, with {:.2f} flavoring, cost: {}".format(askName,askSize,askBeverage,askFlav, subtotal)) It seems you just started learning programming. Python is a good language to start. Please enjoy!

Taking input from user : input, raw_input, math library in Python, by the specified separator and in case the separator is not provided then any white space is considered as a separator. Python user input from the keyboard can be read using the input() built-in function. The input from the user is read as a string and can be assigned to a variable. After entering the value from the keyboard, we have to press the “Enter” button. Then the input() function reads the value entered by the user.


Python Input, In this step-by-step Python tutorial, you'll learn how to take user input from the If you want a numeric type, then you need to convert the string to the You can also format values and assign them to another string variable:. LISTING 4.13 Assigning a Value to a Python Variable >>> coffee_cup = 'coffee' >>> print (coffee_cup) coffee >>> As you see in Listing 4.13, the print function can output the value of the variable without any quotation marks around it. You can take output a step further by putting a string and a variable together as two print function


Basic Input, Output, and String Formatting in Python – Real Python, Indentation and Comment in Python · Python | Set 2 (Variables, Expressions, While Python provides us with two inbuilt functions to read the input from the keyboard. Here, g is a variable which will get the string value, typed by user during the execution of program. We can use raw_input() to enter numeric data also. When one of the input() or raw_input() functions is called, the program flow stops until the user enters the input via the command line. To actually enter the data, the user needs to press the ENTER key after inputing their string.


Input, print and numbers - Learn Python 3, That is what the built-in function input does: First it prints the string you give as a In the hello_you.py program this value is assigned to the variable person, for use later. Without the prompt, the user would not know what was happening, and the '''Two numeric inputs, explicit sum''' x = int(input("Enter an integer: ")) y​  Learn how to take input from a user and system In Python. Display output on the console and write it to file. Accept an integer, float, character and string input from a user. Convert the user input to a different data type. Do a fancier Output Formatting.