如何制作座位'在作为float返回的用户输入中

时间:2016-05-25 02:39:38

标签: python

所以在我的短python程序中,我写道:

print "Welcome to the Receipt Program!"
while True: 
    seat = raw_input('Enter the value for the seat: ["q to quit"] ')
    if seat is not seat.isdigit():
        print "I'm sorry but {} isn't valid. Please try again.".format(seat)
    if seat == 'q':
        break
    else:
        continue

print "*****"
total = seat.count('$')
print total

如何设置,每当用户为座位输入一个号码(专门用于浮动)(目前在我的代码段中不可用)时,它会继续使用代码,然后将所有用户输入相加? 我是初学者,如果这是一个明显的答案,那么道歉。

3 个答案:

答案 0 :(得分:1)

print "Welcome to the Receipt Program!"
seats = []
while True: 
    seat = raw_input('Enter the value for the seat: ["q to quit"] ')
    if seat == 'q':
        break
    try:
        seats.append(float(seat))
    except ValueError:
        print "I'm sorry but {} isn't valid. Please try again.".format(seat)

print "*****"
print '$', sum(seats)

请注意,检查输入值的顺序也很重要(在尝试将其转换为浮点数之前先检查'q'

答案 1 :(得分:0)

你总是可以做一个try / catch语句。这是一个例子。

clang++ -O3 -std=c++11 -fopenmp=libiomp5 test_omp.cpp

在你的情况下,你希望它是这样的:

try:
   numFloat = float(element)
except ValueError:
    print "Not a float"

尝试float函数时要记住的重要一点是将新值赋给变量。它不会改变原来的那个。

有关Try / Catches的更多信息,请查看此处 - 8.3 Handling Exceptions

答案 2 :(得分:0)

那么,你想从用户那里获得多个输入(在Python 2.7中),每个输入都是一个浮点数,然后将它们加起来?

您已经意识到raw_input始终返回一个字符串。为了将该字符串转换为浮点数,您需要应用" float"对输入。问题是,如果你使用str.isdigit来确定你是否有一个数字,那么每次数字都有一个小数点时它就会失败......这在处理浮点数时非常有用。

因此,我认为,最好的选择是抓住一个适当的例外。如果在调用float()时遇到ValueError,则表明存在问题。

这是一个可能的解决方案:

String