def calcwages(totalWages, totalHours):
weeklyWages = totalWages * totalHours
return weeklyWages
def main():
hours = input("Enter how many hours you work")
wage = 7.50
total = calcwages(wage, hours)
print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.'
.format(**locals()))
main()
我想这样做,以便如果用户输入一个字符串四个小时,该程序将让用户知道在再次运行它时不是可接受的响应。我尝试使用while循环,但我遇到了检查字符串问题的麻烦。
答案 0 :(得分:0)
您可以在while循环内使用try except
块控制流量
当条目正确时,循环将退出;但是,当条目包含字符时,它将打印一条消息,并要求输入一个新条目,直到提出正确的条目:
def calcwages(totalWages, totalHours):
weeklyWages = totalWages * totalHours
return weeklyWages
def main():
while True:
hours = input("Enter how many hours you work")
try:
hours = float(hours)
break
except ValueError:
print("pls enter a number")
wage = 7.50
total = calcwages(wage, hours)
print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.'.format(**locals()))
main()
答案 1 :(得分:0)
Python提供了isdigit()函数,用于检查给定字符串是否只有数字。 您可以按如下方式使用它。
def main():
while True:
hours = input("Enter how many hours you work: ")
if hours.isdigit():
break
print('Please only use numbers.')
# ...
请注意,十进制数字不会使用此方法。
答案 2 :(得分:0)
使用isdigit()
- 如果字符串仅包含数字,则返回true,否则返回
def calcwages(totalWages, totalHours):
return totalWages * totalHours
def main():
hours = input("Enter how many hours you work")
while hours.isdigit() == False :
hours = input("Enter digits only")
wage = 7.50
total = calcwages(wage, hours)
print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.' .format(**locals()))
main()
答案 3 :(得分:0)
您可以使用isdigit()
查看,但默认isdigit()
方法仅适用于int而非浮动,因此您可以定义自己的isdigit()
,这对两者都有效:
def isdigit(d):
try:
float(d)
return True
except ValueError:
return False
然后你可以这样做:
def calcwages(totalWages, totalHours):
weeklyWages = totalWages * totalHours
return weeklyWages
def main():
hours = input("Enter how many hours you work ")
if isdigit(hours):
hours = float(hours)
wage = 7.50
total = calcwages(wage, hours)
print('Wages for {hours} hours at ${wage:.2f} per hour are ${total:.2f}.'.format(**locals()))
else:
print("please enter numbers only")
return main()
return total
main()
输出:
Enter how many hours you work three
please enter numbers only
Enter how many hours you work four
please enter numbers only
Enter how many hours you work 3.4
Wages for 3.4 hours at $7.50 per hour are $25.50.