pig latin issues with output code for python - python-3.x

I am having trouble with the code only producing the first two letters of the first word and then attaching the 'AY' to the end while it runs. I can't seem to figure out how to correct this error.
def main():
strin = input('Enter a sentence (English): ')
strlist = strin.split()
i = 0
pigsen = ''
while i < len(strlist):
word = strlist[i]
j = 1
fc = word[0].upper()
pigword =''
while j < len(word):
pigword += word[j].upper()
j += 1
pigword += fc + 'AY'
pigsen += pigword + ' '
i +=1
print('Pig Latin: ' +str(pigsen))
main()

First, I'll assume this is just the start of a pig Latin generator and you'll add the other rules (at least a couple more) once you get this much working. Second, let's simplify the code as a way of fixing it:
def main():
sentence = input('Enter a sentence (English): ')
words = sentence.upper().split()
latin_words = []
for word in words:
first, rest = word[0], word[1:]
latin_word = rest + first + 'AY'
latin_words.append(latin_word)
print('Pig Latin:', *latin_words)
main()
USAGE
> python3 test.py
Enter a sentence (English): He complimented me on my English
Pig Latin: EHAY OMPLIMENTEDCAY EMAY NOAY YMAY NGLISHEAY
>
I would say the problem with your code is you made it too complicated.

Related

How can I extend a word with a loop with Python3?

I'm a beginner and I'm working on an assignment where I want Python to use user input and extend the word.
If user input is monkey the output (print) should be: m-oo-nnn-kkkk-eeeee-yyyyyy
This is my start but it only outputs: m-o-n-k-e-y
Do you have any hints on how I can go forth? https://codeshare.io/8p6nB4
inp = input("Give me a word to extend: ")
index = -len(inp)
ext_inp = ''
for letter in inp:
if index < 0:
ext_inp += inp[index] + '-'
index += 1
print(ext_inp)
word_to_be_extended = input("give me a word to extern:")
word_after_extend = ''
for i in range(len(word_to_be_extended)):
word_after_extend += word_to_be_extended[i] * (i+1)
if i != len(word_to_be_extended)-1:
word_after_extend += '-'
print(word_after_extend)

When execute code below I receive the message error str concatenate

Hy guys! I started learn programming. And when execute code below I receive the message error str concatenate.
import random
word_list = ["ababababababab", "baloon", "banana"]
chosen_word = random.choice(word_list)
print(chosen_word)
guess = input("Guess the word, type one letter: \n").lower()
i = 0
while (i < len(chosen_word)):
for i in chosen_word:
if i == guess:
print(guess)
i += 1
The message error:
TypeError: can only concatenate str (not "int") to str
j = ""
for j in chosen_word:
if j == guess:
print(guess)
Use one loop.
Try this way, put input in a while loop (why did you do while condition in parenthesis?). Another thing that I've changes is to use if statement insted for loop.
import random
word_list = ["ababababababab", "baloon", "banana"]
chosen_word = random.choice(word_list)
print(chosen_word)
i = 0
while i < len(chosen_word):
guess = input("Guess the word, type one letter: \n").lower()
if guess in chosen_word:
print(f'Yep {guess} is in a word')
i += 1

Use Python to reverse the words in a sentence

The question was: Return a sentence with the words reversed
>>> master_yoda('I am home')
'home am I'
It will eventually reverse the words of the line.
I am learning and performing Python in Jupyter Notebook.
def master_yoda(string):
l = string.split()``
p = len(string) - 1
final = ''
while p<0:
final = final + ' ' + s[p]
p = p-1
print (final)
master_yoda('Hello my name is Aryan')
The output is nothing..
No syntax errors , but still no output ...
Perhaps you should try this.
def master_yoda(string):
reversed_list = string.split(' ')
reversed_list.reverse()
reversed_string = ' '.join(reversed_list)
print(reversed_string)
master_yoda("i am home")
The big problem with the code is that you were testing for p < 0 but since p starts off with a positive value, the code never enters the while loop. You should really have been testing for p >= 0. The following code should do what you want, they way you seem to want it to:
def master_yoda(string):
l = string.split()
p = len(l) - 1
final = l[p]
p -= 1
while p >= 0:
final += ' ' + l[p]
p -= 1
return final
Note that this implementation fails if an empty string is passed as input. I tried to keep the code in the spirit of your own code and checking for an empty string would make it more complex. The simplest and most robust solution would be:
def master_yoda(string):
return ' '.join(reversed(string.split()))

