python 2.7 - Ask for user input in a while loop -
this example supposed 5 words, print them in reverse order.
this tried:
n = 5 while n > 0: print "tell me word", n word(n) = raw_input() n = n - 1 print r = 1 while r < 6: print word(r) r = r + 1 what correct way assign this?
you can using list.
words = [] python won't let assign using unassigned index, need call append method:
n = 5 words = [] while n > 0: words.append(raw_input('tell me word: ')) n -= 1 notice can use first argument raw_input print prompt, there's no need separately. can use quicker -= decrement , reassign n.
a while loop sort of unusual choice here, although works. you'd better off for loop using python's built-in range function.
for n in range(5): words.append(raw_input('tell me word: ')) once you're doing can shorten list comprehension , assign list @ once:
words = [raw_input('tell me word: ') n in range(5)] once you've got list it's pretty simple reverse it:
print list(reversed(words)) to print them 1 @ time (one per line) tried, you'd iterate on list such:
for word in reversed(words): print word if you'd rather them space-separated, python 2 uses kind of hack this: print trailing comma.
for word in reversed(words): print word, # note comma! i find python 3 version here lot more readable. can use doing from __future__ import print_function @ top of file:
for word in reversed(words): print(word, end=' ') note if (1.) has right @ top of file, , (2.) parentheses required on calls print (because it's function now).
full script example (python 2):
words = [raw_input('tell me word: ') n in range(5)] word in reversed(words): print word, ps - if you're learning python, why not use python 3?
words = [input('tell me word: ') n in range(5)] word in reversed(words): print(word, end=' ') print()
Comments
Post a Comment