How to take Multiple Input from User in Python - Javatpoint
文章推薦指數: 80 %
Using split() Method · # taking two inputs at a time · a, b, c = input("Enter three values: ").split() · print("Enter Your First Name: ", a) · print("Enter Your ... ⇧SCROLLTOTOP Home Python IfElse ForLoop Function Array String Regex List Set Tuple Dictionary Programs Numpy InterviewQuestions PythonTutorial PythonTutorial PythonFeatures PythonHistory PythonApplications PythonInstall PythonExample PythonVariables PythonDataTypes PythonKeywords PythonLiterals PythonOperators PythonComments PythonIfelse PythonLoops PythonForLoop PythonWhileLoop PythonBreak PythonContinue PythonPass PythonStrings PythonLists PythonTuples PythonListVsTuple PythonSets PythonDictionary PythonFunctions PythonBuilt-inFunctions PythonLambdaFunctions PythonFilesI/O PythonModules PythonExceptions PythonDate PythonRegex PythonSendingEmail ReadCSVFile WriteCSVFile ReadExcelFile WriteExcelFile PythonAssert PythonListComprehension PythonCollectionModule PythonMathModule PythonOSModule PythonRandomModule PythonStatisticsModule PythonSysModule PythonIDEs PythonArrays CommandLineArguments PythonMagicMethod PythonStack&Queue PySparkMLlib PythonDecorator PythonGenerators WebScrapingUsingPython PythonJSON PythonItertools PythonMultiprocessing HowtoCalculateDistancebetweenTwoPointsusingGEOPY GmailAPIinPython HowtoPlottheGoogleMapusingfoliumpackageinPython GridSearchinPython PythonHighOrderFunction nsetoolsinPython PythonprogramtofindthenthFibonacciNumber PythonOpenCVobjectdetection PythonSimpleImputermodule SecondLargestNumberinPython PythonOOPs PythonOOPsConcepts PythonObjectClass PythonConstructors PythonInheritance AbstractioninPython PythonMySQL EnvironmentSetup DatabaseConnection CreatingNewDatabase CreatingTables InsertOperation ReadOperation UpdateOperation JoinOperation PerformingTransactions PythonMongoDB PythonMongoDB PythonSQLite PythonSQLite PythonQuestions HowtoinstallPythoninWindows HowtoreverseastringinPython HowtoreadCSVfileinPython HowtorunPythonProgram HowtotakeinputinPython HowtoconvertlisttostringinPython Howtoappendelementinthelist HowtocomparetwolistsinPython HowtoconvertinttostringinPython HowtocreateadictionaryinPython HowtocreateavirtualenvironmentinPython HowtodeclareavariableinPython HowtoinstallmatplotlibinPython HowtoinstallOpenCVinPython HowtoprintinsamelineinPython HowtoreadJSONfileinPython HowtoreadatextfileinPython HowtouseforloopinPython IsPythonscriptinglanguage HowlongdoesittaketolearnPython HowtoconcatenatetwostringsinPython HowtoconnectDatabaseinPython HowtoconvertlisttodictionaryinPython HowtodeclareaglobalvariableinPython HowtoreverseanumberinPython WhatisanobjectinPython WhichisthefastestimplementationofPython HowtoclearPythonshell HowtocreateaDataFramesinPython HowtodevelopagameinPython HowtoinstallTkinterinPython HowtoplotagraphinPython HowtoprintpatterninPython HowtoremoveanelementfromalistinPython HowtoRoundnumberinPython HowtosortadictionaryinPython StrongNumberinPython HowtoConvertTexttoSpeechinPython BubbleSortinPython LogginginPython InsertionSortinPython BinarySearchinPython LinearSearchinPython PythonvsScala QueueinPython StackinPython HeapSortinPython Palindromeprograminpython ProgramofCumulativesuminpython MergeSortinPython PythonMatrix PythonUnitTesting Forensics&Virtualization BestBookstoLearnPython BestBookstoLearnDjango GCDoftwonumberinpython PythonProgramtogenerateaRandomString HowtoOneHotEncodeSequenceDatainPython HowtowritesquarerootinPython PointerinPython Python2Darray PythonMemoryManagement PythonLibrariesforDataVisualization HowtocallafunctioninPython GitModulesinPython TopPythonFrameworksforGaming PythonAudioModules WikipediaModuleinPython Pythonrandomrandrange() PermutationandCombinationinPython GetoptmoduleinPython MergetwoDictionariesinPython MultithreadinginPython3 StaticinPython HowtogetthecurrentdateinPython argparseinPython PythontqdmModule CaesarCipherinPython TokenizerinPython HowtoaddtwolistsinPython ShallowCopyandDeepCopyinPython AtomPython ContainsinPython LabelEncodinginPython Djangovs.NodeJS PythonFrameworks HowtocreateavectorinPythonusingNumPy PickleModuleofPython HowtoconvertBytestostringinPython PythonProgramtoFindAnagram HowtoconvertListtoSet PythonvsJavaScript PythonHolidaysModule FuzzyWuzzyPythonLibrary DaskPython DaskPython(Part2) ModeinPython Menu-DrivenProgramsinPython PythonArrayvs.List WhatisducktypinginPython PEP8inPython PythonUserGroups BasicCommandsinPython FStringinPython HowBrythonWorks HowtouseBrythonintheBrowser ArimaModelinPython PythonModulusOperator MATLABvs.Python MethodResolutionOrderinPython MonkeyPatchinginPython Python__call__method Pythonheapqmodule PythonSubstring ProjectideasforPythonBeginners PythonFaker Fizz-BuzzPrograminPython TabulaPython PythonProgramtoPrintPrimeFactorofGivenNumber PythonProgramtoPrintPascalTriangle NamedTupleinPython OrderedDictinPython T-TestinPython Pythonreturnstatement GetterandSetterinPython EnumclassinPython DestructorsinPython CurveFitinPython ConvertingCSVtoJSONinPython Underscore(_)inPython SetvsListinPython LocatingandExecutingModules FlattenListinPython PairPlotinPython DataHidinginPython PythonProgramtoFindIntersectionofTwoLists HowtoCreateRequirements.txtFileinPython Tic-Tac-ToeinPython PythonAsynchronousProgramming-asyncioandawait Pythonmain()function strftime()functioninPython VerboseFlaginPythonRegex PythonASTModule PythonRequestsModule-HTTPRequest ShutilModuleinPython PythonepochtoDatetime PythondelStatement LoopingtechniqueinPython MetaprogrammingwithMetaclassesinPython PrecisionHandlinginPython PythonJoinList strip()functioninPython GradientDescentAlgorithm PrettytableinPython SentimentAnalysisinPython ConvertPythonListtoNumPyArrays TracebackinPython Timeclock()MethodinPython DequeinPython DictionaryComprehensioninPython PythonDataAnalytics Pythonseek()Method TernaryOperatorinPython HowtoCalculatetheAreaoftheCircleusingPython HowtoWriteinTextFileusingPython PythonKeyError Pythonsuper()Function max()functioninPython FractionModuleinPython PopularPythonFrameworktoBuildAPI HowtoCheckPythonversion Python%s-StringFormatting PythonseabornLibrary CountplotinPython range()Vs.Xrange()Python WordcloudPackageinPython Convertdataframeintolist ANOVATestinPython Pythonprogramtofindcompoundinterest AnsibleinPython PythonImportantTipsandTricks PythonCoroutines DoubleUnderscoresinPython re.search()VSre.findall()inPythonRegex HowtoinstallstatsmodelsinPython CosinPython vifinPython __add__MethodinPython EthicalHackingwithPython ClassVariablevsInstance PerfectNumberinPython EOLinPython PythonProgramtoconvertHexadecimalStringtoDecimalString DifferentMethodsinPythonforSwappingTwoNumberswithoutusingthirdvariable HowtoChangePlotSizeinMatplotlib HowtoGettheZipCodeinPython EelinPython AssignmentOperatorsinPython SpeechRecognitionpython YieldvsReturninPython GraphenePython NameManglinginPython Pythoncombinationwithoutitertools PythonComprehensions InfluxDBinPython KafkaTutorialinPython AugmentedAssignmentExpressionsinPython Python(x,y)Software PythonEvent-Drivenprogramming PythonSemaphore Pythonsortedreverse AutomorphicNumberinPython sizeofinPython PythonProgramforacceptingthestringswhichcontainsallvowels Class-basedviewsvsFunction-BasedViews HowtohandlecookiesinDjango agg()functioninPython AmicableNumbersinPython ContextManagerinPython CreateBMICalculatorusingPython StringtoBinaryinPython WhatisscriptmodeinPython BestPythonlibrariesforMachineLearning PythonProgramtoDisplayCalendarofGivenYear HowtoopenURLinPython BrokenPipeErrorinPython CodeTemplateforCreatingObjectsinPython Pythonprogramtocalculatethebesttimetobuyandsellstock TupletoStringinPython Kadane'sAlgorithminPython LoggersinDjango WeatherAppinDjango MissingDataConundrum:ExplorationandImputationTechniques DifferentMethodsofArrayRotationinPython WhatisOperatorOverloadinginPython DefaultdictinPython OperatorModuleinPython SpinnerWidgetinthekivyLibraryofPython NumberPlateRecognitionusingPython ObfuscatingaPythonprogram ConvertstringtodictionaryinPython ConvertstringtoJSONinPython DBSCANalgorithminPython HowtoWriteaCodeforPrintingthePythonException/ErrorHierarchy PrincipalComponentAnalysis(PCA)withPython PythonProgramtoFindNumberofDaysBetweenTwoGivenDates ObjectRecognitionusingPython PythonVLCmodule SettolistinPython StringtointinPython InternetofThingswithPython Pythonpysftpmodule AmazinghacksofPython AverageoflistinPython CheckInstalledModulesinPython choice()inPython ConvertListtodataframeinPython ConvertStringtoFloatinPython DecoratorswithParametersinPython DynamicTypinginPython FabsinPython HowtoRemoveDecimalinPython PythonClosure PythonGlobModule WritingaPythonModule ModulesvsPackagesinPython SNMPmoduleinPython AverageoflistinPython AppendvsExtendvsInsertinPython HowtoRemoveDuplicatesfromalistinPython RemoveMultipleCharactersfromaStringinPython ShuffleinPython floor()andceil()FunctionsinPython sqrt():MathFunctionofPython PythonyfinanceModule DifflibmoduleinPython ConverttheColumnTypefromStringtoDatetimeFormatinPandasDataFrame PythonwxPythonModule RandomUniformPython RelationalOperatorsinPython StringtoListinPython ChatbotinPython HowtoConvertfloattointinPython MultiplyAllElementsinlistofPython modulevsfunctioninPython ReverseatupleinPython TupletoDictionaryinPython datetime.timedelta()FunctionofPython PythonBioModule PythonDashModule HowtoSelectrowsinPandasDataFrameBasedonConditions TypecastinginPython DateutilmoduleinPython GetpassmoduleinPython PythonWandlibrary GenerateaQRCodeusingPython BestPythonPDFLibrary PythonCachetoolsModule PythonCmdparserModule PythonDashmodule PythonEmojiModule PythonNmapModule PythonPyLabModule WorkingwithPDFfilesinPython PDFHandlinginPython ManipulatingPDFusingPython ListAllFunctionsfromaPythonModule PythonlistofDictionaries PythonShelveModule CreatingInteractivePDFformsusingPython PythonNewspaperModule HowtoConnectWi-FiusingPython BestPythonLibrariesusedforEthicalHacking WindowsSystemAdministrationManagementusingPython IndentationErrorinPython PythonimaplibModule PythonlxmlModule PythonMayaViModule Pythonos.listdir()method PythonModulesforAutomation DataVisualizationinPythonusingBokehLibrary HowtoPlotglyphsoveraGoogleMapbyusingBokehLibraryinPython HowtoPlotaPieChartusingBokehLibraryinPython HowtoReadContentsofPDFusingOCRinPython GrammarandSpellCheckerinPython ConvertingHTMLtoPDFfilesusingPython ReadlinesinPython HowtoPlotMultipleLinesonaGraphUsingBokehinPython bokeh.plotting.figure.circle_x()FunctioninPython bokeh.plotting.figure.diamond_cross()FunctioninPython HowtoPlotRaysonaGraphusingBokehinPython ImageSteganographyusingPython Inconsistentuseoftabsandspacesinindentation HowtoPlotMultiplePlotsusingBokehinPython HowtoMakeanAreaPlotinPythonusingBokeh PythonChemPyModule Pythonmemory-profilerModule PythonPhonenumbersModule PythonPlatformModule TypeErrorstringindicesmustbeaninteger TimeSeriesForecastingwithProphetinPython PythonPexpectModule PythonOptparseModule intobjectisnotiterable. PythonPeeweeLibrary SomeCryptocurrencyLibrariesforPython BuildingaBlockchainusingPython HuffmanCodingusingPython NestedDictionaryinPython Collections.UserStringinPython HowtoCustomizeLegendswithMatplotlib Matplotliblegendinsubplot MorphologicalOperationsinImageProcessinginPython RoleofPythoninArtificialIntelligence PythonInstagramyModule PythonpprintModule PythonPrimePyModule AndroidDevelopmentusingPython Pythonfbchatlibrary ArtificialIntelligenceinCybersecurity:PittingAlgorithmsvsAlgorithms UnderstandingTheRecognitionPatternofArtificialIntelligence WhenandHowtoLeverageLambdaArchitectureinBigData WhyShouldWeLearnPythonforDataScience HowtoChangethe"legend"PositioninMatplotlib HowtoCheckifElementExistsinListinPython HowtoCheckSpellingsofGivenWordsusingEnchantinPython PythonProgramtoCounttheNumberofMatchingCharactersinaPairofString PingPongGameUsingTurtleinPython PythonFunctiontoDisplayCalendar PythonProgramforCalculatingtheSumofSquaresofFirstnNaturalNumbers PythonProgramforHowtoCheckifaGivenNumberisFibonacciNumberorNot randint()FunctioninPython VisualizeTiffFileusingMatplotlibandGDALinPython rarfilemoduleinPython StemmingWordsusingPython PythonProgramforWordGuessingGame BlockchaininHealthcare:Innovations&Opportunities SnakeGameinPythonusingTurtleModule HowtoFindArmstrongNumbersbetweentwogivenIntegers CeleryTutorialUsingPython RSME-RootMeanSquareErrorinPython BuildingaTwitterBotusingPython PythonProgressbarModule PythonPronouncingModule PythonPyAutoGUIModule PythonPyperclipModule HowtoGenerateUUIDinPython PythonTop10LibrariestoLearnin2022 ReadingNetCDFDatausingPython ThereprlibmoduleinPython HowtotakeMultipleInputfromUserinPython PythonzlibLibrary PythonQueueModule PythonYAMLParser EffectiveRootSearchingAlgorithmsinPython PythonBz2Module PythonIPaddressModule PythonPyLintModule HowtoProcessXMLinPython BisectAlgorithmFunctionsinPython CreatingandUpdatingPowerPointPresentationusingPython Howtochangethesizeoffiguredrawnwithmatplotlib KeyboardModuleinPython PythonPyfigletModule CreatinganMCQQuizGameinPython StatisticwithPython WhatisGILinPython BasicPythonforJavaDevelopers HowtoDownloadYouTubeVideosUsingPythonScripts TrafficFlowSimulationinPython HowtoMergeandSortTwoListsinPython MetacharactersinPython WritethePythonProgramtoPrintAllPossibleCombinationofIntegers ModuloStringFormattinginPython CountersinPython PythonpyautoguiLibrary HowtoDrawtheMandelbrotSetinPython PythonDbmModule WebcamMotionDetectorinPython GraphQLImplementationinDjango HowtoImplementProtobufinPython PyQtlibraryinPython HowtoPrettifyDataStructureswithPrettyPrintinPython EncryptaPasswordinPythonUsingbcrypt PyramidFrameworkinPython BuildingaTelegrambotusingPython Web2pyFrameworkinPython Pythonos.chdir()Method BalancingParenthesesinPython HowtoProvideMultipleConstructorsinPythonClasses ProfilingthePythoncode BuildaDice-RollingApplicationwithPython EmailmoduleinPython EssentialRecursionProgramsinPython HowtoDesignHashsetinPython HowtoExtractYouTubeDatainPython HowtoSolveStockSpanProblemUsingPython SelectionSortinPython info()FunctioninPython TwoSumProblem:PythonSolutionofTwosumproblemofGivenList WriteaPythonProgramtoCheckaListContainsDuplicateElement WritePythonProgramtoSearchanElementinSortedArray PathlibmoduleinPython CreateaRealTimeVoiceTranslatorusingPython HowtoSortTupleinPython AdvantagesofPythonthatmadeitsoPopularanditsMajorApplications LibraryinPython PackagesofDataVisualizationinPython Pythonpymplerlibrary SnakeVizlibraryinPython MaterializedViewvsView NamespaceinPython PythonProgramtoreturntheSignoftheproductofanArray FabricModuleinPython TracemallocmoduleinPython Split,Sub,Subnfunctionsofremoduleinpython RobotFrameworkinPython UnderstandingRoboticswithPython GzipmoduleinPython guppy/heapyinPython MicroservicesinPython FunctoolsModuleinPython PlottingGoogleMapusinggmplotpackageinPython MonitoringDevicesusingPython WebbrowsermoduleinPython BinarySearchusingRecursioninPython CvsC++vsPythonvsJava HowtoCheckVersionofPython PythonListComprehension ConvertRomanNumbertoDecimal(Integer)|WritePythonProgramtoConvertRomantoInteger CreateRESTAPIusingDjangoRESTFramework|DjangoRESTFrameworkTutorial MemoizationusingDecoratorsinPython PythonforNetworkEngineering 'and'vs'&'inPython CryptographypackageinPython HangmanGameinPython ImplementationofLinearRegressionusingPython NestedDecoratorsinPython PythonProgramtoFindDifferencebetweenTwoStrings PythonurllibLibrary FionamoduleinPython Firebasemoduleinpython PythonForKids FloorDivisioninPython Top10BestCourseraPythonCourses TopPythonforNetworkEngineeringLibraries HowdoesTokenizingText,Sentence,WordsWorks HowtoImportDatasetsusingsklearninPyBrain PartofSpeechTaggingusingTextBlob PythonforKids:ResourcesforPythonLearningPath XGBoostMLModelinPython SimpleFLAMESgameinPython AlarmClockwithGUIinPython RockPaperScissorsGameinPython CheckifaGivenLinkedListisCircularLinkedList ReversetheLinkedListinPython Flatten()vsRavel()NumpyFunctions LearningVectorQuantization LemmatizationandTokenizewithTextBlob HowtoRoundNumbersinPython PrecedenceandAssociativityofOperatorsinPython Pythonunofficiallibraries 12BestPythonProjectsforClass12 DesktopNotifierinPython HowtohandleTimezonesinPython PythonSecretModule MakeNotepadusingTkinter CamelcaseinPython DifferencebetweenPythonandScala HowtoUseCbindinPython PythonAsserts PythonBitwiseOperators PythonTimeasctime()Method Q-LearninginPython CombinatoricIteratorsinPython ClassMethodvsStaticMethodvsInstanceMethod FreePythoneBooks EightAmazingIdeasofPythonTkinterProjects CreatingaKeyloggerusingPython QuandlpackageinPython ImplementingAprioriAlgorithminPython SentimentAnalysisusingVADER BreakStatementinPython HandlingImbalancedDatainPythonwithSMOTEAlgorithmandNearMissAlgorithm GUICalculatorusingPython Sympymoduleinpython SmotePython Breadth-FirstSearchinPython PythonGraphviz:DOTLanguage HowtoVisualizeaNeuralNetworkinPythonusingGraphviz PythonGraphviz CompoundInterestGUICalculatorusingPython Rank-basedPercentileGUICalculatorinPython URLshortnerinPython AutomateInstagramMessagesusingPython PythonSimpleHTTPServerModule StandardGUIUnitConverterinPython PythonParamikoModule DispatchDecoratorsinPython IntrospectioninPython ClassDecoratorinPython CustomizingParserBehaviourPythonModule'configparser' Python'sModuleConfigparser GUICalendarusingTkinterinPython PythonProgramtoRotateanImage ValidatetheIPAddressinPython WriteaProgramtoPrinttheDiagonalElementsoftheGiven2DMatrix EncapsulationinPython PolymorphisminPython StringIOModuleinPython 10PythonImageManipulationTools Howtoinsertcurrent_timestampintoPostgresviaPython HowtoPerformaOne-WayANOVAinPython TypesofinheritancePython PythonForMechanicalEngineers PythonModulexxHash EscapeSequencesinPython PYTHONNULLSTATEMENT PythonANDOperator PythonOROperator PythonBitwiseXOROperator PythonNewLine __init__inpython __dict__inPython SimpleTo-DoListGUIApplicationinPython AutomateSoftwareTestingwithPython AutomatetheGooglesearchusingPython __name__inPython _name__main_inPython 8PuzzleprobleminPython accuracy_scoreinSklearn Pythonvs.Julia PythonCrontabModule PythonExecuteShellCommand FileExplorerusingTkinterinPython AutomatedTradinginPython PythonAutomationProjectIdeas K-means1DclusteringinPython Addingakey:valuepairtoadictionaryinPython fit(),transform()andfit_transform()MethodsinPython PythonForFinance LibrosaLibraryinPython PythonArtificialIntelligenceProjectsforBeginners AgeCalculatorusingTkinterinPython HowtoIterateaDictionaryinPython HowtoIteratethroughaListinPython HowtoLearnPythonOnline Cross-ValidationinSklearn PopularPythonLibrariesforFinanceIndustry FamousPythonCertification,CoursesforFinance Accuracy_ScoreinSklearn K-FoldCross-ValidationinSklearn PythonProjectsonMLApplicationsinFinance DigitalClockusingTkinterinPython PlotCorrelationMatrixinPython EuclidianDistanceusingNumPy HowtoParseJSONinPython HowtoMaketheFirstColumnanIndexinPython HowtoMakeanAppinPython MorseCodeTranslatorInPython PythonLocustModule PythonTimeModule SklearnLinearRegressionExample PythonTimeitModule PythonTkinter(GUI) PythonTkinter TkinterButton TkinterCanvas TkinterCheckbutton TkinterEntry TkinterFrame TkinterLabel TkinterListbox TkinterMenubutton TkinterMenu TkinterMessage TkinterRadiobutton TkinterScale TkinterScrollbar TkinterText TkinterToplevel TkinterSpinbox TkinterPanedWindow TkinterLabelFrame TkinterMessageBox PythonWebBlocker Introduction BuildingPythonScript ScriptDeploymentonLinux ScriptDeploymentonWindows PythonMCQ PythonMCQ PythonMCQPart2 RelatedTutorials NumPyTutorial DjangoTutorial FlaskTutorial PandasTutorial PytorchTutorial PygameTutorial MatplotlibTutorial OpenCVTutorial OpenpyxlTutorial PythonCGI PythonDesignPattern PythonPrograms PythonPrograms next→ ←prev HowtotakeMultipleInputfromUserinPython Itisacommonproblemforthebeginners.Itmayaskintheinterview.Sometimes,thedevelopersalsoneedtotakethemultipleinputsinasingleline.ItcanbeeasilydoneintheC/C++usingthescanf()method.However,Pythonprovidesthetwomethodsthathelpustotakemultiplevaluesorinputinoneline. Usingsplit()method UsingListComprehension Inthistutorial,wewilllearnhowtotakemultipleinputsinonelineusingvariousmethods. Usingsplit()Method Thesplit()methodisusefulforgettingmultipleinputsfromusers.Thesyntaxisgivenbelow. Syntax- input().split(separator,maxsplit) Parameters- Theseparatorparameterbreakstheinputbythespecifiedseparator.Bydefault,whitespaceisthespecifiedseparator. Thesplit()methodisusedtosplitthePythonstring,butwecanuseittogetthemultiplevalues. Let'sunderstandthefollowingexample. Example- #takingtwoinputsatatime a,b,c=input("Enterthreevalues:").split() print("EnterYourFirstName:",a) print("EnterYourLastName:",b) print("EnterYourClass:",c) print() #takingthreeinputsatatime x,y,z=input("Enterthreevalues:").split() print("Totalnumberofstudents:",x) print("Numberofpassedstudent:",y) print("Numberoffailedstudent:",z) print() #takingfourinputsatatime a,b,c,d=input("Enterfourvalues:").split() print("Firstnumberis{},secondnumberis{}thirdis{}andfourthis{}".format(a,b,c,d)) print() Output: Enterthreevalues:DavidWarnerMCA EnterYourFirstName:David EnterYourLastName:Warner EnterYourClass:Warner Enterthreevalues:1006733 Totalnumberofstudents:100 Numberofpassedstudents:67 Numberoffailedstudents:33 Enterfourvalues:1234 Firstnumberis1,secondnumberis2thirdis3andfourthis4 Entermultiplevalues:46724 Listofstudents:[4,6,7,2,4] Explanation- Intheabovecode,wetakethemultipleinputsinasingleline.Thevaluesareseparatedbythewhitespace,youcanusecomma(,)oranything. UsingListComprehension Wecanalsotakevaluesandconvertthemintothelistusingthemap()methodalongwiththesplit()method.Let'sunderstandthefollowingexample. Example-2: #Takingmultipleinputsinasingleline #andtypecastingusinglist()function x=list(map(int,input("Entermultiplevalues:").split())) print("Listofstudents:",x) Output: Entermultiplevalues:46724 Listofvalues:[4,6,7,2,4] Explanation- Weusedwhitespaceasaseparatorintheabovecodeandtakentheinputinonelineandtypecasteditintoalist. TakeMatrixInputfromUser Matrixisarectangulararray,orwecansayrectangulararrangementofdataornumbers.Thematrixcantakeanyvaluesuchasintegervalues,floatingvalues,string,complexnumbers,etc.Thevaluesareplacedhorizontallycalledrows,whileverticalvaluesarecalled'columns'.Ifthematrixconsistsofrnumberofrowsandcnumberofcolumns,theorderofthematrixwillberxc. Example- row=int(input("Enterthenumberofrows:")) column=int(input("Enterthenumberofcolumns:")) #Initializematrix matrix=[] print("Entertheentriesrow-wise:") #Foruserinput foriinrange(row):#Aforloopforrowentries a=[] forjinrange(column):#Aforloopforcolumnentries a.append(int(input())) matrix.append(a) #Forprintingthematrix foriinrange(row): forjinrange(column): print(matrix[i][j],end="") print() Output: Enterthenumberofrows:3 Enterthenumberofcolumns:3 Entertheentriesrow-wise: 1 2 3 4 5 6 7 8 9 123 456 789 Theabovecanbeimplementedintheonelineasbelow. Example- row=int(input("Enterthenumberofrows:")) column=int(input("Enterthenumberofcolumns:")) matrix=[[int(input())forxinrange(column)]foryinrange(row)] print(matrix) Output: Enterthenumberofrows:3 Enterthenumberofcolumns:3 1 2 3 4 5 6 7 8 9 123 456 789 Usingmap()functionandnumpyLibrary ThereisapopularlibrarycalledNumpywhichcanuseforanyscientificcomputation.Itprovidestheextensivesupportformultidimensionalarrays.Wewillusethislibraryforinputmatrix.Let'sunderstandthefollowingexample. Example- importnumpyasnp row=int(input("Enterthenumberofrows:")) column=int(input("Enterthenumberofcolumns:")) print("Entertheentriesinasingleline(separatedbyspace):") #Userinputofentriesina #singlelineseparatedbyspace entries=list(map(int,input().split())) #Forprintingthematrix matrix=np.array(entries).reshape(row,column) print(matrix) Output: Enterthenumberofrows:2 Enterthenumberofcolumns:2 Entertheentriesinasinglelineseparatedbyspace:1231 [[12] [31]] Conclusion Inthistutorial,wehaveshownthedifferentwaystotakemultiplevaluesfromtheuser.Itsavesthenumberofcodelinesandisquiteeasytouse.Wehavealsodescribedthesameasamatrixwherewecancreateauser-definematrix. NextTopicPythonzlibLibrary ←prev next→ ForVideosJoinOurYoutubeChannel:JoinNow Feedback SendyourFeedbackto[email protected] HelpOthers,PleaseShare LearnLatestTutorials Splunk SPSS Swagger Transact-SQL Tumblr ReactJS Regex ReinforcementLearning RProgramming RxJS ReactNative PythonDesignPatterns PythonPillow PythonTurtle Keras Preparation Aptitude Reasoning VerbalAbility InterviewQuestions CompanyQuestions TrendingTechnologies ArtificialIntelligence AWS Selenium CloudComputing Hadoop ReactJS DataScience Angular7 Blockchain Git MachineLearning DevOps B.Tech/MCA DBMS DataStructures DAA OperatingSystem ComputerNetwork CompilerDesign ComputerOrganization DiscreteMathematics EthicalHacking ComputerGraphics SoftwareEngineering WebTechnology CyberSecurity Automata CProgramming C++ Java .Net Python Programs ControlSystem DataMining DataWarehouse JavatpointServicesJavaTpointofferstoomanyhighqualityservices.Mailuson[email protected],togetmoreinformationaboutgivenservices.WebsiteDesigningWebsiteDevelopmentJavaDevelopmentPHPDevelopmentWordPressGraphicDesigningLogoDigitalMarketingOnPageandOffPageSEOPPCContentDevelopmentCorporateTrainingClassroomandOnlineTrainingDataEntryTrainingForCollegeCampusJavaTpointofferscollegecampustrainingonCoreJava,AdvanceJava,.Net,Android,Hadoop,PHP,WebTechnologyandPython.Pleasemailyourrequirementat[email protected]Duration:1weekto2weekLike/Subscribeusforlatestupdatesornewsletter
延伸文章資訊
- 1How to take Multiple Input from User in Python - Javatpoint
Using split() Method · # taking two inputs at a time · a, b, c = input("Enter three values: ").sp...
- 2Taking multiple inputs from user in Python - GeeksforGeeks
Using split() method : This function helps in getting multiple inputs from users. It breaks the g...
- 3How to take multiple inputs from user using for loop?
You can ask for a single input and then split it into words with the str.split() method # Get the...
- 4python multiple input - Me Gusta Aragón
Python answers related to "how to multiply inputs in python" input two numbers in python in a sin...
- 5Taking multiple inputs from user in Python - Prutor.ai
Using split() method : This function helps in getting a multiple inputs from user. It breaks the ...