简体   繁体   中英

How do I write a function for Varied amount input data for Python?

I'm having some problems with my code for the below assignment. It's not calculating the average value or the max value. The output I get with the below code is '0,0'. Could someone help me with this, please?

"6.12 LAB: Varied amount of input data Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max."

Example: If the input is: 15 20 0 5 , then the output should be: 10 20

user_input = input()
tokens = user_input.split()
input_data = []
    
for token in tokens:
    token = int()
    input_data.append(token)
        
average = int(sum(input_data) /len(input_data))
max_num = max(input_data)
    
print(average, max_num)

You meant to write int(token) instead of just int() . You can clean your code up a little bit by using "list comprehension" to place most of your code in one line like:

user_input = input()
tokens = [int(x) for x in user_input.split()]

# or even clean it more with: tokens = [int(x) for x in input().split()]
    
average = int(sum(tokens) /len(tokens))
max_num = max(tokens)

print(average, max_num)

With user input being 15 20 0 5 the output is 10 20

You were not converting token to an int value correctly. This is the correct syntax:

user_input = input()
tokens = user_input.split()
input_data = []

for token in tokens:
    token = int(token)
    input_data.append(token)
    
average = int(sum(input_data) /len(input_data))
max_num = max(input_data)

print(average, max_num)

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