我是一名明天有评估的学生,我的练习代码如下:
'''A local technology company has various options for buying cell phones on credit:
• Pay off monthly over six month with no interest
• Pay off monthly over 12 months with 5% interest on the money owing after 6 months and up to 12 months
They have asked you to design and create a program that they can use to work out the various values depending on the customer’s requirements and initial sales price. The initial sales price includes GST. As output, they want the name of the person displayed, sales price, interest to be paid, the term of repayment and the amount they will be paying each month.
The program needs to run continuously until a rogue value Q is entered. You are expected to design and implement a user-friendly approach. Also make sure the program is robust enough to survive any random values entered. Use test data that will cover all possible combinations.
Created By: William
Date: 26th June 2016'''
#Get users name and trap false inputs
name = input("What is your name? ")
while name.isnumeric() or name == "":
print("That isn't a valid option. Please enter an alphabetical name.")
name = input("What is your name? ")
#get sales price and trap false inputs
sales_price = float(input("How much does your phone cost? $"))
while sales_price.isnumeric() or sales_price == "":
print("That isn't a number! Please enter a value above $0")
sales_price = float(input("How much does your phone cost? $"))
print(name, sales_price)
我的问题,正如在说明中所说,我如何在销售价格中记录诸如字母或负值之类的输入? 感谢任何帮助。
答案 0 :(得分:1)
当float()
给出一个无法转换为浮点数的字符串时,你应该利用ValueError
引发while
的事实。
在下面的代码中,只要用户输入一个不能转换为浮点数的负数或字符串,就会重复valid_input = False
while not valid_input:
try:
sales_price = float(input("How much does your phone cost? $"))
if sales_price < 0:
raise ValueError
except ValueError:
pass
else:
valid_input = True
循环。
P
答案 1 :(得分:1)
我建议像这样使用try-except
块:
correct_number = False
while correct_number == False:
try:
x = abs(float(input('>> Enter float number ')))
correct_number = True
except ValueError:
print('not correct input')
print(x)