How to take multiple inputs from user using for loop?
文章推薦指數: 80 %
You can ask for a single input and then split it into words with the str.split() method # Get the input nums = input('Enter numbers ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams Howtotakemultipleinputsfromuserusingforloop? AskQuestion Asked 5monthsago Modified 5monthsago Viewed 453times 1 foriinrange(n-1): nums=int(input('Enternumbers:')) INPUT: Enternumbers:1 Enternumbers:2 Enternumbers:3 Enternumbers:4 ThisistheoutputIamgettingbutIwanttheoutputtobeinasingleline,numbersthatIamenteringshouldbeinasinglelinelike1234.Nocommasnoapostrophe Pleasetellanysolution python Share Improvethisquestion Follow editedMar11at0:54 BillLynch 77.5k1515goldbadges124124silverbadges170170bronzebadges askedMar10at23:52 YarKhanYarKhan 1122bronzebadges 3 Sorry,Iwanttoaskifyouwanttheoutputtohavenocommasandnoapostropheafterinputtingtheabove4numbers? – KevinChoonLiangYew Mar11at1:57 Iwanttotakemultipleinputslikeeg5inasingleattemptandaddthoseinputs – YarKhan Mar11at19:12 Youcanusejointogetyouroutput – KevinChoonLiangYew Mar11at23:52 Addacomment | 2Answers 2 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 2 Youcanaskforasingleinputandthensplititintowordswiththestr.split()method #Gettheinput nums=input('Enternumbers:') #Splitandmapto`int` nums=nums.split() nums=list(map(int,nums)) Share Improvethisanswer Follow answeredMar10at23:55 MateoVialMateoVial 62222silverbadges1111bronzebadges Addacomment | 0 Youcanappenditfirstintoalist defmyfunction(n): return[input('Enternumbers:'for_inrange(n-1)] numbers=myfunction(5) Enternumbers:1 Enternumbers:2 Enternumbers:3 Enternumbers:4 Andthen,youcanuse"".join(numbers) result="".join(numbers) print(result) 1234 Ifyoudonotevenwanttohavethespace: result2="".join(numbers) print(result2) 1234 Share Improvethisanswer Follow editedMar12at0:03 answeredMar11at1:53 KevinChoonLiangYewKevinChoonLiangYew 1,46933silverbadges2121bronzebadges 3 Anytimeyouhavethat"emptylist->looptoappend"patternyoushouldprobablybeusingalistcomprehensionorgeneratorexpression.num=[input('Enternumbers:'for_inrange(n-1)] – Chris Mar11at23:57 Thanks@Chris,Ihaveneverthoughtaboutitthatway!Willupdatemyanswer – KevinChoonLiangYew Mar12at0:02 Great!Butonlyuseitinyouranswerifyoureallyunderstandit. – Chris Mar12at16:58 Addacomment | YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonoraskyourownquestion. TheOverflowBlog Opensourceandaccidentalinnovation TheluckiestguyinAI(Ep.477) FeaturedonMeta Recentsiteinstability,majoroutages–July/August2022 PleasewelcomeValuedAssociate#1301-Emerson StagingGroundWorkflow:QuestionLifecycle Related 6420 HowdoImergetwodictionariesinasingleexpression? 2899 HowdoIsplitalistintoequally-sizedchunks? 3422 Convertbytestoastring 3969 Iteratingoverdictionariesusing'for'loops 3568 Catchmultipleexceptionsinoneline(exceptblock) 2108 WhyisreadinglinesfromstdinmuchslowerinC++thanPython? 3552 HowtoiterateoverrowsinaDataFrameinPandas 3112 HowdoIselectrowsfromaDataFramebasedoncolumnvalues? 2788 Whyis"1000000000000000inrange(1000000000000001)"sofastinPython3? HotNetworkQuestions WhyisiteasiertoraiseACcurrenttohighvoltagethanDC? Isacceptingadeferredprosecutionagreementanadmissionofguilt? Resistorinseries,orvoltagedivider? Dononconstructiveproofsofisomorphismexist? Howdoweensureanorbitofasatellitedoesn’tinterferewithexistingones? Algorithmwhichfindsthecountofvaluesaresmallertotherightthanthecurrentone(inthelist) WhyistherealongstarfieldsequenceatthestartofStarTrek:TheMotionPicture? Whydoes'onsteroids'suggestthemeaningofexaggerationorenhancement? Ispronouncingloanwordsaccordingtotheir"native"pronunciationstigmatisedacrossmostculturesandlanguages? WouldaRussianvisabanbecompliantwiththeUniversalDeclarationofHumanRights? Whatisthesignificanceofreachingmajorversion1.0.0? HowtoScalea"Player"CharactertoBeaVillain/Boss? Whataretheeffectsofmakingawomanaslightasaduck? Thedirtbikekidvideogame Canyouputapropelleronthebackofaplane,andhaveitgoforward? 織田信長pitchaccent Docompoundwordshaveanylogic? WhydoestheopposingforcedifferinwhenfallingonconcretevsonwaterinspiteofNewton'sthirdlaw? HowcomeCetaDiscipleisamerfolk? Whatdoesthissymbolonavoltmeterrepresent? Stoichiometriccoefficientsinreactionbetweenvanadium(II)oxideandiron(III)oxide Queriestogetproductsselectedinmultiplestores Iwitnessedmassivecasesofcorruptionandcheatinginmyuniversity.Nowwhat? HowdoIgetroundededgesonafootballshapeinInkscape? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-py Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1Multiple Inputs From User in Python | Python Input Program
With the help of the split () function, developers can easily collect multiple inputs in Python f...
- 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 input multiple values from user in one line in Python?
// Reads two values in one line. scanf ( "%d %d" , &x, &y) · x, y = input (), input (). Another s...
- 4How 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...
- 5How to Take Multiple Inputs From Users In Python
1. Using split() method ... This function helps in getting multiple inputs from users. It breaks ...