简体   繁体   中英

Finding the max value in user inputs with Python for loop and sequence statements

I'm writing a program that asks a user to input a number of years. and then asks the user to input a yearly tax amount until the specified number of years is met. Then the program needs to output the maximum yearly income tax based on those user inputs. All of my program is working except for the maximum part. It keeps giving me a random number whenever I try to output a maximum value. Is anyone able to tell me where I'm going wrong? Below is my code:

`enter code here`
years = int(input('Number of years: '))
    if years == 0:
      print('Could not calculate maximum tax given.')
      exit()

for i in range(years):
  tax = input("Income tax given for year " +str(i+1)+ "($): ")


maximum = 0

for x in range(int(tax)):
  if (maximum==0 or maximum<x):
    maximum = x

print('Maximum tax given in a year($): ' + str(maximum))

You should add the tax input to a list, otherwise it will be overwritten. to get the max number you can use max().

years = int(input('Number of years: '))
if years == 0:
    print('Could not calculate maximum tax given.')
    exit()
tax=[]
for i in range(years):
    tax.append(int(input("Income tax given for year " +str(i+1)+ "($): ")))


maximum = 0

for x in tax:
    if (maximum==0 or maximum<x):
        maximum = x

print('Maximum tax given in a year($): ' + str(maximum))

print('Maximum tax given in a year($): (using max()) ' + str(max(tax)))

The answer Kilian gave is spot on, just one suggestion though.

Python print of integers or Numbers should be like this:

print('Maximum tax given in a year($): (using max()) %d' %max(tax))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM