Creation of a Function that transforms sentence in Python - python

So I am trying to create a function that calls two functions within the function where one function called "encode" checks if the first letter of a word is a vowel and if yes it will add "way" to the end of the word and if the word starts with a consonant it will move the first letter to the third position in the word and adds gar.
my problem is creating that function that calls from the encode function to read a sentence and change each word accordingly based on the first letter.
So here are some text cases for the function:
encode() function:
The output will look like this:
Please enter your message: python is fun
The secret message is: ythonpar isway unfar
translation is correct when words are separated by more than one space character.
Please enter your message: simple is better than complex
The secret message is: implesar isway etterbar hantar omplexcar
Here is my script. They are suppose to be connected.
def get_input():
user_input = input('Please enter a message: ')
more_message = True
while more_message:
user_input = input('Please enter a message: ')
if not user_input==' ':
more_grades = False
return
def starts_with_vowel(word):
while True:
data = word
the_vowel = "aeiou"
if word[0].lower() in the_vowel:
print ('true')
else:
print ('false')
return
def encode(word):
while True:
data = starts_with_vowel(word)
the_vowel = "aeiou"
if word[0].lower() in the_vowel:
new_word=word+'way'
print ('The secret word is:',new_word)
else:
new_word2=word+'ar'
scrambled_word=new_word2[1:-2]+new_word2[0]+new_word2[3]+new_word2[4]
print (scrambled_word)
print ('The secret word is:',new_word2)
return
def translate(text):
secret_message= encode(text)
return (secret_message)
translate('gin is a boy')

A better approach would be to use split on the sentence (input) and loop over the words:
vowels = 'aeiou'
sentence = 'python is fun'
new_words = []
for word in sentence.split():
if word[0].lower() in vowels:
new_words.append(word+'way')
else:
new_words.append(word[1:3]+word[0]+word[3:]+'gar')
' '.join(new_words)
'ytphongar isway unfgar'

I think in the first part of the code you will need to change the more_grades section with more_message, because first off more_grades has not been initialized and more_messages is controlling your loop so i think that's what you meant to do. Don't worry I believe that's only one error I have caught I will check the rest of the code and get back to you. Don't stress it.Happy coding :-)

Related

Can I print the input of a string for len not just the number of characters?

I'm trying to find find the longest string entered then print it as the output value. The program stops running when an 'a' has been entered then returns the longest string entered not just the numbers of characters in the string. Can the length function do this?
def longest_str(words):
words = len(words)
return words
true = 1
while true: # start loop
words = str(input("Enter a string: "))
words = words.lower()
if words.startswith('a'): #comparing if starts with a or A
print(f"The longest string was: {longest_str(words)}") # printing output
break #stop once reached a
else:
continue # continue to loop through, no a was found.
I understand what you are trying to do but you have several mistakes
while true: # start loop
words = str(input("Enter a string: "))
words = words.lower()
This will read only one word at the time.
So, your if will be executed only if you enter a word starting with 'a'.
This will solve your problem
def longest():
maxLength = 0
longestWord = ''
while(True):
word = str(input("Enter a string: "))
word = word.lower()
if word == 'a':
print(f"The longest string was: {longestWord}")
break
if len(word) > maxLength:
maxLength = len(word)
longestWord = word
Take a look at the differences
We check if the word entered is 'a', then print the longest string and stop.
If not, we check if the new word is longer than what we previously had (initialy nothing).If the new word is longer, we retain it to be able to print it.
Just call this in the main function.
If you want the string itself you could just do it like this:
longest_string = ''
while True:
word = input("Enter a string: ").lower()
if word == 'a': break
if len(word) > len(longest_string):
longest_string = word
print("The longest string was: " + longest_string)
Keep in mind, this will make ALL words lowercase, if you dont want that you have to remove the .lower()

Removing 1 letter each time from the word

