Python Codeacademy: Making a list with a string - python

I'm pondering if I could convert this line of code into a list for all these vowels;
if first== 'a' or first =='e' or first == 'i' or first == 'o' or first =='u':"
I'm thinking str[a,e,i,o,u]
pyg = 'ay'
first = original[0]
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
print original.lower()
if first== 'a' or first =='e' or first == 'i' or first == 'o' or first =='u':
print "vowel"
else:
print "consonant"
else:
print 'empty'
word = original

if first.lower() in ['a','e','i','o','u']:
print "vowel"
else:
print "consonant"
I think the word you are looking for (Beuller) is Boolean?

You can use a string instead of a list:
if first in "aeiou":
print "vowel"
else:
print "consonant"
Bear in mind that your current code prints the first letter in lowercase, but doesn't actually change it to lowercase. You could use:
if first.lower() in "aeiou":

In Python, str types are like list types in many ways. One of those ways is that the simple and succinct in keyword works just fine for testing membership in both.
pyg = 'ay'
first = original[0]
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
print original.lower()
if first in 'aeiou':
print "vowel"
else:
print "consonant"
else:
print 'empty'
word = original

You have a few problems here:
first = original[0]
original = raw_input('Enter a word:')
You're trying to access original before it's defined, this is a simple fix, as it says in the comment (+1 DaoWen), just swap those two lines.
However, then you check to make sure something was entered:
if len(original) > 0
But by then, if original doesn't pass that statement, it will have thrown an error with first = original[0], so it may be better to hold off assigning first until you're in the if block:
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
print original.lower()
first = original[0].lower()
if first in ['a','e','i','o','u']: print "vowel"
else: print "consonant"
else:
print 'empty'
word = original

Related

Editing a String without Python Commands (with "for i in range")

For an assignment, I need code that asks the user for a word and a letter. Then, it edits the word to not include the specific letter. It needs in include a "for i in range" statement. The code before works but doesn't use a for loop and uses a python command.
word1 = raw_input ("Give me a word! ")
letter1 = raw_input ("Give me a letter! ")
modify = word1.replace(letter1,"")
check = word1.find(letter1)
if check == -1:
print "There is no letters to replace in", word1
check = 0
if check >= 1:
print modify
How about:
word = raw_input('Give me a word! ')
letter = raw_input('Give me a letter! ')
cleaned = ''
for i in range(len(word)):
if word[i] != letter:
cleaned += word[i]
if cleaned:
print cleaned
else:
print 'There is no letters to replace in', word
You can iterate through a string letter by letter like you would a list or dict
word='someword'
for letter in word:
print(letter)

Using next string in list in function: python

Using the Codecademy pyglatin.py translator as an example, I am trying to expand the translator to include multiple words at a time.
So far, it reads the first word and translates it, and I would like to continue onto the next word, and then the next, until no more words exist. I would then like to print the entire original translated input.
def piglatin():
pig = 'ay'
original = raw_input('Enter a phrase:').split(' ')
if len(original[0]) > 0 and original[0].isalpha():
word = original[0].lower()
first = word[0]
if first == "a" or first == "e" or first == "i" or first == "o" or first =="u":
new_word = word + pig
print new_word
else:
new_word = word[1:] + word[0:1] + pig
print new_word
again = raw_input('Translate again? Y/N')
print again
if len(again) > 0 and again.isalpha():
second_word = again.lower()
if second_word == "y":
return piglatin()
else:
print "Okay Dokey!"
else:
print 'Letters only please!'
return piglatin()
Thanks!
You want a for loop. A good starting point would be:
for word in original:

My program works but Codeacademy does not acknowledge

Here is my code for the pig latin translator. It works both on Code academy and in linux terminal.
pyg = 'ay'
new_word = pyg
original = raw_input('Enter a word: ')
if len(original) > 0 and original.isalpha():
original.lower()
word = original
first = original[0]
if first == 'a' or first =='e' or first == 'i' or first =='o' or first == 'u':
print 'vowel'
elif first != 'a' or first !='e' or first !='o' or first !='i' or first !='u':
print word.lower()[1:] + first +new_word
else:
print 'empty'
Code academy gives following result;
Oops, try again! Your word started with a consonant, but “ay' was printed instead of “ogday”. Make sure the correct value #is stored in “new_word”.
"ay" is not printed but "ogday' is printed.
Does anyone know how to fix this? I cannot continue with Codeacademy as without solving this.
You can do something like this for example. You are in the right track just use what you have learned in the Code academy up to this task.
consonants = "bcdfghjklmnpqrstvxz"
original = raw_input('Enter a word: ')
if len(original) > 0 and original.isalpha():
if original.lower()[0] in 'aeiou':
print original.lower() + 'ay'
else:
keep_first_consonants = ''
count = 0
for letter in original.lower():
if letter in consonants:
keep_first_consonants = keep_first_consonants + letter
count += 1
else:
break
total_characters = len(original.lower())
print original.lower()[count:total_characters] + keep_first_consonants + 'ay'
else:
print 'Accept only letters'
The codeacademy lesson checker seems to check the variable new_word when you hit run
So you just need to use new_word for both your print varibles
This code works:
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
if first == "a" or first == "e" or first == "i" or first == "o" or first == "u":
new_word = original + pyg
print new_word
else:
newer_word = word[1:]
new_word = newer_word + first + pyg
print new_word

Recursive Program: What am I doing wrong?

I am trying to write a code that would analyze if a word is a palindrome.
BTW a palindrome is a word that is read the same backward and forward. Example are "madam" or "noon"
Here is a try:
x = raw_input("please enter a word:\n")
L = len(x)
# this part returns the first letter of the word
def first(word):
return word[0]
# this part returns the last letter of the word
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def is_palindrome(word):
if L <= 2:
print 'enter a word with at least three letters'
elif first(word) != last(word):
print 'This word is not a palindrome'
else:
word = middle(word)
is_palindrome(word)
is_palindrome(x)
But when executed, I get
IndexError: string index out of range
...line 7, in first return word[0]
The first branch of "is_palindrome" works perfectly. i.e. when the word is not a palindrome, I get no errors. Like "noopn" is executed with no errors, but the error is in the second branch
I've playing with this code for so many times but can't figure out the "iterative part" I have the answer but I don't want to look at it yet. I need to figure out two things:
1. a way to make the iteration in the function is_palindrome work correctly?
and 2. a way to exit the program in the end.
Could you folks direct me to how to answer these questions without providing the solution yet?
Finally where should I put the print statement: print 'This word is a palindrome'
Thank you
To accomplish your goal, why don't just use:
string[::-1] == string
And the reason for your answer is when there is only 1 letter, middle will return an empty string and then ''[0] will cause the error.
You need a base case for your recursion. A one letter word is a palindrome, and an empty string is also a palindrome.
def is_palindrome(word):
# handle the base case
if len(word) <= 1:
print 'This word is a palindrome'
elif first(word) != last(word):
print 'This word is not a palindrome'
else:
word = middle(word)
is_palindrome(word)
If you want to reject words with fewer than three letters, then you can use a helper function that calls the recursive function:
def is_palindromeHelper(word):
if len(word) <= 2:
print 'enter a word with at least three letters'
else:
is_palindrome(word)
Personally, I would prefer separating the check and the output. So is_palindrome() should just return the answer and not be responsible for telling the user. That makes it more reusable.
def is_palindrome(word):
# handle the base case
if len(word) <= 1:
return True
elif first(word) != last(word):
return False
else:
word = middle(word)
return is_palindrome(word)
This enables you to do
x = raw_input("please enter a word:\n")
L = len(x)
if L <= 2:
print 'enter a word with at least three letters'
elif is_plaindrome(word):
print 'This word is a palindrome'
else:
print 'This word is not a palindrome'
This puts the validity check to the front of the execution, while in the recursion, you have only the checks which are valid all over the recursion.
(I doubt if your check is necessary at all - are y and oo no palindromes? We could argue about the empty string, however...)
The next improvement steps could be to omit the functions first(), last() and middle() - they are trivial and only used once, so you could put there code where they are used.
Added an extra condition in your code , which will solve your problem. You don't need to call is_palindrome() , when you have just a single character left
x = raw_input("please enter a word:\n")
L = len(x)
# this part returns the first letter of the word
def first(word):
return word[0]
# this part returns the last letter of the word
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
def is_palindrome(word):
if L <= 2:
print 'enter a word with at least three letters'
elif first(word) != last(word):
print 'This word is not a palindrome'
else:
word = middle(word)
if len(word) > 1:
is_palindrome(word)
else:
print 'This word is a palindrome'
is_palindrome(x)
A basic version without considering capitalization and white-space, I'd suggest:
def is_palindrome(word):
if len(word) < 3:
print 'Enter a word with at least three letters'
else:
for letter in range(len(word)/2):
if word[letter] != word[-letter - 1]:
print "This word is not a palindrome"
return
print "This word is a palindrome"
Though I think it might personally remove white space and make the comparisons using .lower(). Then it will be case insensitive and allow for testing a phrase or sentence also.
Great directions guys. All got an upvote.
These directions allowed me to make the following concise codes
Code 1
x = raw_input("enter a word to check if it is a palindrome:\n")
if x[::-1] == x:
print 'yes this one is a palindrome'
else:
print 'sorry try again by re-running the program'
Code 2
x = raw_input("enter a word to check if it is a palindrome:\n")
if len(x) <= 1:
print 'Of course ', x, ' is a palindrome'
def is_palindrome(x):
if len(x) >= 2:
if x[0]!=x[-1]:
print 'This is not a palindrome'
else:
x = x[1:-1]
return is_palindrome(x)
print 'This is FINALLY a real palindrome'
is_palindrome(x)
I guess I could include the function is_palindrome as a second branch of the conditional statement len(x) <= 1, but I like it better this way since the code is all about this function

checking if the first letter of a word is a vowel

I am trying to use python to write a function that checks whether the first letter of a given word, for instance "ball" is a vowel in either uppercase or lowercase. So for instance:
#here is a variable containing a word:
my_word = "Acrobat"
#letters in vowel as a list
the_vowel = ["a","e","i","o","u"]
How do a check that the first letter in "Acrobat" is one of the vowels in the list? I also need to take into consideration whether it is upper or lowercase?
try my_word[0].lower() in the_vowel
I don't know if it is better than the answers already posted here, but you could also do:
vowels = ('a','e','i','o','u','A','E','I','O','U')
myWord.startswith(vowels)
Here are some hints to help you figure it out.
To get a single letter from a string subscript the string.
>>> 'abcd'[2]
'c'
Note that the first character is character zero, the second character is character one, and so forth.
The next thing to note is that an upper case letter does not compare equal to a lower case letter:
>>> 'a' == 'A'
False
Luckily, python strings have the methods upper and lower to change the case of a string:
>>> 'abc'.upper()
'ABC'
>>> 'a' == 'A'.lower()
True
To test for membership in a list us in:
>>> 3 in [1, 2, 3]
True
>>> 8 in [1, 2, 3]
False
So in order to solve your problem, tie together subscripting to get a single letter, upper/lower to adjust case, and testing for membership using in.
my_word = "Acrobat"
the_vowel = "aeiou"
if myword[0].lower() in the_vowel:
print('1st letter is a vowel')
else:
print('Not vowel')
My code looks like this.
original = raw_input("Enter a word:")
word = original.lower()
first = word[0]
vowel = "aeiou"
if len(original) > 0 and original.isalpha():
if first in vowel:
print word
print first
print "vowel!"
else:
print word
print first
print "consonant
x = (input ("Enter any word: "))
vowel = "aeiouAEIOU"
if x[0] in vowel:
print ("1st letter is vowel: ",x)
else:
print ("1st letter is consonant: ",x)
Here's how I did it since the inputted word needs to be checked first before storing it as a variable:
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
if first in ['a','e','i','o','u']:
print "vowel"
else:
print "consonant"
else:
print 'empty'
changes:
if my_word[0] in ('a','e','i','o','u'):
print(' Yes, the first letter is vowel ')
else:
print(' No, the first letter is not vowel ')
So, Here is the simple code for finding out that the first letter is either vowel or not!! If you have any further query in python or js, then comment it down.
import ast,sys
input_str = sys.stdin.read()
if input_str[0] in ['a','e','i','o','u','A','E','I','O','U']:
print('YES')
else:
print('NO')
Here is the solution to the exercise on codecadmy.com:
original = raw_input('Enter a word:')
word = original.lower()
first = word[0]
vowel = "aeiou"
if len(original) > 0 and original.isalpha():
if first in vowel:
print 'vowel'
else:
print 'consonant'
else:
print 'empty'
Will it not be (slightly) faster to define the_vowel as a dictionary than a list?
the_vowel = {"a":1,"e":1,"i":1,"o":1,"u":1}
my_word[0].lower() in the_vowel
anti vowel Function
def anti_vowel(text):
vowel = ["a","e","i","o","u"]
new_text = ''
for char in text:
if char.lower() in vowel:
continue
else:
new_text += char
print new_text
return new_text
x = raw_input("Enter a word: ")
vowels=['a','e','i','o','u']
for vowel in vowels:
if vowel in x:
print "Vowels"
else:
print "No vowels"
This would print out 5 lines, if any of those includes a line that says Vowels then that means there is a vowel. I know this isn't the best way but it works.
Let's do it in more simply way
def check_vowel(s1):
v=['a','e','i','o','u']
for i in v:
if s1[0].lower()==i:
return (f'{s1} start with Vowel word {i}')
else:
return (f" {s1} start with Consonants word {s1[0]}")
print(check_vowel("orange"))
inp = input('Enter a name to check if it starts with vowel : ') *# Here we ask for a word*
vowel = ['A','E','I','O','U', 'a','e','i','o','u'] *# This is the list of all vowels*
if inp[0] in vowel:
print('YES') *# Here with the if statement we check if the first alphabet is a vowel (alphabet from the list vowel)*
else:
print('NO') *# Here we get the response as NO if the first alphabet is not a vowel*
my_word = "Acrobat"
the_vowel = ["a", "e", "i", "o", "u"]
if my_word[0].lower() in the_vowel:
print(my_word + " starts with a vowel")
else:
print(my_word + " doesnt start with a vowel")
input_str="aeroplane"
if input_str[0].lower() in ['a','e','i','o','u']:
print('YES')
else:
print('NO')
Output will be YES as the input string starts with a here.

Categories