Python UnboundLocalError "Need help" - python

def rotate_word(word,number)
for i in word:
word_num = ord(i)
new_word += chr(word_num + number)
return new_word
Hi guys, the code above is not working. This is a python function. When i run the program i will return an error: "UnboundLocalError: 'new_word' referenced before assignment"
what this means? Can anyone help me?
the output of my function would be:
print rotate_word('abc',5)
output: fgh

You should define new_word before using it. Place this before the for:
new_word = ''
You are also missing an indentation for the return and a colon after the def. Here is a fixed version:
def rotate_word(word, number):
new_word = ''
for i in word:
word_num = ord(i)
new_char = chr(word_num + number)
if new_char > 'z':
new_char = chr(ord(new_char) - 26)
new_word += new_char
return new_word
print rotate_word('abc', 5)
print rotate_word('xyz', 3)
EDIT: I've updated your code so it wraps after 'z'

Related

Turning random.choice into a mutable

I'm very new to python and I'm trying to make a hangman game. I currently have a line of code saying word = (random.choice(open("Level1py.txt").readline())).
I'm getting the error 'str' object does not support item assignment.
Here is the rest of my code (sorry for the mess):
import random
def checkLetter(letter, word, guess_word):
for c in word:
if c == letter:
guess_word[word.index(c)] = c
word[word.index(c)] = '*'
print(guess_word)
word = (random.choice(open("Level1py.txt").readline().split()))
guess_word = ['_' for x in word]
print(guess_word)
while '_' in guess_word:
guess = input('Letter: ')
print(checkLetter(guess, word, guess_word))
Strings are immutable in python. An easy workaround is to use lists, which are mutable:
st = "hello"
ls = list(st)
ls[3] = 'r'
st = ''.join(ls)
print(st)
Outputs
helro
Edit: here's how you would implement it in your own code
import random
def checkLetter(letter, word, guess_word):
for c in word:
if c == letter:
guess_word[word.index(c)] = c
word_list = list(word)
word_list[word.index(c)] = "*"
word = ''.join(word_list)
print(guess_word)
word = 'test'
guess_word = ['_' for x in word]
print(guess_word)
while '_' in guess_word:
guess = input('Letter: ')
print(checkLetter(guess, word, guess_word))
Note that there are still other issues that have nothing to do with this, like printing None and duplicate printing
You can also solve your problem using a dictionary:
word = "my string" #replace this with your random word
guess_word = {i: '_' for i in set(word)} # initially assign _ to all unique letters
guess_word[' '] = ' ' # exclude white space from the game
wrong_attempts = 0
while '_' in guess_word.values():
guess = input('Letter: ')
if guess in guess_word.keys():
guess_word[guess] = guess
else:
wrong_attempts += 1
if wrong_attempts > 11:
break
printable = [guess_word[i] for i in word]
print(' '.join(printable))
if '_' in guess_word.values():
print('you lost')
else:
print('congratulation, you won')

Pig latin translator not handling vowel 'a'

