How To Take Multiple Inputs In Python - Tutorial And Example

文章推薦指數: 80 %
投票人數:10人

How To Take Multiple Inputs In Python ... In C language, we make use of the scanf() function to obtain the values from the user and store it in ... PythonTutorial Introduction PythonFeatures PythonApplications PythonSystemRequirements PythonInstallation PythonExamples PythonBasics PythonIndentation PythonVariables PythonDataTypes PythonIDE PythonKeywords PythonOperators PythonComments PythonPassStatement PythonConditionalStatements PythonifStatement PythonelifStatement PythonIf-elsestatement PythonSwitchCase PythonLoops Pythonforloop Pythonwhileloop PythonBreakStatement PythonContinueStatement PythonGotoStatement PythonArrays PythonArray PythonMatrix PythonStrings PythonStrings PythonRegex PythonBuilt-inDataStructure PythonLists PythonTuples PythonListsvsTuples PythonDictionary PythonSets PythonFunctions PythonFunction Pythonmin()function Pythonmax()function PythonUser-defineFunctions PythonBuilt-inFunctions PythonRecursion Anonymous/LambdaFunctioninPython pythonapply()Function Pythonlambda()Function PythonFileHandling PythonFileHandling PythonReadCSV PythonWriteCSV PythonReadExcel PythonWriteExcel PythonReadTextFile PythonWriteTextFile ReadJSONFileinPython PythonExceptionHandling PythonExceptionHandling PythonErrorsandexceptions PythonAssert PythonOOPsConcept OOPsConceptsinPython Classes&ObjectsinPython InheritanceinPython PolymorphisminPython PythonEncapsulation PythonConstructor PythonSuperfunction PythonStaticMethod StaticVariablesinPython AbstractioninPython PythonIterators IteratorsinPython YieldStatementInPython PythonYieldvsReturn PythonGenerators PythonGenerator PythonDecorators PythonDecorator PythonFunctionsandMethods PythonBuilt-inFunctions PythonStringMethods PythonListMethods PythonDictionaryMethods PythonTupleMethods PythonSetMethods PythonModules PythonModules PythonDatetimeModule PythonMathModule PythonImportModule PythonTimeModule PythonRandomModule PythonCalendarModule CSVModuleinPython PythonSubprocessModule PythonSubprocess PythonMySQL PythonMySQL PythonMySQLClient UpdateOperation DeleteOperation DatabaseConnection CreatingnewDatabaseusingPythonMySQL CreatingTables PerformingTransactions PythonMongoDB PythonMongoDB PythonSQLite PythonSQLite PythonDataStructureImplementation PythonStack PythonQueue PythonLinkedList PythonHashTable PythonGraph PythonAdvanceTopics SpeechRecognitioninPython FaceRecognitioninPython PythonLinearregression PythonRestAPI PythonCommandLineArguments PythonJSON PythonVirtualEnvironment TypeCastinginPython PythonCollections PythonCommands PythonDataVisualization PythonDebugger PythonDefaultDict PythonEnumerate Python2 WhatisPython2 Python3 AnacondainPython3 Anacondapython3installationforwindows10 ListComprehensioninPython3 Misc PythonPPTX PythonPickle PythonSeaborn PythonCoroutine PythonEOL PythonInfinity Pythonmath.cosandmath.acosfunction PythonProjectIdeasBasedOnDjango ReverseaStringinPython ReverseaNumberinPython PythonWordTokenizer PythonTrigonometricFunctions Pythontrycatchexception GUICalculatorinPython Implementinggeometricshapesintothegameinpython InstallingPackagesinPython PythonTryExcept PythonSendingEmail SocketProgramminginPython PythonCGIProgramming PythonDataStructures Pythonabstractclass PythonCompiler PythonK-MeansClustering NSEToolsInPython OperatorModuleInPython PalindromeInPython PermutationsinPython PillowPythonintroductionandsetup PythonFunctionalitiesofPillowModule PythonArgmin Pythonwhois PythonJSONSchema Pythonlock ReturnStatementInPython ReverseasentenceInPython tell()functioninPython WhylearnPython? WriteDictionarytoCSVinPython WriteaStringinPython BinarySearchVisualizationusingPygameinPython LatestProjectIdeasusingPython2022 ClosestPairofPointsinPython ComboBoxinPython PythonvsR BestresourcestolearnNumpyandPandasinpython CheckLetterinaStringPython PythonConsole PythonControlStatements ConvertFloattoIntinPythonusingPandas Differencebetweenpythonlistandtuple ImportingNumpyinPycharm PythonKeyError PythonNewLine Pythontokensandcharacterset PythonStrongNumber any()Keywordinpython BestDatabaseinPython Checkwhetherdirisemptyornotinpython CommentsinthePythonProgrammingLanguage ConvertinttoFloatinPythonusingPandas DecisionTreeClassificationinPython EndParameterinpython __GETITEM__and__SETITEM__inPython PythonNamespace PythonGUIProgramming ListAssignmentIndexoutofRangeinPython ListIterationinPython ListIndexoutofRangePythonforLoop ListSubtractinPython PythonEmptyTuple PythonEscapeCharacters Sentencetopythonvector SlicingofaStringinPython ExecutingShellCommandsinPython GeneticAlgorithminpython Getindexofelementinarrayinpython LoopingthroughDataFrameinPython SyntaxofMapfunctioninPython AfterPythonWhatShouldILearn PythonAIOHTTP AlexaPython Artificialintelligenceminiprojectsideasinpython ArtificialintelligenceminiprojectswithsourcecodeinPython Findwhetherthegivenstringnumberispalindromeornot FirstUniqueCharacterinaStringPython PythonNetworkProgramming PythonInterface PythonMultithreading PythonInterpreter DataDistributioninpython Flutterwithtensorflowinpython Frontendinpython IterateaDictionaryinPython IterateaDictionaryinPython–Part2 Allocateaminimumnumberofpagesinpython AssertionErrorsandAttributeErrorsinPython CheckingwhetheraStringContainsaSetofCharactersinpython PythonControlFlowStatements *Argsand**KwargsinPython BarPlotinPython ConditionalExpressionsinPython Functionannotations()inPython HowtoWriteaConfigurationfileinPython ImagetoTextinpython import()FunctioninPython ImportpyfileinPython MultipleLinearRegressionusingPython NestedTupleinPython PythonStringNegativeIndexing ReadingaFileLinebyLineinPython PythonCommentBlock BaseCaseinRecursivefunctionpython ERdiagramoftheBankManagementSysteminpython ImagetoNumPyArraysinPython NOTINoperatorinPython OneLinerIf-ElseStatementsinPython SklearninPython CubeRootinPython PythonVariables,ConstantsandLiterals WhatDoesthePercentSign(%)MeaninPython CreatingWebApplicationinpython Notepad++ForPython PyPiTensorFlow Python|Readcsvusingpandas.read_csv() WhatisonlinepythonfreeIDE WhatisPythononlinecompiler RunexecpythonfromPHP WhatarethePurposesofPython PythonTernaryOperators SelfinPython PythonvsJava PythonModulo PythonPackages PythonSyntax PythonUses PythonBitwiseOperators PythonIdentifiers PythonMatrixMultiplication PythonANDOperator PythonLogicalOperators PythonMultiprocessing PythonUnitTesting __init__inPython AdvantagesofPython IsPythonCase-sensitivewhenDealingwithIdentifiers PythonBoolean PythonCallFunction PythonHistory PythonImageProcessing Pythonmain()function PythonPermutationsandCombinations DifferencebetweenInput()andraw_input()functionsinPython ConditionalStatementsinpython ConfusionMatrixVisualizationPython PythonAlgorithms PythonModulesList DifferencebetweenPython2andPython3 IsPythonCaseSensitive MethodOverloadinginPython PythonArithmeticOperators AssignmentOperatorsinPython IsPythonObjectOrientedProgramminglanguage DivisioninPython Pythonexitcommands ContinueAndPassStatementsInPython ColorsInPython ConvertStringIntoIntInPython ConvertStringToBinaryInPython ConvertUppercaseToLowercaseInPython ConvertXMLToJSONInPython ConvertingSetToListInPython CovarianceInPython CSVModuleInPython DecisionTreeInPython DifferenceBetweenYieldAndReturnInPython DynamicTypingInPython Howto HowtoSubstringaStringinPython HowtoIteratethroughaDictionaryinPython HowtoconvertintegertofloatinPython HowtoreverseastringinPython HowtotakeinputinPython HowtoinstallPythoninWindows HowtoinstallPythoninUbuntu HowtoinstallPIPinPython HowtocallafunctioninPython HowtodownloadPython HowtocommentmultiplelinesinPython HowtocreateafileinPython HowtocreatealistinPython HowtodeclarearrayinPython HowtoclearscreeninPython HowtoconvertstringtolistinPython HowtotakemultipleinputsinPython HowtowriteaprograminPython HowtocomparetwostringsinPython HowtocreateadictionaryinPython HowtocreateanarrayinPython HowtoupdatePython HowtocomparetwolistsinPython HowtoconcatenatetwostringsinPython HowtoprintpatterninPython Howtocheckdatatypeinpython Howtoslicealistinpython HowtoimplementclassifiersinPython HowToPrintColoredTextinPython Howtodevelopagameinpython Howtoprintinsamelineinpython Howtocreateaclassinpython Howtofindsquarerootinpython Howtoimportnumyinpython Howtoimportpandasinpython Howtouninstallpython HowtoupgradePIPinpython Howtoappendastringinpython Howtoopenafileinpython HowtoOpenafileinpythonwithPath HowtorunaPythonfileinCMD HowtochangethenamesofColumnsinPython HowtoConcattwoDataframesinPython HowtoIterateaListinPython HowtolearnpythonOnline HowtoMakeanAppwithPython Sorting PythonSortList SortDictionaryinPython Pythonsort()function PythonBubbleSort Programs FactorialPrograminPython PrimeNumberPrograminPython FibonacciSeriesPrograminPython LeapYearPrograminPython PalindromePrograminPython CheckPalindromeInPython CalculatorPrograminPython ArmstrongNumberPrograminPython PythonProgramtoaddtwonumbers AnagramPrograminPython NumberPatternProgramsinPython EvenOddPrograminPython GCDPrograminPython PythonExitProgram PythonProgramtocheckLeapYear OperatorOverloadinginPython PointersinPython PythonNotEqualOperator RaiseExceptioninPython SalaryofPythonDevelopersinIndia WhatisaScriptinPython HowToTakeMultipleInputsInPython 2022-03-1622:10:59 HowToTakeMultipleInputsInPython InClanguage,wemakeuseofthescanf()functiontoobtainthevaluesfromtheuserandstoreitinthevariable. ComingtothePythonlanguage,weusetheinput()functiontotaketheinputfromtheuser,andthenwefurtherapplyoperationsonthatvalue. Toaddtwonumbers,wespecifyvariablesa&bandthenusetheinput()functionforeachvariableforitsstorage. Inthisarticle,wewilldiscusshowwecantakemultipleinputsfromtheuserandthenproceedwithourobjective. So,inpython,wecantakemultipleinputsusing- split()Usinglistcomprehension Inthefirstexample,wehaveusedthesplit()functionwithinput().Withthehelpofthis,wecantakethreevaluesfromtheuseratatimeandthenprintthem. Followingprogramshowshowthreevalues(ages)aretakenatonce,andthentheagesarecompared. a,b,c=input("Entertheagesofa,bandc:").split() print("Valueofa:",a) print("Valueofb:",b) print("Valueofc:",c) if(a>banda>c):   print("{}isoldest".format(a)) elif(b>aandb>c):   print("{}isoldest".format(b)) else:   print("{}isoldest".format(c)) INPUT- OUTPUT- Onexecutingthegivencode,wecanobservethefollowingthingsintheoutput- Theuserhasprovidedthreevaluesforobjectsa,b,andcwhichareseparatedbyablankspace.Sincewehaveusedtheprintfunction,therespectivevaluesaredisplayed.Wehaveusedthedecision-makingif-elifinourprogram,sothevaluesarecomparedandtheexpectedresultisdisplayed. Inthenextexample,wewilltaketwovaluesfromtheuser(byusingthesplit()again)andthendisplaythevaluesofxandy. Followingprogramillustratesthesame- x,y=input("Enterthevaluesforxandy:").split() print("Valueofxis{}".format(x)) print("Valueofyis{}".format(y)) INPUT- OUTPUT- Intheoutput,wecanobservethattheexpectedresultsaredisplayed. Thenextexampleshowsaslightvariationofthepreviousprogram.Insteadofprintingthevaluesofaandbintwoseparatelines,wewillprinttheminthesameline. Followingprogramillustratesthesame- a,b=input("Enterthevaluesofaandb:").split() print("Thevaluesofaandbare{}and{}".format(a,b)) INPUT- OUTPUT- Intheaboveoutput,wehaveobservedthattheexpectedresultisdisplayed. Sofarthevaluesthataregivenbytheuserareofintegertype. Inthenextexample,wewillprovidestringvaluesandseewhathappens! Thefollowingprogramillustratesthesame- pc1,pc2=input("Enterthepossiblevalueswhenacoinistossed:").split() print("Thevaluesofpc1andpc2are{}and{}".format(pc1,pc2)) INPUT- OUTPUT- Onexecutingthegivencode,wecanobservethefollowingthingsintheoutput- Theuserhasprovidedtwostringvaluesforobjectspc1andpc2whichareseparatedbyablankspace.Sincewehaveusedtheprintfunction,thevaluesofpc1andpc2aredisplayedwhichareheadsandtailsrespectively. Weknowthatthemapfunctiontakesthesequenceandfunctionasitsparameters.Itappliesacertainfunctionalitytoalltheelementsofalist. Inthegivenexample,wehaveusedmapfunctionalongwithsplit()totakemultipleinputsfromtheuser. Followingprogramillustratesthesame- x=list(map(int,input("Enterthevalues:").split())) print("Elementsinxare:",x) print(type(x)) INPUT- OUTPUT- Onexecutingthegivencode,wecanobservethefollowingthingsintheoutput- Theuserhasprovidedmultiplevaluesforxwhichareseparatedbyablankspace.Sincewehaveusedtheprintfunction,alltheelementsofxaredisplayed.Thetypeofxis‘list’. Inthenextexample,wewillwriteourprograminastepwisemanner.First,wewilltakeourvaluesandthenapplythesplit()method. Followingprogramillustratesthesame- s_colors=input("Enterthevaluesseparatedwithaspace:") s_colors=s_colors.split() print(s_colors) INPUT- OUTPUT- Intheaboveoutput,theuserhasgivenfourstringvalues,sincethesplit()isusedintheprogram,alistisreturnedcontainingallthestrings. Thesecondmethodwewilldiscusstotakemultipleinputsisusingtheconceptoflistcomprehensionwhichmakesourprogrammoreprecise. Followingprogramillustratesthesame- #usinglistcomprehension  a,b=[int(a)foraininput("Enterthevalues:").split()] print("Thevalueofais{}".format(a)) print("Thevalueofbis{}".format(b)) INPUT- OUTPUT- Intheaboveoutput,wehaveobservedthattheexpectedresultsaredisplayed. Inthenextexample,wehaveusedthesplit()functionwithinput()insideourlistcomprehension.Withthehelpofthis,wecantakethreevaluesfromtheuseratatimeandthenprintthem. Followingprogramshowshowthreevalues(ages)aretakenatonce,andthentheagesarecompared. #usinglistcomprehension  a,b,c=[int(a)foraininput("Enterthevalues:").split()] print("Thevalueofais{}".format(a)) print("Thevalueofbis{}".format(b)) print("Thevalueofcis{}".format(c)) if(a>banda>c):   print("{}isoldest".format(a)) elif(b>aandb>c):   print("{}isoldest".format(b)) else:   print("{}isoldest".format(c)) INPUT- OUTPUT- Onexecutingthegivencode,wecanobservethefollowingthingsintheoutput- Theuserhasprovidedthreevaluesforobjectsa,b,andcwhichareseparatedbyablankspace.Sincewehaveusedtheprintfunction,therespectivevaluesaredisplayed.Wehaveusedthedecision-makingif-elifinourprogram,sothevaluesarecomparedandtheexpectedresultisdisplayed. Inthenextexample,wewillusethelistcomprehensionandtakemultiplevaluesfromtheuserandstoretheminx. #usinglistcomprehension  x=[int(x)forxininput("Entermultiplevalues:").split()]#enteringmultiplevalues  print("Thevalueofxis{}".format(x)) INPUT- OUTPUT- Intheaboveoutput,wehaveobservedthattheexpectedresultsaredisplayed. Sointhisarticle,welearnedhowmultipleinputscanbetakeninpythonusingsplit()andlistcomprehension. ADVERTISEMENT ADVERTISEMENT



請為這篇文章評分?