python中的输入多个数据_在Python中处理多个输入值

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 to convert CGS units to SI units

For example:

if num == "1": #Gauss --> Tesla

A=float(raw_input ("Enter value: "))

print "=", A/(1e4), "T"

with this I'm only able to convert one value at a time. Is there a way I can input multiple values, perhaps separated by commas and perform the calculation on all of them simultaneously and spit out another list with the converted values?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值