Pig latin translator not working properly .Not showing output for vowel 'a'.
example: input: va
the output is an error showing reference error.
working properly for all other vowels except 'a'.
UnboundLocalError: local variable 'list3' referenced before assignment.
import string
def translate(str1):
str2="eaiouy"
list2=[]
punstr=""
for c in str1:
if c in string.punctuation:
punstr=punstr+c
for c in string.punctuation:
str1= str1.replace(c,"")
if str1.isdigit():
return str1+punstr
else:
if (len(str1)==1):
if str1[0] in str2:
return str1+"yay"+punstr
else:
return str1+"ay"+punstr
elif str1[0] in str2:
return str1+"yay"+punstr
else:
for i in str2:
list1=str1.split(i)
if (len(list1[0])<len(list2)):
list3=list1[0]
list2=list1[0]
prestr=str(list3)
stem=str1.split(list3)
reqstem=stem[1]
return reqstem+prestr+"ay"+punstr
while True:
str1=raw_input("\nenter the sentance")
sentlist=str1.split(" ")
for i in range(len(sentlist)):
mystr=sentlist[i]
if i==0:
reqstring=translate(mystr)
print reqstring.capitalize(),
else:
reqstring=translate(mystr)
print reqstring,
list3 is only assigned to when len(list1[0]<len(list2), which means sometimes it isn't set, and that's when prestr=str(list3) will give you trouble.
working now!!!
import string
def translate(str1):
vowel=" eaiouy"
list2=[]
punstr=""
for c in str1:
if c in string.punctuation:
punstr=punstr+c
for c in string.punctuation:
str1= str1.replace(c,"")
if str1.isdigit():
return str1+punstr
else:
if (len(str1)==1):
if str1[0] in vowel:
return str1+"yay"+punstr
else:
return str1+"ay"+punstr
elif str1[0] in vowel:
return str1+"yay"+punstr
else:
for i in str1:
if i in vowel:
list1=str1.split(i)
print list1
break
prestr=str(list1[0])
stem=str1.split(prestr)
reqstem=stem[1]
return reqstem+prestr+"ay"+punstr
while True:
str1=raw_input("\nenter the sentance")
sentlist=str1.split(" ")
for i in range(len(sentlist)):
mystr=sentlist[i]
if i==0:
reqstring=translate(mystr)
print reqstring.capitalize(),
else:
reqstring=translate(mystr)
print reqstring,

i need to have some assistance with my pyglatin translator code (python)

ok so the code is
pyg = 'ay'
def word():
def new_word():
new_word = word + first + pyg
print "To translate type A word or name!"
original = raw_input('Enter A word:')
if len(original) > 0 and original.isalpha():
def new_word():
word = original.lower()
first = word[0]
new_word = word[1 : len(new_word)] + first + pyg
print "Translating 1 moment..."
print "Translated view below!"
print new_word
print "Made by: Tobias Balentine"
else:
print 'empty'
thats my code every thing is working except the part where its supposed to be the translated word ill show you what im getting
To translate type A word or name!
Enter A word:Tobias
Translating 1 moment...
Translated view below!
<function new_word at 0x021619F0>
Made by: Tobias Balentine
so this line (<function new_word at 0x021619F0>) is supposed to be the translated word but for some reason its not showing it please help somebody
pyg = 'ay'
print "To translate type A word or name!"
original = raw_input()
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word[1:] + first + pyg
print "Translating 1 moment..."
print "Translated view below!"
print new_word
print "Made by: Tobias Balentine"
else:
print 'empty'
You have way too many functions defined, and you are not even using them.

Assign a new variable for every item in list - Python

Here is the standard pig latin code used in codeacademy. It works well but it's shortcoming is that it only works for one word at a time:
pyg = 'ay'
original = raw_input('Enter a word or phrase:')
if len(original) > 0 and original.isalpha():
word = original.lower()
translate = word[1:] + word[0]
if word[0] != "a" and word[0] != "e" and word[0] != "i" and word[0] != "o" and word[0] != "u":
new_word = translate + pyg
print new_word
else:
new_word = word + pyg
print new_word
else:
print 'Input is empty or illegal'
so I wanted to make it so that it could phrases. This is what I came up with:
pyg = 'ay'
count = 0
original_input = raw_input('Enter a word or phrase:')
original = original_input
original_list = []
#converts to a list
while " " in original:
if count > 50:
break
word = original[0:original.index(" ")]
original_list.append(word)
space = original.index(" ")
space += 1
original = original[space:]
count += 1
#this works great until there is a word left and no spaces i.e. the last word
if len(original) > 0:
original_list.append(original)
#this adds the last word
print original_list
def pyglatin(phrase):
#old code doesn't work because phrase is a list
#now I have to translate BACK to a string
for words in phrase:
new_word = str(words)
"""this works for one word, how do I assign a new variable for every word if I don't know the phrase length ahead of time"""
so that brings me to my question: How do I assign a variable for every item when I don't know how many items I'm going to need, and then be able to call that code back (through the old pyglatin translator)?
As Maxime mentioned, lists are useful in this instance, and the string can be converted to a list much easier. To account for phrases, I would rewrite the code as follows:
def trans_word(original):
if len(original) > 0 and original.isalpha():
word = original.lower()
translate = word[1:] + word[0]
if word[0] != "a" and word[0] != "e" and word[0] != "i" and word[0] != "o" and word[0] != "u":
new_word = translate + pyg
return new_word
else:
new_word = word + pyg
return new_word
else:
return "Input is empty or illegal"
def pyglatin(phrase):
if len(phrase) > 0:
return " ".join(trans_word(word) for word in phrase)
else:
return "Input is empty or illegal"
pyg = 'ay'
count = 0
original_input = raw_input('Enter a word or phrase:')
original_list = original_input.split()
print pyglatin(original_list)
Maybe something like this?
def latinize(word):
word = word.lower()
translate = word[1:] + word[0]
return (translate if word[0] in 'aeiou' else word) + 'ay'
original = raw_input('Enter a word or phrase:')
print ' '.join(latinize(word) for word in original.split())
Example input and output:
Enter a word or phrase:Gallia est omnis divisa in partes tres
galliaay steay mnisoay divisaay niay partesay tresay
But shouldn't you actually move all initial consonants to the end, and not only the first?
Edit:
If you want to move all initial consonants to the end, you can use:
def latinize(word):
word = word.lower()
firstvowel = min (word.index (v) if v in word else 42042 for v in 'aeiou')
if firstvowel == 42042: raise Exception ('No vowel in word')
return word [firstvowel:] + word [:firstvowel] + 'ay'
original = raw_input('Enter a word or phrase:')
print ' '.join(latinize (word) for word in original.split () )
Sample input and output:
Enter a word or phrase:star chick mess string
arstay ickchay essmay ingstray

Why does my python method print out 'None' when I try to print out the string that the method returns?

This is the problem I'm running into, instead of returning new_word and printing it out it just prints 'None'
text = "hey hey hey,hey"
word = 'hey'
def censor(text,word):
new_word = ""
count = 0
if word in text:
latter_count = ((text.index(word))+len(word))
while count < text.index(word):
new_word+= text[count]
count += 1
for i in range(len(word)):
new_word += '*'
while latter_count < len(text) :
new_word += text[latter_count]
latter_count += 1
if word in new_word :
censor(new_word,word)
else :
return new_word
print censor(text,word)
A function returns None if there is no return statement.
Probably while doing recursion, if word in text: is False, and so there is nothing to return. You also did not return the recursive step. You must return censor(new_word,word)
You're not returning in the first branch of the if toward the end. Change that to
if word in new_word:
return censor(new_word,word)
Your function will also return None if word in text is false, so you might want to add an else at the end to return an empty string or some other default value in that case.
If the function hits the end without hitting a "return" statement, it's the same as "return None":
def censor(text,word):
new_word = ""
count = 0
if word in text:
latter_count = ((text.index(word))+len(word))
while count < text.index(word):
new_word+= text[count]
count += 1
for i in range(len(word)):
new_word += '*'
while latter_count < len(text) :
new_word += text[latter_count]
latter_count += 1
if word in new_word :
censor(new_word,word) # probably want to return here
else : # don't need this else if you return in the if branch
return new_word
# what do you want to return in this case?
return None

Categories