def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "Q"
else:
translation = translation + "q"
else:
translation = translation + letter
return translation
print(translate(input("Enter phrase to translate: ")))
Hi, I'm new to Python and this is my first post here. I'm following a Python tutorial and I'm a little confused, this code executes fine, I'm just wondering why the following code works:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "Q"
If letter.lower converts each letter in sequence to a lower case, how could the next if statement return anything for letter.isupper?
If the phrase is "AaAa", wouldn't letter.lower() convert that to aaaa first, before checking the letter.isupper, meaning nothing could be isupper? Yet, it still works, and AaAa returns QqQq.
Also, is my formatting correct for posting the code on here? I just pasted it and clicked the bracket button.
Thanks
The lower method'1 only returns a lowercase letter (or the original string if there is no lowercase version); it does not change letter itself.
>>> letter = 'A'
>>> letter
'A'
>>> letter.lower()
'a'
>>> letter
'A"
lower() will return the lowercase character and you are checking if its a vowel. The letter itself is not changed e.g. A will remain as A
if letter.lower() in "aeiou":
The next line you are checking if its in upper case using isupper to add uppercase Q else lowercase q
if letter.isupper():
Don't get confused .I will make you very clear with your codes.
Please follow the steps below:-
1.your code:
if letter.lower() in "aeiou":
if letter.isupper():
translation=translation + "Q"
else:
translation=translation + "q"
In the first line of above code ,first of all you converted the letter(it can be in uppercase or lowercase) to lowercase.Then you checked that if it is in "aeiou" or not ,if the letter is there in "aeiou" then next if statement will get executed.
Now plese note that the letter you converted in the first line to lowercase remains in lowercase upto the execution of first line only,it means that the role of original case of the letter(case of letter while inputting it ) comes in account from second line,it also mean that the isupper() function do not change the case of the letter permanently.
3.According to your input "AaAa".First the letter 'A' will get converted into 'a' and as
'a' is there in "aeiou" control of program will go to second 'if' statement and there your letter is "A"(original case while input) so you get 'Q' as the result of 3rd statement and then this process continues for all letter("AaAa") and your output is "QqQq".
For more clarification of your doubt please refer to the code below and you will never stuck in this problem anymore:-
s="AaAa"
for letter in s:
print(letter.lower())
print(letter)
output:
a
A
a
a
a
A
a
a
ya you are correct with your formatting of code .You can post your question in a more better way but the way you have posted is also fine.
Related
Why is the variable "translation" assigned to an empty string? Is that because we are going to replace it with the user's input?
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "G"
else:
translation = translation + "g"
else:
translation = translation + letter
return translation
print (translate(input("Enter a phrase: ")))
In line 6 you have:
translation = translation + "G"
This tries to set translation to whatever string it previously was, but with G at the end. However, at the very start of the loop, what value is translation? How can we add something to it if it doesn't exist yet?
We need to initialize it so that things can be added onto it. That's what setting it to an empty string before the loop is doing.
You're appending "g" and "G" to it. If you don't initialize it, what would you be appending to? - Aplet123
You are doing + to the variable. if you don't initialize it, you'll get UnboundLocalError.
And if you initialize it in the for loop, it will keep resetting the value.
That's why you are assigning at the first part of the function.
And btw, you can use +=
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation += "G"
else:
translation += "g"
else:
translation += letter
return translation
print (translate(input("Enter a phrase: ")))
When a variable is assigned, it gets stored somewhere in the memory with an address. If you don't initialize(define) any location for data, how is it supposed to work?
def translate(phrase):
translation= ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "G"
else:
translation = translation + "g"
else:
translation = translation + letter
return translation
print(translate(input("Enter a phrase: ")))
(This is a program to change vowels to the letter 'g' or 'G' depending if it is upper or lower case)
Why does this work? Since there is a letter.lower() shouldn't it transform that letter to a lowercase one? that way the next if statement ("if letter.isupper():") would never be true...
I'm confused because I only know C and I'm trying to learn Python. In C if I did that it would transform the letter variable to a lower case one so the next if statement would never be true. I'm guessing that functions inside if statements in Python don't change/alter the variables inside those same fucntions...? But then again that wouldn't really make sense to me... What am I thinking wrong?
From https://docs.python.org/3/library/stdtypes.html#str.lower:
Return a copy of the string with all the cased characters converted to lowercase.
letter.lower() does not modify letter when called, it returns a new value.
I wanted to create a translator, so I looked at some videos online and found one that showed how to substitute certain letters in a sentence and turn them into other letters/symbols. I tried doing it and it worked. But once I started adding new other letters for it to look for. It started printing the letter that was supposed to have been substituted.
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "ㅏ": #if ㅏ then A
translation = translation + "A"
if letter in "Б": #if Б then B
translation = translation + "B"
else:
translation = translation + letter
return translation
print(translate(input("Enter a phrase: ")))
I am planning on adding the whole alphabet, so I can't have it print the unwanted "supposed to have been substituted letter". I have tried all I can. But I simply can't get it to work. Any thoughts?
You need to combine the if statements like so:
if letter in "ㅏ": #if ㅏ then A
translation = translation + "A"
elif letter in "Б": #if Б then B
translation = translation + "B"
else:
translation = translation + letter
Otherwise you'll be hitting the else branch for every character other than Б (and that includes ㅏ!)
It might be worth noting that letter in "ㅏ" can be written more simply as letter == "ㅏ". The same goes for the other comparison.
Finally, you might also want to take a look at maketrans() and translate(): https://www.tutorialspoint.com/python3/string_maketrans.htm
I'm trying to write a program that takes in a string(sentence) and after each vowel it adds a letter for example: "Jon" becomes "Jofon". I thought doing it with for loops maybe(certainly) there is a better way.
Here it's what I tried so far:
sen="Jon"
newString=""
for letter in sen:
if letter == "a" or letter == "e" or letter == "i" or letter == "o" \
or letter == "u" or letter == "y":
newString+=letter+"f"+letter
print(newString)
It seems to add the letter "f" only to vowels leaving consonants out giving me this result:
ofo
Of course, since there's no fallback for when it's not a vowel... You need an else:
for letter in sen:
if letter in "aeiouy":
newString+=letter+"f"+letter
else:
newString+=letter
(doesn't handle the case where the letters are uppercased BTW)
But there are more efficient (and pythonic ways) of doing it. Concatenating strings is underperformant, and this kind of problem is better solved using comprehensions or regular expressions.
In one line, using ternary and list comprehension, passed to "".join:
newstring = "".join(["{0}f{0}".format(letter) if letter.lower() in "aeiouy" else letter for letter in sen])
Alternative with regular expressions, capturing the vowel as a group and using it twice to wrap the f char against recalled group (\1) using raw prefix or \1 is interpreted as ASCII character \x01 instead:
re.sub("([aeiouy])",r"\1f\1","Jon",flags=re.IGNORECASE)
that finds a vowel, and replaces it by this vowel + f + this vowel again.
THe rules for the pig latin sentences are:
1.for words beginning with consonants, all letters before the first vowel are moved to the end of the word, and is further appended by 'ay'
2.for words that begin with vowels, the word is appended by 'hay'
3.for words that do not contain a vowel, the first letter is moved to the end of the word and is appended with 'way'
4. all non characters (i.e., numbers, symbols) are ignored
The main part of the code executes an infinite loop that takes a string input from the user, invokes the pigLatin function and prints the result returned. The pigLatin function receives a list of words as its input and converts them to pig latin using the rules above. The main part exits when the user input "Quit this program" as the input sentence for conversion. Verify your program for all cases (including invalid inputs) and save your program.
I find it very difficult to solve rule 3. As I test the code, the out put isn't correct...
I struggle it for the whole night and couldn't sleep....Please help
Here is my code:
enter code here
sentence=input('input:')
VOWELS=['a','e','i','o','u']
CONSONANTS=['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
def pigLatin():
t=-1
for word in newsentence:
if word[0] in CONSONANTS:
if 'a'and'e'and'i'and'o'and'u' not in word[1:]:
print(word[1:]+word[0]+'way',end=' ')
for u in word:
t +=1
if u in VOWELS:
print (word[t:]+word[0:t]+'ay',end=' ')
break
elif word[0] in VOWELS:
print (word[0:]+'hay',end=' ')
else:
print (word[0:])
while sentence!=('Quit the program'):
newsentence=sentence.split()
pigLatin()
sentence=input('input:')
As Willem Van Onsem said, this line doesn't do what you think:
if 'a'and'e'and'i'and'o'and'u' not in word[1:]:
You should try experimenting with the interpreter.
'a' and 'e' not in "bar"
# returns True
This is happening because and is a logical operator which looks at what comes before and after it. It is doing this:
'a' and ('e' not in "bar")
which evaluates to
'a' and True
which evaluates to True, because non-empty strings get assigned the boolean True.
Here is something that will work. It uses the all function, which only returns True if all of its elements are true, and a feature of Python called comprehension which allows you to do tidy loops:
vowels = "aeiou"
all(char not in vowels for char in word)