Sign in to follow this  

Python ?

This topic is 3568 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If im wanting to print a word that is input by the user in random order. For example the word "hello" printed like "llohe". How could I does this?

Share this post


Link to post
Share on other sites
You probably wouldn't actually print the word in random order, rather you'd scramble the word and then print it. To scramble the word would be to run the string through a loop that would randomly choose 2 characters from that string and swap them. Do this a few times, then print out the scrambled word.

If you're looking for Python code, I can't help you there, but that would be the process for something like this.

Share this post


Link to post
Share on other sites
The random.shuffle method will shuffle the elements of a sequence in random manner, but it requires that the sequence support item assignment, which means you can't pass a string to it. Fortunately, converting a string to a list is trivial, as is converting a list to a string:
import random

random.seed()

def shuffle(word):
word = list(word)
random.shuffle(word)
return ''.join(word)

if __name__ == '__main__':
word = raw_input("Please enter a single word:")
print "Your word, shuffled, is", shuffle(word)

Share this post


Link to post
Share on other sites
it means the code will only execute when the program is called as a script, like

python script.py


and not when it is imported, this a good way to test modules

Share this post


Link to post
Share on other sites
In a nutshell, python files are usually executed in two ways: when run from the command line like python myscript.py or when imported. The if __name__ == '__main__': causes the following code to be executed only if the script isn't being imported.

Share this post


Link to post
Share on other sites

This topic is 3568 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this