I am trying to make a program that asks for a word, and then prints it to the console multiple times, each time removing the first character until the word ends. Program also asks if the word should be printed as shown or backwards.
The printing action is the same regardless if the word should be printed forwards or backwards.
The output should be something like this:
Give a word: milkfloat
Print forward? (yes/no): yes
milkfloat
ilkfloat
lkfloat
kfloat
float
loat
oat
at
t
Give a word: hippopotamus
Print forward? (yes/no): no
sumatopoppih
umatopoppih
matopoppih
atopoppih
topoppih
opoppih
poppih
oppih
ppih
pih
ih
h
I am trying but I cant figure out how to do it. Can anybody help?
Use the input() function to get some input from the command line e.g.
word = input('Enter word: ')
print(word)
>>> Enter word:
>>> Enter word: dog
>>> 'dog'
Use the print() function to print strings e.g.
word = 'dog'
print(word)
>>> 'dog'
Use an if statement to evaluate a condition e.g.
word = 'dog'
if word == 'dog':
print('I love dogs!')
elif word == 'cat':
print('I am more of a dog person...')
else:
print('Do you not like animals?')
>>> I love dogs!
Use [] square brackets to slice strings into the pieces you want e.g.
word = 'dog'
print(word[:-1])
>>> 'do'
print(word[1:])
>>> 'og'
Use the len() function to work out the length of a string e.g.
word = 'dog'
print(len(word))
>>> 3
Use a for loop with range() to do something a certain number of times e.g.
for i in range(3):
print(i)
>>> 0
>>> 1
>>> 2
I'll leave the rest to you.
def printer(word):
for i in range(len(word)):
print(word[i::])
text = input("Give a word: ")
forward = input("Print forward? (yes/no): ")
if forward=="yes":
printer(text)
else:
printer(text[::-1])
So this is something that I've set a friend to do as an exercise to get more comfortable with python.
The exercise is called "word pyramids" and this is the answer that I came up with (so that they have something to refer to later if they get stuck):
def print_backwards_word_pyramid(word):
for i in range(0, len(word)):
if i == 0:
print(word[::-1])
else:
print(word[:i-1:-1])
return
and this will print, for the word "juice"
eciuj
eciu
eci
ec
e
But, if you want something a little bit more elegant, the back half can be done as:
def print_backwards_word_pyramid(word):
for i in range(0, len(word)):
print(word[i:][::-1])
return
... which if read from right to left (for those who need a hand with what this is telling python) says:
In reverse, the slice starting at the "i'th" character, of the string value of variable "word", print.

Python Programming String Handling Functions

So, I'm a beginner to programming. I am trying to create a program where the user can input a sentence and the program will tell the user how many letters are in that sentence.
counter=0
wrd=raw_input("Please enter a short sentence.")
if wrd.isalpha():
counter=counter+1
print "You have" + str(counter) +"in your sentence."
When I enter this, my output is blank. What is my mistake in this program?
You need to indent code inside if blocks. In the code you have provided, you've forgotten to indent counter = counter + 1.
You are missing a loop across all characters of wrd. Try this instead,
counter = 0
wrd = raw_input("Please enter a short sentence.")
# Iterate over every character in string
for letter in wrd:
# Check if the letter is an alphabet
if letter.isalpha():
# Increment counter only in this condition
counter += 1
print "You have " + str(counter) + " in your sentence."
First of all as #kalpesh mentioned, the statement counter=counter+1 should be indented.
Second of all, you need to iterate over the entire string entered and then count the number of characters or whatever the logic you need.
counter=0
wrd=raw_input("Please enter a short sentence.")
for i in wrd:
if i.isalpha():
counter = counter+1
print "You have " + str(counter) +"in your sentence."
Once you start learning more, then you can use the below code,
counter=[]
count = 0
wrd=raw_input("Please enter a short sentence.")
counter = [len(i) for i in wrd.split() if i.isalpha()]
print "You have " + str(sum(counter)) +"in your sentence."
I am just splitting the word and then checking if it is alpha or not and using the list comprehension to iterate over the string entered.
wrd.isalpha() returns a boolean (true or false). So if the function returns true, counter=counter+1 will be called once (and only once). You need to iterate through every letter of wrd and call isalpha() on each letter.
You could always remove the spaces from your sentence using replace() then use len() to get how many characters are in the sentence.
For example:
sentence = input("Type in a sentence: ") # Ask the user to input a sentence
sentence = sentence.replace(" ", "") # Replace the spaces in the sentence with nothing
print("Your sentence is " + str(len(sentence)) + " characters long") # Use len() to print out number of letters in the sentence

