I am a young student, and I'm wanting to learn coding. However, my if function is causing an issue and I'm not sure as to why. I'm sorry if anything is hard to understand or if my code is over-complicated; I'm not sure how to make it quicker.
As one of my first experiences with coding, I tried to create a basic bit of code, saying how old the user is in years, months, and days, based on their inputs. This had worked, however, if I input the month as 2, while the current month as 1, it would become a negative number. To try and stop this, I added an "if" function. This isn't working and I'm not sure as to why.
from time import localtime
year = localtime().tm_year
month = localtime().tm_mon
day = localtime().tm_mday
print("What day, month, and year were you born?")
day_input = int(input())
month_input = int(input())
year_input = int(input())
year_output = year - year_input
month_output = month - month_input
day_output = day - day_input
if month_input>month and month == "1" or month_input>month and month == "3" or month_input>month and month == "5" or month_input>month and month == "7" or month_input>month and month == "8" or month_input>month and month == "10" or month_input>month and month == "12":
month_output = 12-month
day_output = 31-1
year_output = year-year_input-1
if month_input>month and month == "2":
month_output = 12-month
day_output = 28-1
year_output = year-year_input-1
if month_input>month and month == "4" or month_input>month and month == "6" or month_input>month and month == "9" or month_input>month and month == "11":
month_output = 12-month
day_output = 30-1
year_output = year-year_input-1
print("You are", year_output, "years,", month_output, "months, and", day_output, "days old!")
As the user 0x5453 had said, the variable comparation needed to be between int variables and not strings. So if you just change the if lines to:
if month_input>month and month == 1 or month_input>month and month == 3 or month_input>month and month == 5 or month_input>month and month == 7 or month_input>month and month == 8 or month_input>month and month == 10 or month_input>month and month == 12:
if month_input>month and month == 2:
if month_input>month and month == 4 or month_input>month and month == 6 or month_input>month and month == 9 or month_input>month and month == 11:
The calculation will be fine.
As others users had cited, your code isn't optimized, but, it isn't your question focus. I suggest follow the hints given.
hi the problem is that at the first, second and third lines the program thinks that localtime is a variable.
Related
Transform the ERL for one or more selection statements to decide whether a year is a Leap year.
The rules are:
A year is generally a Leap Year if it is divisible by 4, except that if the year is divisible by 100, it is not a Leap year, unless it is also divisible by 400.
Thus 1900 was not a Leap Year, but 2000 was a Leap year.
year = int(input ("What year would you like to assess? "))
leapYear = False #Setting a flag which will be assessed at the end
#the if statements are checking to see if the conditions #are true to assess it as a leap year
if year mod 4 == 0 then
leapYear = True
endif
if year mod 100 == 0 then
leapYear = False
end if
if year mod 400 == 0 then
leapYear = True
end if
if leapYear == True then
print("This is a leap year")
else
print("This is not a leap year")
end if
hrs = int(input("How many hours do you want? "))
if hrs >= 24:
day = hrs/24
hrs = hrs
if day == 1:
print(hrs, "hours is equal to", day, "day")
else:
if day >= 7:
wks = day / 7
if wks == 1:
print(day, "days is equal to", wks, "week")
else:
if wks >= 4:
mon = wks / 4
if mon == 1:
print(wks, "weeks is equal to", mon, "month")
else:
if hrs == 1:
print("You have 1 hour")
else:
print("You have", hrs, "hours")
For some reason when I try and use a number greater than 24 in hrs = int(input("How many hours would you like? ")) it stops completely not giving me what the problem is.
Here is what is shown in the console
I am using VisualStudio Code to make this
try using Floor division // instaed of normal devision /
hrs = int(input("How many hours do you want? "))
if hrs >= 24:
day = hrs//24
hrs = hrs
if day == 1:
print(hrs, "hours is equal to", day, "day")
else:
if day >= 7:
wks = day // 7
if wks == 1:
print(day, "days is equal to", wks, "week")
else:
if wks >= 4:
mon = wks // 4
if mon == 1:
print(wks, "weeks is equal to", mon, "month")
else:
if hrs == 1:
print("You have 1 hour")
else:
print("You have", hrs, "hours")
There's nothing wrong with Visual Studio Code based on the information that you've provided in your post.
The first mistake that I could see was this:
day = hrs/24
#...
if day == 1:
Here, day will be exactly equal to 1 only when hrs == 24. For hrs > 24, day will always be a floating point number unless hrs is storing a multiple of 24. Hence, the condition day == 1 will never be True.
This also applies to the else block underneath, where you've written wks = day / 7 and then if wks == 1:.
To resolve this, use the floor-division operator, //, which returns an integer value if both operands are integers.
The second thing that I noticed was that in line #4, you've written hrs = hrs. I believe you wanted to write hrs = hrs % 24, which assigns the remainder of hrs and 24 to hrs itself. So for hrs = 25, number of days = hrs // 24 = 1. And, number of hours = hrs % 24 = 25 % 24 = 1 (remainder when 25 is divided by 24).
Now, on to the main question: Why did the console show no output, and why did the code terminate without doing anything?
Well, notice that all the print statements in the code are under if or else conditions. If the conditions are never true, the print statements will not be executed at all!
Consider the case where hrs = 25. The first if block becomes True (if hrs >= 24) and hence gets executed. Note that the two print statements in the corresponding else block at lines 19 and 21 will not be executed now.
Since hrs / 24 is a floating point number (not an integer, and definitely not equal to 1), the statement day == 1 is never True and hence its if statement never gets executed. So, the print statement in the if day == 1: block, printf(hrs, "hours is equal to", day, "day"), also does not get executed.
Now, the control goes to the else block below. day >= 7 evaluates to False, since hrs/24 is actually 1.08333....
Corresponding to this if (if day >= 7:), there is no else! So, when this if condition turns out to be False, the program terminates without doing anything!
I am writing the program to get two dictionaries, dict1 with names as keys and the number of wins as values, dict 2 with years as keys and the number of times won as values. My question is when I try to get the current year inside the for loop which need for the dict 1, it's always giving me and "index error: list index out of range"
and the problem is here as it shows "year_team[year]=winners[year-1903]".
def main():
dfile=open('worldserieswinners.txt','r')
winners=dfile.read().splitlines()
team_wins={}
year_team={}
for team in winners:
if team not in team_wins:
team_wins[team]=1
else:
team_wins[team]+=1
for year in range(1903, 2010):
if year != 1904 and year != 1994:
year_team[year]=winners[year-1903]
year=int(input('Enter a year between 1903 and 2009 or 0 to quit: '))
while year!= 0:
if year == 1904 or year == 1994:
print('Not played in this year')
elif 1903>year or year>2009:
print('Invalid choice')
else:
team=year_team[year]
wins=team_wins[team]
print('The winning team in',year,'was the',team)
print('The',team,'won',wins,'times between 1903 and 2009.')
year= int(input('Enter a year between 1903 and 2009 or 0 to quit: '))
dfile.close()
main()
Presumably your 'worldserieswinners.txt' file has less than 107 (2010 − 1903) lines, so that the index year-1903 gets out of range.
I'm constantly getting a NameError Although I already defined a term, The problem is with "day" on line 28.
def today():
day = input("What day is it?")
if "sunday" in day:
day = 0
elif "monday" in day:
day = 1
elif "tuesday" in day:
day = 2
elif "wednesday" in day:
day = 3
elif "thursday" in day:
day = 4
elif "friday" in day:
day = 5
elif "saturday" in day:
day = 6
else:
today()
today()
days_on_vacation = int(input("How many days will you be on vacation? "))
days_to_add_to_day = days_on_vacation % 7
day += days_to_add_to_day
I already gave day a value in the function today() right? Why am I being told it is not defined?
Names you assign to in a function are locals; they are not visible outside of the function.
The best way to share that result is to return the value from the function, so that you can assign it to a variable as a result of the call:
def today():
# ...
return day
and
result = today()
The result variable then holds the value the function returned. You are free to use the name day there too but that's then a separate variable from the one inside the function.
You did complicate matters here by using a recursive function call; you then also need to make sure you pass on the result of the recursive calls back along the chain:
def today():
# ...
else:
return today()
return day
However, it is better not to rely on recursion here; a simple enless loop would do a better; returning from the function would automatically end the loop:
def today():
while True:
day = input('...')
# ...
else:
# not valid input, restart the loop
continue
# input was valid, return the result
return day
day_left = input("What day are you leaving?")
Sunday = int(0)
Monday = int(1)
Tuesday = int(2)
Wednesday = int(3)
Thursday = int(4)
Friday = int(5)
Saturday = int(6)
days_gone = int(input("How many days are you going to be gone?"))
day_return = day_left + days_gone
day_week = day_return % 7
print(day_week)
Please excuse me if there is a very simple way to do this as I am just beginning to jump into the world of programming, starting with Python 3.4(as in first time ever). I was able to complete the basic function by having the user input a integer(ie; 0-6 for Sunday through Saturday, 3 for Wednesday, etc) for the day of the week that they were leaving.
Trying to make it more functional I seem to be running into this error:
line 18, in <module>
day_return = day_left + days_gone
TypeError: Can't convert 'int' object to str implicitly
and cannot figure out what I am doing wrong.Thanks for any help you can provide.
Also if I did anything wrong in my first post on here, please feel free to point it out; as I've been told this is an excellent source to get answers and hope to continue to use it.
days_left is a string, but you converted days_gone to an integer. You cannot sum the two.
You probably wanted to convert days_left too:
day_left = int(input("What day are you leaving?"))
Next, I see you created variables for each day of the week; you don't need to use int() when using literals, the 0, 1, etc. already produce int values:
Sunday = 0
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6
You cannot (easily) map an integer back to those names, however. You probably just want to create a sequence here:
weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
You can then index into this list to get a string for each day of the week as represented by an integer:
>>> weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
>>> weekdays[3]
'Wednesday'
First line should cast to integer like so:
day_left = int(input("What day are you leaving?"))
Basically, your current code is trying to add a string to an integer. What is the result of 'something' + 3? It simply can't be done
day_left is a string so day_return is attempting to combine an integer and a string.
If you're just starting out with programming using an if/elif statement is one easy way to change the string input to an integer, day_left_integer.
day_left = input("What day are you leaving?")
if day_left == "Sunday":
day_left_integer = 0
elif day_left == "Monday":
day_left_integer = 1
elif day_left == "Tuesday":
day_left_integer = 2
elif day_left == "Wednesday":
day_left_integer = 3
elif day_left == "Thursday":
day_left_integer = 4
elif day_left == "Friday":
day_left_integer = 5
elif day_left == "Saturday":
day_left_integer = 6
days_gone = int(input("How many days are you going to be gone?"))
day_return = day_left_integer + days_gone
day_week = day_return % 7
print(day_week)