My life calculater project - python

I'm currently working on a life calculator that i have programmed in python. I need ideas of what to add to it and examples on how to add it and also how do i add a end control so i can just input end and the program stops. I'm trying to make this better because i plan to take it to a technology fair im going to. Here is my code.
print("The Life Calculator")
name = input("What is you're name? ")
age = int(input("age: "))
months = age * 12 #This equals to how many months you have been alive.
days = age * 365 #This equals to how many days you have been alive.
hours = age * 8765.81 #This equals to how many hours you have been alive.
minutes = age * 31556926 #This equals to how many minutes you have been alive.
seconds = age * 3.156e+7 #This equals to how many seconds you have been alive.
miliseconds = age * 3.15569e10 #This equals to how many miliseconds you have been alive.
microseconds = age * 3.156e+13 #This equals to how many microseconds you have been alive.
nanoseconds = age * 3.156e+16 #This equals to how many nanoseconds you have been alive.
print("This is how many months you have been alive.")
print (months) #This shows how many months you have been alive.
print("This is how many days you have been alive.")
print (days) #This shows how many months you have been alive.
print("This is how many hours you have been alive.")
print (hours) #This shows how many hours you have been alive.
print("This is how many minutes you have been alive.")
print (minutes) #This shows how many minutes you have been alive.
print("This is how many seconds you have been alive.")
print (seconds) #This shows how many seconds you have been alive.
print("This is how many miliseconds you have been alive.")
print (miliseconds) #This shows how many miliseconds you have been alive.
print("This is how many microseconds you have been alive.")
print (microseconds) #This shows how many microseconds you have been alive.
print("This is how many nanoseconds you have been alive.")
print (nanoseconds) #This shows how many nanoseconds you have been alive.
lastline = ("this is how long you have been alive, so what are you going to do with the rest of your life?")
print (name)
print (lastline)

Here is a spiffed-up version.
I took a lot of the repetitive statements and converted them to data:
from collections import namedtuple
TimeUnit = namedtuple("TimeUnit", ["name", "per_year"])
units = [
TimeUnit("decade", 0.1 ),
TimeUnit("month", 12.0 ),
TimeUnit("fortnight", 26.09),
TimeUnit("day", 365.25),
TimeUnit("hour", 8765.81),
TimeUnit("minute", 31556926),
TimeUnit("second", 3.156e+7),
TimeUnit("millisecond", 3.15569e10)
]
def get_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
pass
def main():
print("The Life Calculator")
name = input("What is your name? ")
years = get_float("What is your age? ")
print("You have been alive for:")
for unit in units:
print(" {} {}s".format(years * unit.per_year, unit.name))
print("what are you going to do with the rest of your life, {}?".format(name))
if __name__ == "__main__":
main()

Your program is running once, not multiple times so actually you don't have to ask to user for end. However, if you want to run your program until user types end, you have to put that codes in a while loop.
If you want to stop running your program when user types end, just add this line to your program;
while True:
#your codes here
#end of your codes add this line
ask=input("Want to end it?")
if ask.lower()=="end":
break
Using lower() so even user types END or eND or EnD etc. it will be ok.

Related

why it doesn't output the product from the if loop

Everything works but it doesn't produce the workout and keep asking me to input the skill from the list. I want to ask the user to input the skill, output the workout and keep asking them to put another skill. Otherwise input stop to break out the loop.
skill4 = ['defense', 'finishing', 'athleticism', 'posting']
print('Focus on: \nDefense \nPosting \nAthleticism \nFinishing')
skill4 = str.lower(input('Select 1 skill you want to improve on the list: '))
while True:
if work != skill4:
skill4 = str.lower(input('Please select 1 skill from above: '))
if work == skill4[0]:
print (' \nYour exercises are: ')
print('Lateral training 40 seconds \nShuffle on a line 40 seconds \nladder training: 40 seconds')
if work == skill4[1]:
print (' \nYour exercises are: ')
print('Side hook: 10 makes (per side)\nScoop: 10 makes (per side)\nFloater: 10 makes (per side)')
if work == skill4[2]:
print (' \nYour exercises are: ')
print('Run 7 miles per hour for 30 minutes (break each 15)\nJump squat: 40 seconds\nRope skipping: 1 min 30 sec')
if work == skill4[3]:
print (' \nYour exercises are: ')
print('Up and under move (15 times)\nKobe fadeaway move (15 times)\nCut to short corner, receive pass from wing and shoot. (10 times) ')
if work == "stop":
break
else: skill4 = str.lower(input('Select another skill: '))
on this line
skill4 = str.lower(input('Select 1 skill you want to improve on the list: '))
you are setting the variable skill4, thus overwriting your list of skills. Because the work variable stays undefined, you will not be able to compare it later.
You also have an indentation problem. The if statements are nested. Because of that, you only check if work == skill4[1] when work == skill4[0], which can never be true.
The last problem I see is not very noticable but very annoying: in this line
if work != skill4:
You check if the item selected is a valid work item, but you compare it to the list instead of checking if it is in the list. You would do that this way:
if work not in skill4:
I hope this helps you!

