import random
def scramble(word):
"""This is the function to scramble 2 characters. It takes a single parameter word"""
l = len(word)
p1 = 0
p2 = 0
while p1 == p2:
"""I added this while loop just so that if the two characters to be switched cannot be the same"""
"""p1 and p2 are the 2 positions of characters to be switched. randrange will return random values in the given range"""
p1 = random.randrange(1, l-1)
p2 = random.randrange(1, l-1)
if word[p1] == word[p2]:
if l == 4:
"""If length of word equal 4 and the two characters in between are the same, then this loop will be infinite; So to avoid this case, I added this condition"""
break
p1 = p2
s = ""
"""The following function will create a new scrambled string (append the characters from word to an empty string except for the selected position, in that case, we switch the positions"""
for i in range(l):
if i == p1:
s += word[p2]
elif i == p2:
s += word[p1]
else:
s += word[i]
return s
str = input("Enter sentence/phrase: ")
l = str.split(' ')
"""str contains the input string and split function is used to split every word into a list of words in list l"""
newstr = ""
"""Below code is to call the scramble function for every word whose length is greater than 3 (if length of 3 and below cannot be scrambled) and append the words to a string and print it"""
for i in l:
if len(i) > 3:
newstr += scramble(i) + " "
else:
newstr += i + " "
print(newstr)
Task:
It can only prompt the user one time, how to make it prompt 3 times or more to ask the user to enter
sentence/phrases?