'How can i resolve loops issues code in ppython
Hi everyone i'm new here, and i i'm learning python too for my university, i'm stuck on this problem, i have to create a list of week days and put the values ad miles then i have to do the total and count the cost of the petrol but i need to insert loops and tell to the program is the value is less then 0 to go back and insert the value again. This is my problem, if someone can help me i will be happy. thanks.
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)
Solution 1:[1]
By creating a function, you can simply add a while that will retry while the condition is not met.
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)
EDIT: by suggestion of @aneroid using dict comprehension on a list of days simplifies the code:
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)
Solution 2:[2]
how are you doing, i am also newcomer in python learning, so i think that's the solution:
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
