converting phone letters to numbers and using while loop - python-3.x

I am currently writing function that takes in a string and converts that string (which is a phone number) into numbers only. In addition I am also using a while loop asking the user if they want to continue. My output is only showing me the first number or letter I type in, I want to know why. This is what I have so far:
def translate_num(convert):
answer=input('insert y to continue')
convert=input('Enter phone number here')
while answer=='y':
for word in convert:
phone_num=[]
if word == 'A' or word == 'B' or word == 'C':
phone_num.append('2')
elif word == 'D' or word == 'E' or word == 'F':
phone_num.append('3')
elif word == 'G' or word == 'H' or word == 'I':
phone_num.append('4')
elif word == 'J' or word == 'K' or word == 'L':
phone_num.append('5')
elif word == 'M' or word == 'N' or word == 'O':
phone_num.append('6')
elif word == 'P' or word == 'Q' or word == 'R' or word== 'S':
phone_num.append('7')
elif word == 'T' or word == 'U' or word == 'V':
phone_num.append('8')
elif word == 'W' or word == 'X' or word == 'Y' or word=='Z':
phone_num.append('9')
else:
phone_num.append(word)
print(phone_num)
answer=input('insert y to continue')
return
translate_num('555-361-FOOD')

you are re-initializing the phone_num with phone_num=[] value after going through each value in convert. Instead declare phone_num=[] once at the start of the function, also as pointed out by kabanus the return statement needs to be de-intended by a block. My implementation below seems to work (I have removed the redundant input statements since you are already calling the function, I have also added code to convert the number list back to a string :
def translate_num(convert):
#answer=input('insert y to continue')
#convert=input('Enter phone number here')
phone_num=[]
while True:
for word in convert:
if word == 'A' or word == 'B' or word == 'C':
phone_num.append('2')
elif word == 'D' or word == 'E' or word == 'F':
phone_num.append('3')
elif word == 'G' or word == 'H' or word == 'I':
phone_num.append('4')
elif word == 'J' or word == 'K' or word == 'L':
phone_num.append('5')
elif word == 'M' or word == 'N' or word == 'O':
phone_num.append('6')
elif word == 'P' or word == 'Q' or word == 'R' or word== 'S':
phone_num.append('7')
elif word == 'T' or word == 'U' or word == 'V':
phone_num.append('8')
elif word == 'W' or word == 'X' or word == 'Y' or word=='Z':
phone_num.append('9')
else:
phone_num.append(word)
#print(phone_num)
#answer=input('insert y to continue')
number=''
for item in phone_num:
number=number+str(item)
return (number)
print (translate_num('555-361-FOOD'))

Related

I need to Create a function switchPlayer that requires 1 parameter named curr_player. If curr_player is X, return O. If curr_player is O, return X

We assume curr_player to be 'X'.
Output should be 'O', and vice-versa
(is my code correct?)
#my code
def switchPlayer(curr_player):
if curr_player == "X" or curr_player == "x":
print("your Player 'O' ")
return curr_player
if curr_player == "O" or curr_player == "o":
print("your Player 'X' ")
return curr_player
switchPlayer("X")
You want to return the opposite of what it currently is. Something else I changed was the way you compare the strings. Instead of checking for uppercase and lowercase, you can convert the string to lowercase first, and you only need to compare it one time.
if (curr_player.lower() == 'x'):
return 'O'
if (curr_player.lower() == 'o'):
return 'X'
This code can also be simplified to this:
return 'O' if curr_player.lower() == 'x' else 'X'
def switchPlayer(curr_player):
if curr_player == "X" or curr_player == "x":
curr_player="O"
return curr_player
if curr_player == "O" or curr_player == "o":
curr_player="X"
return curr_player
inp=input("input the current player")
a=switchPlayer(inp)
print("returned player",a)

Homework with strings

Hello guys i got a homework where i get a string and basically i should change the letters in it then return it backward:
A --> T
T --> A
G --> C
C --> G
Here is my code :
def dnaComplement(s):
newWord = ""
for x in s:
if x == "T":
newWord.join('A')
elif x == "A":
newWord.join('T')
elif x == "C":
newWord.join('G')
elif x == "G":
newWord.join('C')
return newWord[::-1]
the input is: ACCGGGTTTT
Your effort so far has got a minor issue with it.
You are using newWord.join('X') in an attempt to add the new character to the string. This doesn't work in the way you are attempting to use it. Read again how join functions in the official documentation.
Instead, you can use the += operator to append the characters to the end of your newWord string:
newWord += 'X'
Your code then becomes:
def dnaComplement(s):
newWord = ""
for x in s:
if x == "T":
newWord += 'A'
elif x == "A":
newWord += 'T'
elif x == "C":
newWord += 'G'
elif x == "G":
newWord += 'C'
return newWord[::-1]
print(dnaComplement('ACCGGGTTTT'))
Output:
AAAACCCGGT
This is the reverse of TGGCCCAAA which is stored in newWord until you return it from dnaComplement.
newWord.join(...) doesn't change the value of network, but rather returns a new string.
So to begin with, you would need to do something like network = newWord.join(...).
That being said, here is a cleaner way IMO:
d = {'T': 'A',
'A': 'T',
'C': 'G',
'G': 'C'
}
def dnaComplement(s):
return ''.join(d[x] for x in s[::-1])

how to fix self create module not working

My self made module is not returning an expected result( I want to input ABC and get back 123, But it is not doing that)
I am doing this to learn how to do this and so I can make my code look cleaner.(I am trying to make a very complicated message encoder and this is my first step)
def counter(key):
length = len(key)
counting = 0
word = []
try:
while length != counting:
if key[counting] == 'A' or 'a' :
word += '1'
counting += 1
if key[counting] == 'B' or 'b' :
word += '2'
counting += 1
if key[counting] == 'C' or 'c' :
word += '3'
counting += 1
if key[counting] == 'D' or 'd' :
word += '4'
counting += 1
if key[counting] == 'E' or 'e' :
word += '5'
counting += 1
if key[counting] == 'F' or 'f' :
word += '6'
counting += 1
if key[counting] == 'G' or 'g' :
word += '7'
counting += 1
if key[counting] == 'H' or 'h' :
word += '8'
counting += 1
if key[counting] == 'I' or 'i' :
word += '9'
counting += 1
if key[counting] == 'J' or 'j' :
word += '10'
counting += 1
if key[counting] == 'K' or 'k' :
word += '11'
counting += 1
if key[counting] == 'L' or 'l' :
word += '12'
counting += 1
if key[counting] == 'M' or 'm' :
word += '13'
counting += 1
if key[counting] == 'N' or 'n' :
word += '14'
counting += 1
if key[counting] == 'O' or 'o' :
word += '15'
counting += 1
if key[counting] == 'P' or 'p' :
word += '16'
counting += 1
if key[counting] == 'Q' or 'q' :
word += '17'
counting += 1
if key[counting] == 'R' or 'r' :
word += '18'
counting += 1
if key[counting] == 'S' or 's' :
word += '19'
counting += 1
if key[counting] == 'T' or 't' :
word += '20'
counting += 1
if key[counting] == 'U' or 'u' :
word += '21'
counting += 1
if key[counting] == 'V' or 'v' :
word += '22'
counting += 1
if key[counting] == 'W' or 'w' :
word += '23'
counting += 1
if key[counting] == 'X' or 'x' :
word += '24'
counting += 1
if key[counting] == 'Y' or 'y' :
word += '25'
counting += 1
if key[counting] == 'Z' or 'z' :
word += '26'
counting += 1
if key[counting] == ' ' :
word += '#'
counting += 1
finally:
return word
I want this module to let you input any phrase and convert the letters to numbers(A = 1, B =2, C = 3, etc.) and return the phrase back translated in numbers.
( I am not importing wrong)
To test I imputed 'Hello I am Sam' and I got back
['1', '2', '3', '4', '5', '6', '7', '8', '9', '1', '0', '1', '1', '1', '2', '1', '3', '1', '4'] This is obviously not right, so what is the problem.
This is the way my import looks
import random
from h import counter
key = "Hello I am Sam"
keyascii = counter(key)
print(key)
print(keyascii)
I am using ord to get the integer representation, and subtracting it with 64 to get the integer equivalent you specified in your code.
I am converting each character into uppercase, since you want both A and a to be 1, B and b to be 2 and so on. I am appending a whitespace character as it is
def counter(s):
result = ''
for c in s:
if c != ' ':
result += str(ord(c.upper())-64)
else:
result += ' '
return result
print(counter('ABC'))
print(counter('Hello I am Sam'))
#123
#85121215 9 113 19113

Pig Latin Program in Python

Write a program in Python 3 that converts a sentence typed in by the user to Pig Latin. Pig Latin has two rules:
If a word begins with a consonant all consonants before the first
vowel are moved to the end of the word and the letters "ay" are then
added to the end. e.g. "coin" becomes "oincay" and "flute" becomes
"uteflay". If a word begins with a vowel then "yay" is added to the
end. e.g."egg" becomes "eggyay" and "oak" becomes "oakyay".
My code works for individual words but does not work for sentence. I have tried entering:
wordList = word.lower().split(" ")
for word in wordList:
but it does not work.
#Pig Latin Program
import sys
VOWELS = ('a', 'e', 'i', 'o', 'u')
def pig_latin(word):
if (word[0] in VOWELS):
return (word +"yay")
else:
for letter in word:
if letter in VOWELS:
return (word[word.index(letter):] + word[:word.index(letter)] + "ay")
return word
word = ""
while True:
word = input("Type in the word or Exit to exit:")
if (word == "exit" or word == "Exit" or word == "EXIT"):
print("Goodbye")
sys.exit()
else:
print(pig_latin(word))
The input sentence: the rain in Spain
The output sentence: ethay ainray inyay ainSpay
So you could do something like this, it returns an iterable of all the pig-ed words and you can join them in the last step. You don't need that last return you have. My guess is the issue you saw was that you are returning in the first loop. you could track the return outside the loop and append to it in the loop and return that also.
import sys
VOWELS = ('a', 'e', 'i', 'o', 'u')
def pig_latin(word):
wordList = word.lower().split(" ")
for word in wordList:
if (word[0] in VOWELS):
yield (word +"yay")
else:
for letter in word:
if letter in VOWELS:
yield (word[word.index(letter):] + word[:word.index(letter)]+ "ay")
break
word = ""
while True:
word = input("Type in the word or Exit to exit:")
if (word == "exit" or word == "Exit" or word == "EXIT"):
print("Goodbye")
sys.exit()
else:
print(' '.join(pig_latin(word)))

how to to define a function make_ 3 rd _form() which given a verb in infinitive form returns its third person singular form?

I need to to define a function make_3rd_form() which given a verb in infinitive form returns its third person singular form.
The third person singular verb form in English is distinguished by the suffix-s, which is added to the stem of the infinitive form: run-> runs.
these are the rules:
If the verb ends in y, remove it and add ies
If the verb ends in o, ch, s, sh, x or z, add es
By default just add s.
I think that string method ends with() is the way.
I am new to python so any type of idea would be helpful.
def make_3rd_form():
word = raw_input('Please enter a word: ')
if word[len(word)-1] == 'o' or word[len(word)-1] == 's' or word[len(word)-1] == 'x' or word[len(word)-1] == 'z':
word = word + 'es'
print word
elif word[len(word)-2] == 'c' and word[len(word)-1] == 'h':
word = word + 'es'
print word
elif word[len(word)-2] == 's' and word[len(word)-1] == 'h':
word = word + 'es'
print word
elif word[len(word)-1] == 'y':
word = word[:-1]
word = word + 'ies'
print word
else:
word = word + 's'
print word
make_3rd_form()
Is this what you were thinking of? I hope so! However, if one of the requirements was to use with(), sorry, because clearly I didn't.
def make_3rd_form(verb):
es = ('o', 'ch', 's', 'sh', 'x', 'z')
if verb.endswith('y'):
return re.sub('y$', 'ies', verb)
elif verb.endswith(es):
return verb + 'es'
else:
return verb + 's'

Resources