首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何解决ppython中的循环问题

如何解决ppython中的循环问题
EN

Stack Overflow用户
提问于 2022-04-12 10:35:20
回答 2查看 43关注 0票数 1

大家好,我是这里新来的,我也在为我的大学学习python,我被困在这个问题上,我必须创建一个星期的日子列表,把每周的天数和英里数,然后我必须做总数和计算汽油的费用,但我需要插入循环并告诉程序是值小于0返回并再次插入值。这是我的问题,如果有人能帮我,我会很高兴的。谢谢。

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

发布于 2022-04-12 10:58:49

通过创建一个函数,您可以简单地添加一个会在不满足条件时重试的时间。

代码语言:javascript
复制
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理解一串日子,简化了代码:

代码语言:javascript
复制
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)
票数 2
EN

Stack Overflow用户

发布于 2022-04-12 10:58:43

你好,我也是蟒蛇学习方面的新手,所以我认为这就是解决办法:

代码语言:javascript
复制
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)
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71841150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档