How to show my destination by adding the time(24 hour) to the time left?

So I have to make a program for class that lets the user input the time (hour and minute part), how many miles are left, and their miles/hour then it has to output the current time 00:00, travel time remaining _ hours and _ minutes left, then what time they will reach destination 00:00
We can only use input, int, round, str, format in our program. So far I have
print("Welcome to the travel advisor program.")
hour = int(input("Enter current time, the hours part, using a 24-hour format: "))
num = int(input("Enter current time, the minutes part: "))
minute =format(num, "02d")
miles = int(input("Enter distance to destination in miles: "))
mph = int(input("Enter speed in miles/hour: "))
time_travel_hour = (miles // mph)
time_t = (miles / mph)
travel_time_minute = round((time_t - time_travel_hour) * 60)
clock_format = str(time_travel_hour) + str(":") + str(travel_time_minute)
current = str(hour) + str(":") + str(minute)
print("\n")
print("Here is your trip report")
print("Current time is " + str(current))
print("Distance to destination is " + str(miles) + " miles")
print("Travel speed is " + str(mph) + " miles/hour")
print("Travel time remaining:", time_travel_hour, " hours and", travel_time_minute, "minutes")
I tried making adding hour and travel_time hour together and it worked, but when I add num (minute) and travel_time_minute together it just keeps going past 60 so it doesnt go into the hour.
Generally, when solving problems like this it's much easier to think in terms of one unit. When dealing with time, that single unit is often seconds, but for this case, it can just as easily be minutes. Once you have the input from the user, if all of the problems you need to solve are done in terms of minutes, the math is straightforward enough. From there it's just a matter of presentation. It's easy for a computer to think of "120 minutes", but when displaying it to a user, they would expect to see "2 hours, 0 minutes"
# Replacing the input calls here with direct input so the results are
# easily reproducible, it makes discussion about the problem easier on Stack Overflow
print("Welcome to the travel advisor program.")
hour = 12 # int(input("Enter current time, the hours part, using a 24-hour format: "))
mins = 34 # int(input("Enter current time, the minutes part: "))
miles = 150 # int(input("Enter distance to destination in miles: "))
mph = 60 # int(input("Enter speed in miles/hour: "))
# Time in minutes, this makes some of the calculations easier
travel_time = round(miles / mph * 60)
print("\n")
print("Here is your trip report")
# Show what the user input
print(f"Current time: {hour}:{mins:02d}")
print(f"Distance to destination is {miles} miles")
print(f"Travel speed is {mph} miles/hour")
# Show the travel time. travel_time is in minutes, but present it to the user
# in terms of hours and minutes
# 'travel_time // 60' divides the current time by 60, and drops the fractional part
# 'travel_time % 60' uses the modulo operator, meaning we return the remainder from the division
print(f"Travel time remaining: {travel_time // 60} hours and {travel_time % 60} minutes")
# Outputs: Travel time remaining: 2 hours and 30 minutes
# And calculate the eta, use the same logic as the travel_time, which
# means thinking in number of minutes since the start of the day
# The '% 24' here lets us "loop" around in case the eta goes beyond the
# 24 hours in a day. This is just to present the user a valid "wall clock" time,
# and may or may not be desired.
eta = hour * 60 + mins + travel_time
print(f"ETA is {(eta // 60) % 24}:{eta % 60:02d}")
# Outputs: ETA is 15:04

How to create a payrate calculator for different payrates within each day?

I have a table of how many hours each employee worked for a week. They can start and end at any time of the day, including overnight shifts. But for each time period, there is a different payrate. For example, from 5am-5pm Mon-Fri is $20/h. But 5pm-11:59pm Fri is $21/h. Sat and Sun full day is $23/h, and Monday 00:00am to 5am is again $20.
Say a worker starts 4pm Fri and ends 2am Sat, so the calculation comes (1 * 20) + (7 * 21) + (2 * 23). Doing these types of calculations for half a dozen workers across the whole week is time consuming and prone to making mistakes.
Instead of doing this manually, how can I write a program to take inputs of the day, start and end time and then calculate what the pay should be?
Not necessarily looking for code (although that would be helpful), but a way to break this down into a way that can be coded.
payrates = {'p1':20, 'p2': 21, 'p3':23, 'p4':20}
#p1 = 5am-5pm Mon-Fri
#p2 = 5pm-11:59pm Fri
#p3 = Sat and Sun full day is $23/h
#p4 = Monday 00:00am to 5am
name = input("Please Enter Staff's Name: ")
stop = ''
totalpay=0
while True:
wrate = input('Enter payrate type: ')
hours = input('No of Hours worked: ')
pay = payrates[wrate] * int(hours)
totalpay += pay
print(f'Subtotal = {totalpay}')
stop = input('Press Enter to continue or type "stop" to finish: ')
if stop == 'stop':
break
else:
continue
print(f'Total pay for {name} is {totalpay}')
Here, I've simply created a dictionary that stores that various pay rates(p1,p2,p3,p4), then with a while loop, i can input the payrate and number of hours worked. Within the loop, I get the total pay calculated, and generate the final value.
This is a basic illustration, in a situation where you have many workers, you can have a dictionary hold all work details of each worker(something like {'victor':{'p1':7, p2:2, p3:1}, 'david': {'p1':8, 'p2':1, 'p3':3},...}, in which case you can run an iteration through the workers dictionary to generate their respective total pay. You may use pandas if your records are much.

How to display a message when a prompted input isn't entered?

I'm getting back into programming, so I started a project that rolls a die based on the amount of side's a user inputs, and the amount of times the user wants the die to be rolled. I'm having trouble with a part of the program involving time. When the user doesn't input within ten seconds of being prompted, I want a message to be displayed. If nothing is entered in another ten seconds a message should be displayed, so on and so forth. I'm using python.
Right now most of the program is working, but time is only checked after an input is taken. Thus a user could sit on the input screen infinitely and not get prompted. I'm really stuck on how to simultaneously wait for an input, while checking the amount of time elapsed since being prompted for the input.
def roll(x, y):
rvalues = []
while(y > 0):
y -= 1
rvalues.append(random.randint(1, x))
return rvalues
def waitingInput():
# used to track the time it takes for user to input
start = time.time()
sides = int(input("How many sides does the die have? "))
times = int(input("How many times should the die be rolled? "))
tElapsed = time.time() - start
if tElapsed <= 10:
tElapsed = time.time() - start
rInfo = roll(sides, times)
print("Each side occurs the following number of times:")
print(Counter(rInfo))
waitingInput()
else:
print("I'm waiting...")
waitingInput()
Any advice would be appreciated. I'm looking to improve my coding any way I can, so constructive criticism about unrelated code is welcome.
Situations like this call for a threaded timer class. The python standard library provides one:
import threading
...
def waitingInput():
# create and start the timer before asking for user input
timer = threading.Timer(10, print, ("I'm waiting...",))
timer.start()
sides = int(input("How many sides does the die have? "))
times = int(input("How many times should the die be rolled? "))
# once the user has provided input, stop the timer
timer.cancel()
rInfo = roll(sides, times)
print("Each side occurs the following number of times:")
print(Counter(rInfo))

Using python to track and constantly update days left of school

I'm trying to create a program that asks if there was school that day and if so, subtracts that from the total, (86 days left as of 1-22-18). It works, but the program ends after one subtraction, so my question is, is there any way for it to continue running and update itself, or maybe ask the user again in 24 hours (no clue how)?
Python 3.4.4
Windows 10
import time
localtime = time.asctime(time.localtime(time.time()))
day = localtime[0:3]
check = 0
daysLeft = 87 #As of 1-22-18
daysOfTheWeek = ["Mon", "Tue", "Wed", "Thu", "Fri"]
yesPossibilities = ["yes", "y", "yeah"]
print ("Did you have school today?")
schoolToday = input().lower()
if schoolToday in yesPossibilities:
if day in daysOfTheWeek:
daysLeft -= 1
print ("There are", daysLeft, "days of school left!")
I think what you're really trying to do is save the results each time you run your script (Ex: If you run it today, it tells you there are 86 days left, if you run it tomorrow, it tells you there are 85 days left, etc). You probably don't want to run the script forever because if you turn your computer off, the script is terminated, which means you'll lose all of your results. I would save the output to a text file in the following manner:
print("There are" daysLeft, "days of school left!")
with open("EnterNameOfFileHere.txt",'w') as f:
print(daysLeft,file=f)
This will save the daysLeft variable in a text file, which you can access at the start of your program in the following manner:
check = 0
with open("EnterNameOfFileHere.txt") as f:
daysLeft = int(f.readline().strip())
daysOfTheWeek = ....
In summary, implementing this will allow you to save your results each time you run your script so that you can start from that value the next time you run the script.
You need an infinite loop and a sleep timer
import time
time.sleep(86400) #this will make the code sleep for 1 day = 86400 seconds
Next, put the sleep into the infinite loop
while True:
#get input
if input meets condition:
reduce day count by 1
print number of days left
time.sleep(86400)
if days left meets some threshold:
print "school over"
break

Categories

Resources