How to Take Multiple Inputs From Users In Python

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

1. Using split() method ... This function helps in getting multiple inputs from users. It breaks the given input by the specified separator. If a ... HomeAboutStackademicBlogNewsletterCommunityJobsPartnershipsContactAboutStackademicBlogNewsletterCommunityJobsPartnershipsContactHowtoTakeMultipleInputsFromUsersInPythonAllthewaysinwhichwecantakemultipleinputsfromusersinPythonByShelviGarghttps://linkedin.com/in/shelvi-garg-3a7421108July11th,2021 InPython,userscantakemultiplevaluesorinputsinonelinebytwomethods: Usingthesplit()method UsingListcomprehension 1.Usingsplit()method Thisfunctionhelpsingettingmultipleinputsfromusers.Itbreaksthegiveninputbythespecifiedseparator.Ifaseparatorisnotprovidedthenanywhitespaceisaseparator.Generally,usersuseasplit()methodtosplitaPythonstringbutonecanuseitfortakingmultipleinputs. Syntax: input().split(separator,maxsplit) separator:Thisisadelimiter.Thestringsplitsatthisspecifiedseparator.Ifisnotprovidedthenanywhitespaceisaseparator. maxsplit:Itisanumber,whichtellsustosplitthestringintoamaximumofprovidednumberoftimes.Ifitisnotprovidedthenthedefaultis-1whichmeansthereisnolimit. a)Takingtwoinputsatatime: a,b=input("Enter2variables").split() print("ais:",a) print("bis:",b) Enter2variableshithere ais:hi bis:therea,b=input("Enter2variables").split() print("ais:",a) print("bis:",b) Enter2variables3456 ais:34 bis:56 Note:Asyoucansee,theinputgivencanbeany:int,string,float,etc.Wehaven'tmentionedtheseparatorusedhencewhitespaceisconsideredasdefault. b)TakingInputswithSeparatorandMaxsplitdefined x,y,z=input("Entervariables:").split(",",3) print(x,y,z) Entervariables:how,are,you howareyoux,y,z=input("Entervariables:").split(",") print(x,y,z) Entervariables:how,are,you howareyou Note: Whetherornotmaxsplitwasdefined,theresultswerethesame.Forboththeabovecasesonly3inputs(notmoreorlesscanbeprovidedcorrespondingtodefinedvariables!) TakingUnlimitedInputs: x=input("Entervariables:").split(",") print(x) Entervariables:how,are,you,dear ['how','are','you','dear'] c)TakingMultipleInputsAsList Takingmultipleinputsatatimeandtypecastingusinglist()function. WithMapFunction: UsedMapFunction(Optional)toconvertthyinputintoaninteger. x=list(map(int,input("Entermultiplevalue:").split())) print("Listofstudents:",x) Entermultiplevalue:67908954123409 Listofstudents:[67,90,89,54,12,34,9] Fortheabovecode,becauseoftheuseofthemapintegerfunction,ourinputcanonlybeintegers. WithoutMapFunction: x=list(input("Entermultiplevalue:").split()) print("Listofstudents:",x) Entermultiplevalue:hey78amazingperson2021 Listofstudents:['hey','78','amazing','person','2021'] Note:Hereaswedidnotuseanymapfunction,thetypeofinputcanbeany! 2.UsingListComrehensions: 2InputataTime: x,y=[int(x)forxininput("Enter2values:").split()] print("xis",x) print("yis",y) Enter2values:678 xis6 yis78x,y=[int(x)forxininput().split()] print("xis",x) print("yis",y)7890 xis78 yis90 TakingMultipleInputsatatime: x=[int(x)forxininput().split()] print("Numberoflistis:",x)4312346709653232112 Numberoflistis:[43,12,34,67,9,653,2321,12] Theaboveexamplestakeinputseparatedbyspaces.Incasewewishtotakeinputseparatedbycomma(,),wecanusethefollowing. TakingUser-DefinedNumberofInputs: #InputsofNumberofinputsuserwanttoenter: n=int(input()) #definingempylist: L=[] #Takingmultipleinputsbasedonn: foriinrange(n): t=input().split() Theresultfortheabovecodewouldbealistwithnnumberofuserinputs. MultipleInputUsingSeparator x=[int(x)forxininput().split(",")] print("Numberoflistis:",x) 67,432,11,1,2,3,4 Numberoflistis:[67,432,11,1,2,3,4] SomeExtraCheese:UsingStrip()method strip()isaninbuiltfunctioninthePythonprogramminglanguagethatreturnsacopyofthestringwithbothleadingandtrailingcharactersremoved(basedonthestringargumentpassed). Syntax: string.strip([chars]), chars---astringspecifyingthesetofcharacterstoberemoved.Iftheoptionalcharsparameterisnotgiven,allleadingandtrailingwhitespacesareremovedfromthestring. Example: string="theKinghasthelargestarmyintheentireworldthe" #printsthestringafterremoving"the"frombeginningandend print(string.strip("the")) Kinghasthelargestarmyintheentireworld string=".theKinghasthelargestarmyintheentireworldthe." #printsthestringafterremoving".the"frombeginningandend print(string.strip(".the")) Kinghasthelargestarmyintheentireworld Thestripmethodcanmakeyourinputcleanremovingunnecessaryinputs. HopethissmalltutorialhelpedyoulearnhowtotakemultipleinputsinPython. Cheers!:) ShareonTwitter10SaaSToolsToImproveYourCompany'sProductivity8WebDesignTrendsUsedToCreateStandoutPlatformsin2022HowtocreateabasiccalculatorusingHTML,CSSandJavaScript30Highest-VotedPythonQuestionsonStackOverflowHowToAvoidPropDrillinginReactUsingComponentCompositionCreatingaConfirmDialoginReactandMaterialUI



請為這篇文章評分?