Where is issue with final display in this code?

The code requires the user to provide an input of strings and convert the uppercase to lower and vice-versa.Input: Rohit Tapadia , Expected Output: rOHIT tAPADIA , Actual Output: rOHIt TAPADIA . It should do exactly what the swapcase() does.
inp = input("Enter ")
for i in inp:
inp_lst.append(i)
print(inp_lst)
for j in inp_lst:
if j.isupper()==True:
x=inp_lst.index(j)
#print(x)
#print(j)
k = j.lower()
#print(k)
inp_lst[x]=k
print(inp_lst[x])
elif j.islower()==True:
y=inp_lst.index(j)
#print(y)
#print(j)
l = j.upper()
inp_lst[y]=l
print(inp_lst[y])
else:
z=inp_lst.index(j)
#print(z)
#print(j)
inp_lst[z]=j
print(inp_lst[z])
print(''.join(inp_lst))```
You can achieve exactly the same thing in 2 lines with the built-in swapcase() method:
inp = input("Enter ")
print(inp.swapcase())
Example input:
heLLo StackOverflow
Output:
HEllO sTACKoVERFLOW
Demo: https://repl.it/#glhr/55548482
Edit: here's a working and simplified implementation of your code. Note that inp_lst is not needed since you can directly iterate over characters in a string. You can simply add each character to the output string using string concatenation (not that outputString += j is equivalent to outputString = outputString + j - it simply adds j at the end of the string).
inp = input("Enter ")
outputString = ""
for j in inp:
if j.isupper():
outputString += j.lower()
elif j.islower():
outputString += j.upper()
else:
outputString += j
print(outputString)
Edit 2: The problem in your code is this inp_lst.index(j), because index() searches for the first occurrence of the character j. So if j='t', it will select the first occurrence of t in the list, and turn it uppercase/lowercase, even if the loop is at the second occurrence of t. That's why the first t in "Rohit Tapadia" is turned to lowercase in the output.
you can try this one too
inp = input("Enter ")
output="".join([char.lower() if char.isupper() else char.upper() for char in inp ])
inp = "Rohit Tapadia"
output will be
rOHIT tAPADIA

Count on which loop text was entered and display as index

I'm working on a small program which takes a text input - and then places each of these items in a dictionary alongside which line they were entered on. At the moment if I enter 4 lines of text. It'll take them all out correctly, but every word will be set to the value 4 - instead of the loop it was inputted on. I've removed all the other functions from my code (remove punct, remove stopwords, stemwords, etc). to make this clearer.
from string import *
function = False
words_split = []
lineNumber=0
final_value = []
def indexer(t):
global words_split
words = t.split();
for word in words:
words_split.append(word)
def dict_print():
for keys in Dict:
output = keys + " " + str(Dict[keys][0])
i= 1
while i < len(Dict[keys]):
output = output + ", " + str(Dict[keys][i])
i = i + 1
print(output)
print("Please type a line and hit 'Enter' or type a single fullstop followed by 'Enter' to exit \n")
text = ""
while function == False :
if(text == "."):
print("The index is:")
function = True
dict_print()
else:
Dict = {}
text = input()
lineNumber += 1
for word in words_split:
if word in Dict:
if lineNumber not in Dict[word]:
Dict[word] = Dict[word] + [lineNumber]
else:
Dict[word] = [lineNumber]
indexer(text)
My global variable was causing the issue. I'll leave this up with my completed full code in case someone else runs into the same issue (:
https://repl.it/#Glaschu/AdmiredSteelCardinal

Resources