Write a program that gets a string from the user and assign it to a variable nam
ID: 3803835 • Letter: W
Question
Write a program that gets a string from the user and assign it to a variable named prefixes. Then prompts the user to enter in a string for a variable called suffix. Create function called prefixNsuffix that will accept two parameters, and concatenate each letter in prefixes with the suffix. You program should remove any whitespace, Example Sample Input: prefixes = “ ertrTgdf tr ” suffix = “own” Sample Output: Letter Prefix & suffix -------------------------- E Eown R Rown T Town R Rown T Town G Gown D Down F Fown T Town R Rown Program Logic Shell def main(): # Get user input #print table header #call prefixNsuffix function #Define prefixNsuffix function def prefixNsuffix(pre,suf): #for each letter in prefixes concatenate it with the suffix # Call the main function. main()
Explanation / Answer
The given program logical structure:
def main():
# Get user input
#print table header
#call prefixNsuffix function
#Define prefixNsuffix function
def prefixNsuffix(pre, suf):
#for each letter in prefixes concatenate it with the suffix
# Call the main function.
main()
Let's fill out each part.
# Get user input :
We use raw_input function to get input from the user. So do it as,
prefixes = raw_input("Prefixes = ")
suffix = raw_input("Suffix = ")
#print table header : Use print function to print to the output.
print "Letter Prefix & suffix"
print "--------------------------"
#call prefixNsuffix function : Its simply like prefixNsuffix(prefixes, suffix)
#Define prefixNsuffix function :
We first need to remove all the spaces from the prefixes, we can do that replace function as prefixes.replace(" ", ""). This will replace all the whitespace characters by empty string and hence removes the whitespace characters.
Now we have to convert the resulting string to Uppercase since each letter in prefixes needs to be printed and concatenated with suffix in uppercase as shown in the sample output in the question. We can use upper function to do that.
#for each letter in prefixes concatenate it with the suffix : This can be done with a for loop. Concatination in python is done with the "+" operator.
Stitching togrther the final code will be as follows:
def main():
# Get user input
prefixes = raw_input("Prefixes = ")
suffix = raw_input("Suffix = ")
#print table header
print "Letter Prefix & suffix"
print "--------------------------"
#call prefixNsuffix function
prefixNsuffix(prefixes, suffix)
#Define prefixNsuffix function
def prefixNsuffix(pre, suf):
#for each letter in prefixes concatenate it with the suffix
for letter in pre.replace(" ", "").upper():
print "%s %s" % (letter, letter + suf)
# Call the main function.
main()
Put the above code in a python file (.py extension) and execute it.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.