Process multiple input values in Python

后端 未结 2 1485
轻奢々
轻奢々 2021-01-27 18:51

Hi so I\'m very very new to programming so please forgive me if I\'m not able to ask with the correct jargon, but I\'m writing a simple program for an assignment in which I\'m t

2条回答
  •  故里飘歌
    2021-01-27 19:02

    You can read in a comma-separated list of numbers from the user (with added whitespace possibly), then split it, strip the excessive white space, and loop over the resulting list, converting each value, putting it in a new list, and then finally outputting that list:

    raw = raw_input("Enter values: ")
    inputs = raw.split(",")
    results = []
    for i in inputs:
        num = float(i.strip())
        converted = num / 1e4
        results.append(converted)
    
    outputs = []
    for i in results:
        outputs.append(str(i))  # convert to string
    
    print "RESULT: " + ", ".join(outputs)
    

    Later, when you're more fluent in Python, you could make it nicer and more compact:

    inputs = [float(x.strip()) for x in raw_input("Enter values: ").split(",")]
    results = [x / 1e4 for x in inputs]
    print "RESULT: " + ", ".join(str(x) for x in results)
    

    or even go as far as (not recommended):

    print "RESULT: " + ", ".join(str(float(x.strip()) / 1e4) for x in raw_input("Enter values: ").split(","))
    

    If you want to keep doing that until the user enters nothing, wrap everything like this:

    while True:
        raw = raw_input("Enter values: ")
        if not raw:  # user input was empty
            break
        ...  # rest of the code
    

提交回复
热议问题