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.
Related
This Python program should read a birth year until the number zero is entered.
The program should then print out the average age and how old the youngest and oldest is.
I need help with two things.
Print "Unreasonable age, please try again" when input year is -N, like "-45"
Print the result i.e. the arithmetic average, the youngest and oldest only when I exit the loop.
That means when I enter 0.
Current output:
Please type in birth year, to stop, enter 0: 1948
Average age is 72.0 years old.
The younges is 72 years old, and the oldest is 72 years old.
Please type in birth year, to stop, enter 0: 1845
Unreasonable age, please try again
Average age is 72.0 years old.
The younges is 72 years old, and the oldest is 72 years old.
Please type in birth year, to stop, enter 0: 1995
Average age is 48.5 years old.
The younges is 25 years old, and the oldest is 72 years old.
Please type in birth year, to stop, enter 0: 2005
Average age is 37.333333333333336 years old.
The younges is 15 years old, and the oldest is 72 years old.
Please type in birth year, to stop, enter 0: 0
Average age is 37.333333333333336 years old.
The youngest is 15 years old, and the oldest is 72 years old.
Expected output that I want:
Please type in birth year, to stop, enter 0.
Year: 1998
Year: 1932
Year: 1887
Fail: Unreasonable age, please try again.
Year: 1987
Year: -77
Fail: Unreasonable age, please try again.
Year: 1963
Year: 0
Average age is 49 years old. The youngest is 21 years old, and the oldest is 87 years old.
Example code:
# set number_years to zero ### Initial value (has not started counting yet)
number_year = 0
# set number_years to zero ### Initial value (has not started counting yet)
sum_year = 0
# set sum_year to zero ### No maximum age yet
max_year = 0
# set max_year to zero ### Well increased minimum value (age) to start with
min_year = 110
# set input_year to minus 1 ### Only as start value for the sake of the loop start!
input_year = -1
# White input_year is not 0:
while input_year != 0:
# print info and store input value to input_year, stop if 0 is entered
input_year = int(input("Please type in birth year, to stop, enter 0: "))
# let age be (2020 - input_year)
age = (2020 - input_year)
# To avoid beauty flaws with the printout "Unreasonable year ..."
# when the final zero is entered, we must check that age is not 2020
# which it is deceptive enough because 2020-0=2020
# if age is less than zero or age is greater than 110 and age is not 2020:
if age < 0 or age > 110 and age != 2020:
# Print "Unreasonable age, please try again"
print("Unreasonable age, please try again")
# else
else:
# if input_year is greater than zero:
if input_year > 0:
# increase number_year with 1
number_year += 1
# let sum_year become sum_year + age
sum_year = sum_year + age
# if age is less than min_year:
if age < min_year:
# set min_year to age ### New minimum age found
min_year = age
# if age is bigger than max_year:
if age > max_year:
# set max_year to age ### New maximum age found
max_year = age
## If the entered number was 0, exit the loop
#if input_year == 0:
# break
# Now just print the arithmetic average, the youngest and oldest
# Print "Average age is ", sum_year / number_year, "year."
print("Average age is ", sum_year / number_year, "years old.")
# Print "The younges is ", min_year, " and the oldest is ", max_year
print("The youngest is", min_year, "years old,", " and the oldest is ", max_year, "years old.")
# Done! :-)
The code works by simply unindenting the two last print statements and uncommenting the if …: break:
# Initial value (has not started counting yet)
number_year = 0
# Initial value (has not started counting yet)
sum_year = 0
# No maximum age yet
max_year = 0
# Well increased minimum value (age) to start with
min_year = 110
# Only as start value for the sake of the loop start!
input_year = -1
while input_year != 0:
# print info and store input value to input_year, stop if 0 is entered
input_year = int(input("Please type in birth year, to stop, enter 0: "))
age = 2020 - input_year
# To avoid beauty flaws with the printout "Unreasonable year ..."
# when the final zero is entered, we must check that age is not 2020
# which it is deceptive enough because 2020-0=2020
if age < 0 or age > 110 and age != 2020:
print("Unreasonable age, please try again")
# else
else:
if input_year > 0:
number_year += 1
sum_year += age
if age < min_year:
### New minimum age found
min_year = age
if age > max_year:
### New maximum age found
max_year = age
if input_year == 0:
break
# print the arithmetic average, the youngest and oldest
print("Average age is ", sum_year / number_year, "years old.")
print("The youngest is", min_year, "years old,", " and the oldest is ", max_year, "years old.")
I also removed unnecessary comments. But, your code can be simplified very much by simply using a list:
ages = []
while True: # infinite loop - we will exit by break-ing when age is 0
age = 2020 - int(input("Please enter birth year (0 to exit)"))
if age == 2020: # user entered a 0 - exit loop
break
if age < 0 or age > 110:
print("Unreasonable age, please try again")
continue # directly go to next loop
ages.append(age) # will only get appended if the condition above was false because of the continue
if ages: # ages list is not empty
print("Average age is", sum(ages) / len(ages), "years old")
print("The youngest is", min(ages), "old, and the oldest is", max(ages), "old")
else:
print("No ages entered - cannot print mean, min and max age - exiting")
You could store all the ages in a list and then do the math you need with that.
# initialize your list
ages = []
# run your code here, adding the age value with each valid input
# this can be done right before finishing the loop, after the last if statement
...
while input_year != 0:
...
ages.append(age)
# at the end, do the required calculations
average_age = np.mean(ages)
min_age = np.min(ages)
max_age = np.max(ages)
So, last week, I got some work sent to me for Python 3, and one of the questions goes as follows: "Write (a) program which inputs the year. Your program should output whether it is a leap year or not. To work out if it is a leap year, test whether it is exactly divisible by 4."
This is what I've got so far:
yearStr = input("Please input a year: ")
year = float(yearStr)
calculation = year / 4
print(calculation)
if calculation == .0:
print("This is a leap year.")
else:
print("This is not a leap year.")
When I run the program, the IF statement doesn't work as intended. Could you help me, please?
Division does not yield zero if the number is evenly divisible, so this method cannot work.
Rather, use the modulo (%) operator to get the remainder of the division:
year = int(yearStr)
calculation = year % 4
if calculation == 0: # leap year
...
And note that strictly speaking, leap year determination is a bit more complex than just being divisible by four. But it'll do for the next 79 years.
Your problem is the performance of the code. To check if the year is leap, you have to put different conditions. You can now use this code:
year = int(input("Please input a year: "))
if ((year%400 == 0) or ((year%4 == 0) and (year%100 != 0))):
print("This is a leap year.")
else:
print("This is not a leap year.")
You are comparing calculation with 0, which is true only if the year was 0. You can check if integer value is equal to number itself.
calculation = year / 4
print(calculation)
if int(calculation) == calculation:
print("This is a leap year.")
else:
print("This is not a leap year.")
Still, this is not a good way to solve this problem, there is a remainder operation - %. For example 5 % 2 = 1. You can use it this way:
yearStr = input("Please input a year: ")
year = float(yearStr)
print(calculation)
if calculation % 4 == 0:
print("This is a leap year.")
else:
print("This is not a leap year.")
I'm trying to implement another condition into my program but can't seem to figure it out.
Here is the code:
print ("Welcome to the winning card program.")
year_one=[]
year_one.append(eval(input("Enter the salary individual 1 got in year 1: ")))
year_one.append(eval(input("Enter the salary individual 2 got in year 1: ")))
if year_one[0]==year_one[1]:
print("Error. The amount are the same, please reenter information.")
year_two=[]
year_two.append(eval(input("Enter the salary individual 1 got in year 2: ")))
year_two.append(eval(input("Enter the salary individual 2 got in year 2: ")))
if year_two[0]==year_two[1]:
print("Error. The amount are the same, please reenter information.")
year_three=[]
year_three.append(eval(input("Enter the salary individual 1 got in year 3: ")))
year_three.append(eval(input("Enter the salary individual 2 got in year 3: ")))
if year_three[0]==year_three[1]:
print("Error. The amount are the same, please reenter information.")
year_four=[]
year_four.append(eval(input("Enter the salary individual 1 got in year 4: ")))
year_four.append(eval(input("Enter the salary individual 2 got in year 4: ")))
if year_four[0]==year_four[1]:
print("Error. The amount are the same, please reenter information.")
year_five=[]
year_five.append(eval(input("Enter the salary individual 1 got in year 4: ")))
year_five.append(eval(input("Enter the salary individual 2 got in year 4: ")))
if year_five[0]==year_five[1]:
print("Error. The amount are the same, please reenter information.")
individual1_total=year_one[0]+year_two[0]+year_three[0]+year_four[0]+year_five[0]
individual2_total=year_one[1]+year_two[1]+year_three[1]+year_four[1]+year_five[1]
if (individual1_total>individual2_total):
print("Individual one has the highest salary.")
elif (individual2_total>individual1_total):
print("Individual two has the highest salary.")
If the salary for the two individuals for a particular year is exactly the same, you should print an error and make the user enter both the salaries again for that year. (The condition is the salaries should not be the exact same).
I look forward to everyone's feedback.
Thank you in advance.
Ok so building on surge10 here is a more complete replacement of your code. I broke all the pieces down into functions, and made a dictionary as my in in-memory database.
total_years = 5
years = {}
def dict_key(year, userId):
return '{}:{}'.format(year, userId)
def get_user_data(year, userId):
key = dict_key(year, userId)
years[key] = float(input("Enter the salary individual {} got in year {}:".format(userId, year)))
def get_year_salaray(year, userId):
key = dict_key(year, userId)
return years[key]
def any_salaries_match(year, userIds):
for userLeft in userIds:
salary_left = get_year_salaray(year, userLeft)
for userRight in userIds:
if userLeft != userRight:
salary_right = get_year_salaray(year, userRight)
if salary_left == salary_right:
return True
def get_user_totals(userId):
total = 0
for key, value in years.items():
if ':{}'.format(userId) in key:
total += value
return total
for x in range(total_years):
year = x + 1
data_invalid = True
while data_invalid:
userOne = 1
userTwo = 2
get_user_data(year, userOne)
get_user_data(year, userTwo)
if any_salaries_match(year, [userOne, userTwo]):
print("Error. The amount are the same, please reenter information.")
else:
data_invalid = False
userOneTotal = get_user_totals(1)
userTwoTotal = get_user_totals(2)
if (userOneTotal>userTwoTotal):
print("Individual one has the highest salary.")
elif (userTwoTotal>userOneTotal):
print("Individual two has the highest salary.")
Since we were checking for five different years I used a loop for those five years
Later we can get it back into individual years.
print ("Welcome to the winning card program.")
years=[]
for x in range(5):
# range starts at zero so add one all the time
# to start it at one
y = str(x + 1)
errors = True
while errors:
salary_one = input("Enter the salary individual 1 got in year " + y + ": ")
salary_two = input("Enter the salary individual 2 got in year " + y + ": ")
if salary_one == salary_two:
print("Error. The amount are the same, please reenter information.")
errors = True
else:
years.append([salary_one, salary_two])
errors = False
year_one = years[0]
year_two = years[1]
...
print(year_one)
print(year_two)
...
could anyone please help me with a current problem Im having... Its a leap year exercise.
● Write a program to input a year and a number of years.
● Then determine and display which of those years were or will be leap
years.
Example:
What year do you want to start with? - 1994
How many years do you want to check? - 8
1994 isn’t a leap year
1995 isn’t a leap year
1996 is a leap year
1997 isn’t a leap year
1998 isn’t a leap year
1999 isn’t a leap year
2000 is a leap year
2001 isn’t a leap year
I cant seem to get my years to display there own value of being a leap year or not....this is the code i have so far:
year = int(input("Please enter the year you would like to start checking leap years from."))
total_years = int(input("Please enter over how many years you would like to check."))
leap_year= 0
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
leap_year = ("this is a leap year")
else:
leap_year = ("this is not a leap year")
for a in range (0,total_years):
print(year + a, leap_year)
Any help will be greatly appreciated.
Thank you.
You need to put the logic for checking the years into the loop. For example like so:
start_year = int(input("Please select a starting year: "))
num_of_years = int(input("Please select how many years you'd like to check: "))
end_year = start_year + num_of_years
# The formula I used below to determine when a year is a leap year was copied from emrah-diril in this thread
for year in range(start_year-1, end_year):
year += 1
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
print ("{}: Is a leap year".format(year))
else:
print (year)
The if-else block that checks for leap year should be inside the for loop. It's currently outside the for loop so it checks the first year you enter and the for loop simply prints the result for the first year total_years number of times.
So, to fix your code, try something like this:
year = int(input("Please enter the year you would like to start checking leap years from."))
total_years = int(input("Please enter over how many years you would like to check."))
def is_leap_year(year):
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return True
else:
return False
for a in range (0, total_years):
if is_leap_year(year+a):
print("this is a leap year")
else:
print("this is not a leap year")
python
start_year = int(input("Please enter the year you would like to start checking leap years from: "))
total_years = int(input("Please enter over how many years you would like to check: "))
for year in range(start_year, start_year + total_years):
if year % 4 == 0:
print(f"{year} is a leap year")
else:
print (f"{year} is not a leap year")
The 2013 CCC Senior 1 problem on page 4 is to find the smallest number that is larger than the input with distinct digits as the title explains.
I'm a total beginner at programming and I can't find what's wrong with this code:
year = 1987
distinct = 'no'
a = []
while distinct != 'yes':
year += 1
for i in str(year):
if i not in a:
a.append(i)
distinct = "yes"
else:
distinct = "no"
break
print(year)
I think the code is still in the while loop but I don't understand why. The code above is supposed to print 2013. Thank you for your help.
Your approach to increment the year by 1 and check if the digits are distinct is correct, and your code is almost correct. Your mistake is that you initialize a[], your set of digits in the year, only once, but it should be initialized to empty for each year. Move the line a = [] to after the line year += 1 and give it the proper indentation and your code will work. That would make your code into:
year = 1987
distinct = 'no'
while distinct != 'yes':
year += 1
a = []
for i in str(year):
if i not in a:
a.append(i)
distinct = "yes"
else:
distinct = "no"
break
print(year)
Another approach is to use a set, which automatically removes any duplicates. You can check if making the string of the year into a set changes its size. So perhaps use this, which also avoids using a status variable like distinct:
year = 1987
year += 1
while len(set(str(year))) != len(str(year)):
year += 1
print(year)
If you want that status variable, or do not like that repeated line year += 1, you could do this:
year = 1987
distinct = False
while not distinct:
year += 1
if len(set(str(year))) == len(str(year)):
distinct = True
print(year)