大家好,我是这里新来的,我也在为我的大学学习python,我被困在这个问题上,我必须创建一个星期的日子列表,把每周的天数和英里数,然后我必须做总数和计算汽油的费用,但我需要插入循环并告诉程序是值小于0返回并再次插入值。这是我的问题,如果有人能帮我,我会很高兴的。谢谢。
myDay = day1, day2, day3, day4, day5, day6, day7
day1 = int(input("Enter miles for Monday:"))
day2 = int(input("Enter miles for Tuesday:"))
day3 = int(input("Enter miles for Wednesday:"))
day4 = int(input("Enter miles for Thursday:"))
day5 = int(input("Enter miles for Friday:"))
day6 = int(input("Enter miles for Saturday:"))
day7 = int(input("Enter miles for Sunday:"))
if myDay <= 0:
print("that number is wrong, select a number superior then 0")
myDay = int(input("Try again"))
total = day1 + day2 + day3 + day4 + day5 + day6 + day7
print("The total mileage is", total)
print("Cost of petrol", total * 1.35 / 11.2)发布于 2022-04-12 10:58:49
通过创建一个函数,您可以简单地添加一个会在不满足条件时重试的时间。
def new_day(day_name):
day = 0
first = True
while day <= 0:
if first:
first = False
else:
print("that number is wrong, select a number superior then 0")
day = int(input(f"Enter miles for {day_name}:"))
return day
day1 = new_day("Monday")
day2 = new_day("Tuesday:")
day3 = new_day("Wednesday:")
day4 = new_day("Thursday:")
day5 = new_day("Friday:")
day6 = new_day("Saturday:")
day7 = new_day("Sunday:")
total = day1 + day2 + day3 + day4 + day5 + day6 + day7
print("The total mileage is", total)
print("Cost of petrol", total * 1.35 / 11.2)编辑:通过建议@aneroid使用dict理解一串日子,简化了代码:
def new_day(day_name):
day = 0
first = True
while day <= 0:
if first:
first = False
else:
print("that number is wrong, select a number superior then 0")
day = int(input(f"Enter miles for {day_name}:"))
return day
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
day_miles = {day: new_day(day) for day in days}
total = sum(day_miles.values())
print("The total mileage is", total)
print("Cost of petrol", total * 1.35 / 11.2)发布于 2022-04-12 10:58:43
你好,我也是蟒蛇学习方面的新手,所以我认为这就是解决办法:
day1=int(input('Enter miles:'))
day2=int(input('Enter miles:'))
weekday=[day1, day2]
for i in weekday:
if i<=0:
print('that number is wrong, type another one:')
i=int(input('write:'))
weekday.append(i)
total=sum(weekday)
print(total)
print(total*1.35/11.2)https://stackoverflow.com/questions/71841150
复制相似问题