Can't get program to print "not in sentence" when word not in sentence

I have a program that asks for input of a sentence, then asks for a word, and tells you the position of that word:
sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")
for i, word in enumerate(words):
if askedword == word :
print(i+1)
#elif keyword != words :
#print ("this not")
However I cannot get the program to work correctly when I edit it to say that if the input word is not in the sentence, then print "this isn't in the sentence"
Lists are sequences, as such you can use the in operation on them to test for membership in the words list. If inside, find the position inside the sentence with words.index:
sentence = input("enter sentence: ").lower()
askedword = input("enter word to locate position: ").lower()
words = sentence.split(" ")
if askedword in words:
print('Position of word: ', words.index(askedword))
else:
print("Word is not in the given sentence.")
With sample input:
enter sentence: hello world
enter word to locate position: world
Position of word: 1
and, a false case:
enter sentence: hello world
enter word to locate position: worldz
Word is not in the given sentence.
If you're looking to check against multiple matches then a list-comprehension with enumerate is the way to go:
r = [i for i, j in enumerate(words, start=1) if j == askedword]
Then check on whether the list is empty or not and print accordingly:
if r:
print("Positions of word:", *r)
else:
print("Word is not in the given sentence.")
Jim's answer—combining a test for askedword in words with a call to words.index(askedword)—is the best and most Pythonic approach in my opinion.
Another variation on the same approach is to use try-except:
try:
print(words.index(askedword) + 1)
except ValueError:
print("word not in sentence")
However, I just thought I'd point out that the structure of the OP code looks like you might have been attempting to adopt the following pattern, which also works:
for i, word in enumerate(words):
if askedword == word :
print(i+1)
break
else: # triggered if the loop runs out without breaking
print ("word not in sentence")
In an unusual twist unavailable in most other programming languages, this else binds to the for loop, not to the if statement (that's right, get your editing hands off my indents). See the python.org documentation here.

Python How to Stop my Loop

I made a program in python that basically gets each word from a sentence and puts them into a palindrome checker. I have a function that removes any punctuation put into the sentence, a function that finds the first word in the sentence, a function that gets the rest of the words after the first word of the sentence, and a function that checks for palindromes.
#sent = input("Please enter a sentence: ")#sent is a variable that allows the user to input anything(preferably a sentence) ignore this
def punc(sent):
sent2 = sent.upper()#sets all of the letters to uppercase
sent3=""#sets sent3 as a variable
for i in range(0,len(sent2)):
if ord(sent2[i])==32 :
sent3=sent3+sent2[i]
elif ord(sent2[i])>64 and ord(sent2[i])<91:
sent3=sent3+sent2[i]
else:
continue
return(sent3)
def words(sent):
#sent=(punc(sent))
location=sent.find(" ")
if location==-1:
location=len(sent)
return(sent[0:location])
def wordstrip(sent):
#sent=(punc(sent))
location=sent.find(" ")
return(sent[location+1:len(sent)])
def palindrome(sent):
#sent=(words(sent))
word = sent[::-1]
if sent==word:
return True
else:
return False
stringIn="Frank is great!!!!"
stringIn=punc(stringIn)
while True:
firstWord=words(stringIn)
restWords=wordstrip(stringIn)
print(palindrome(firstWord))
stringIn=restWords
print(restWords)
Right now I am trying to use the string "Frank is great!!!!" but my problem is that I'm not sure how to stop the program from looping. The program keeps getting the "GREAT" part of the string and puts it into the palindrome checker and so on. How do I get it to stop so it only checks it once?
you can stop it like that
while True:
firstWord=words(stringIn)
restWords=wordstrip(stringIn)
#if the word to processed is the same as the input word then break
if(restWords==stringIn) : break
print(palindrome(firstWord))
stringIn=restWords
print(restWords)

Categories

Resources