How to pass multiple inputs from the user to a function?
I’m trying to get the number of tests, assignments, quizzes and labs. Then pass those values to a function to get the score for each item in the category. How do I pass multiple values so they can be used in the function?
def get_initial_input(): int(input("How many assignments? ")) int(input("How many quizzes? ")) int(input("How many labs? ")) int(input("How many tests? ")) #Trying to pass all the values entered above to the function below #Using 'return' I can only pass one value def get_scores(s): for x in range(len(s)): s[x] = int(input("Give a score: ")) def main(): num = get_initial_input() scores = [0] * num get_scores(scores) total = 0 for x in range(len(scores)): total += scores[x] print("The sum is: "+str(total)) if total > 0: print("The average is: "+str(total/num)) if (total/num) > 100: print("You got extra credit!") main()
4 Answers 4
def get_initial_input(): input_list = [] input_list.append(int(input("How many assignments? "))) input_list.append(int(input("How many quizzes? "))) input_list.append(int(input("How many labs? "))) input_list.append(int(input("How many tests? "))) return input_list def get_scores(s): return [ int(input("Give a score: ")) for x in s] #use list comprehensions def main(): input_list = get_initial_input() scores = get_scores(input_list) total = sum(scores) num = sum(input_list) # I am assuming this print("The sum is: "+str(total)) if total > 0: print("The average is: "+str(total/num)) if (total/num) > 100: print("You got extra credit!") main()
- To return multiple values from a function, there are a lot of work arounds. Using a list of values if one of them.
- In the function get_scores , I have used a list comprehension. It can also be done using a for loop: for item in s: score_list.append(. ); return score_list . List comprehensions are much more cleaner and much more pythonic.
- You no longer have to write a loop to sum an array. Python has built-in functions to do that. Just use sum(list) . Built-in Functions
- I see that you are using a C/C++ like style of coding. Reading more tutorials and writing more code would help develop a pythonic style of writing code.
You need to store the returned input:
assignments = int(input("How many assignments? "))
Now you have a variable you can work with. You’d need to return that from the function:
def get_initial_input(): assignments = int(input("How many assignments? ")) quizzes = int(input("How many quizzes? ")) labs = int(input("How many labs? ")) tests = int(input("How many tests? ")) return assignments, quizzes, labs, tests
and when store the return value of the function call:
assignments, quizzes, labs, tests = get_initial_input()
Multiprocessing a function with several inputs
In Python the multiprocessing module can be used to run a function over a range of values in parallel. For example, this produces a list of the first 100000 evaluations of f.
def f(i): return i * i def main(): import multiprocessing pool = multiprocessing.Pool(2) ans = pool.map(f, range(100000)) return ans
Can a similar thing be done when f takes multiple inputs but only one variable is varied? For example, how would you parallelize this:
def f(i, n): return i * i + 2*n def main(): ans = [] for i in range(100000): ans.append(f(i, 20)) return ans
5 Answers 5
def f(i, n): return i * i + 2*n def main(): import multiprocessing pool = multiprocessing.Pool(2) ans = pool.map(functools.partial(f, n=20), range(100000)) return ans
I know that this is allowed, but why, given that only functions defined at the module top level may be pickled?
Can you clarify moment about using partial — looks like it ignores keys for argument: if I want to pool.map on SECOND argument — partial(f, i=20) — I got error: got multiple values for argument i .
@Mikhail_Sam docs.python.org/2/library/functools.html#functools.partial The function you are adding to the partial needs to have the first argument as the positional argument (like ‘i’ when running for loop) and the remaining keyword arguments should come after that. All the values of ‘i’ are added as a list/range as the second argument to the ‘pool.map’ function. In your example, you have provided a value of ‘i’ within the partial function when the values for ‘i’ are already available as the second argument of ‘pool’ function, leading you to the self explanatory error/
Taking multiple integers on the same line as input from the user in python
This opens up one input screen and takes in the first number. If I want to take a second input I need to repeat the same command and that opens up in another dialogue box. How can I take two or more inputs together in the same dialogue box that opens such that:
Enter 1st number. enter second number.
Yes, I figured that. I’m still surprised because raw_input should just write the prompt to sys.stdout and read the input from sys.stdin , and those are usually a terminal, another program’s output or a file. If there’s GUI happening when you do it, that’d be very unusual enviroment.
19 Answers 19
You can then use ‘a’ and ‘b’ separately.
How about something like this?
user_input = raw_input("Enter three numbers separated by commas: ") input_list = user_input.split(',') numbers = [float(x.strip()) for x in input_list]
(You would probably want some error handling too)
Or if you are collecting many numbers, use a loop
num = [] for i in xrange(1, 10): num.append(raw_input('Enter the %s number: ')) print num
My first impression was that you were wanting a looping command-prompt with looping user-input inside of that looping command-prompt. (Nested user-input.) Maybe it’s not what you wanted, but I already wrote this answer before I realized that. So, I’m going to post it in case other people (or even you) find it useful.
You just need nested loops with an input statement at each loop’s level.
data="" while 1: data=raw_input("Command: ") if data in ("test", "experiment", "try"): data2="" while data2=="": data2=raw_input("Which test? ") if data2=="chemical": print("You chose a chemical test.") else: print("We don't have any " + data2 + " tests.") elif data=="quit": break else: pass
You can read multiple inputs in Python 3.x by using below code which splits input string and converts into the integer and values are printed
user_input = input("Enter Numbers\n").split(',') #strip is used to remove the white space. Not mandatory all_numbers = [int(x.strip()) for x in user_input] for i in all_numbers: print(i)
- a, b, c = input().split() # for space-separated inputs
- a, b, c = input().split(«,») # for comma-separated inputs
whenever you want to take multiple inputs in a single line with the inputs seperated with spaces then use the first case .And when the inputes are seperated by comma then use the seconfd case . You implement this to shell or any ide and see the working ..@MittalPatel
You could use the below to take multiple inputs separated by a keyword
a,b,c=raw_input("Please enter the age of 3 people in one line using commas\n").split(',')
The best way to practice by using a single liner,
Syntax:
Taking multiple integer inputs:
list(map(int, input('Enter: ').split(',')))
Taking multiple Float inputs:
list(map(float, input('Enter: ').split(',')))
Taking multiple String inputs:
list(map(str, input('Enter: ').split(',')))
List_of_input=list(map(int,input (). split ())) print(List_of_input)
Python and all other imperative programming languages execute one command after another. Therefore, you can just write:
first = raw_input('Enter 1st number: ') second = raw_input('Enter second number: ')
Then, you can operate on the variables first and second . For example, you can convert the strings stored in them to integers and multiply them:
product = int(first) * int(second) print('The product of the two is ' + str(product))
Thats right but isnt this going to open up two boxes. how can i enter both numbers in one box? like embedding both raw_input commands into one dialogue box at the same time
@user899714 In the default cpython environment, raw_input has no graphical user interface. You seem to be using a graphical/educational Python environment. Can you tell us the name of that environment?
Actually i haven’t used one yet. i was wondering if i could enhance the look of how i take input from user without getting into the hassle of using a graphical environment just by modifying/changing raw_input command. But i guess it isn’t possible.
In Python 2, you can input multiple values comma separately (as jcfollower mention in his solution). But if you want to do it explicitly, you can proceed in following way. I am taking multiple inputs from users using a for loop and keeping them in items list by splitting with ‘,’.
items= [x for x in raw_input("Enter your numbers comma separated: ").split(',')] print items
import sys for line in sys.stdin: j= int(line[0]) e= float(line[1]) t= str(line[2])
For details, please review,
Split function will split the input data according to whitespace.
data = input().split() name=data[0] id=data[1] marks = list(map(datatype, data[2:]))
name will get first column, id will contain second column and marks will be a list which will contain data from third column to last column.
A common arrangement is to read one string at a time until the user inputs an empty string.
strings = [] # endless loop, exit condition within while True: inputstr = input('Enter another string, or nothing to quit: ') if inputstr: strings.append(inputstr) else: break
This is Python 3 code; for Python 2, you would use raw_input instead of input .
Another common arrangement is to read strings from a file, one per line. This is more convenient for the user because they can go back and fix typos in the file and rerun the script, which they can’t for a tool which requires interactive input (unless you spend a lot more time on basically building an editor into the script!)
with open(filename) as lines: strings = [line.rstrip('\n') for line in lines]
Using functions for multiple inputs [Python]
I’m new to python, taking my first class in it right now, only about 4 weeks in. The assignment is to calculate test average and display the grade for each test inputted. Part of the assignment is to use a function to calculate the average as well as deciding what letter grade to be assigned to each score. As I understand it, functions are supposed to help cut down global variables. My question is this: how do I condense this code? I don’t know how to use a function for deciding letter grade and then displaying that without creating a global variable for each grade that has been inputted. If you notice any redundancy in my code, I would appreciate a heads up and a little lesson on how to cut that out. I can already smell the mark downs I will get if I turn this in as is.
def main(): grade1=float(input( "Enter score (0-100):")) while (grade1 100 ): if grade1 100: print("Please enter a valid grade") grade1=float(input( "Enter score (0-100):")) grade2=float(input( "Enter score (0-100):")) while (grade2 100 ): if grade2 100: print("Please enter a valid grade") grade2=float(input( "Enter score (0-100):")) grade3=float(input( "Enter score (0-100):")) while (grade3 100 ): if grade3 100: print("Please enter a valid grade") grade3=float(input( "Enter score (0-100):")) grade4=float(input( "Enter score (0-100):")) while (grade4 100 ): if grade4 100: print("Please enter a valid grade") grade4=float(input( "Enter score (0-100):")) grade5=float(input( "Enter score (0-100):")) while (grade5 100 ): if grade5 100: print("Please enter a valid grade") grade5=float(input( "Enter score (0-100):")) total=grade1+grade2+grade3+grade4+grade5 testAverage=calcAverage(total) eachGrade1=determineGrade(grade1) eachGrade2=determineGrade(grade2) eachGrade3=determineGrade(grade3) eachGrade4=determineGrade(grade4) eachGrade5=determineGrade(grade5) print("\nTest #1 grade:", (eachGrade1)) print("Test #2 grade:", (eachGrade2)) print("Test #3 grade:", (eachGrade3)) print("Test #4 grade:", (eachGrade4)) print("Test #5 grade:", (eachGrade5)) print("\nTest average:", (testAverage),("%")) def calcAverage(total): average=total/5 return average def determineGrade(grade): if grade >=90: return "A" elif grade >=80: return "B" elif grade >=70: return "C" elif grade >=60: return "D" else: return "F"