This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 3 years ago.
My base text is asking to be defined but I can't work out why.
I've tried changing it from list to string.
My code is:
text_str = input("What is your text: ")
text_list = list(text)
text_list_reversed = text_list.reverse()
text_str_reversed = str(text_list_reversed)
if text_str_reversed == text_str:
print("Your word is a palindrome")
else:
print("Your original was",text_str)
print("Your word reversed is",text_str_reversed)
Error code:
What is your text: owo
Traceback (most recent call last):
File "C:/Users/sambi.LAPTOP-UU5B18TJ/OneDrive/Documents/Python/My Code/School Stuff/Palindrome checker.py", line 1, in <module>
text_str = input("What is your text: ")
File "<string>", line 1, in <module>
NameError: name 'owo' is not defined
My excepted result would be for it to tell me it's a palindrome but instead it's spitting out a message saying that "owo" needs to be defined.
Lot going wrong in the original code. Try:
def pal_check():
text_str = input("What is your text: ")
text_str_rev = text_str[::-1]
if text_str_rev == text_str:
print("Your word is a palindrome")
else:
print(f"Your original was: {text_str}")
print(f"Your word reversed is: {text_str_rev}")
In your original code, text_list_reversed = text_list.reverse() fails because reverse() reverses in place, and returns None. Also, text is an uninitialized variable, which indicates you probably didn't copy-paste the code, but rather retyped it, if you weren't getting an error for that.
Related
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 months ago.
I keep getting an error on the line with the #. I've tried putting "" around each symbol, all the symbols together, and put the symbols in ().
def main():
name = input("Enter a reader's name: ")
symbol = input("Enter a symbol: ")
rating = input("Enter a rating: ")
if name not in 'ratings.txt':
print("No such reader " + name)
print("bye!")
return
#if symbol not >,<,=:
print("please use >,<,=")
return
if rating not -5,-3,0,1,3:
print("please use -5,-3,0,1,3")
return
if name = []:
print('no books found')
return
You can use the not in construct to check if an item is not in a list/tuple/other container. Thus, you can do this:
item = "foo"
print(item not in ["foo", "bar", "baz"]) # False
print(item not in ["ham", "egg", "pan"]) # True
This works for numbers too. However, using sets (with curly braces) is more efficient if all you're doing is testing if an item is in the container. Also, I see your code has
if name = []:
When testing for equality in an if statment, use the equals operator ==. Thus your code will be:
name = input("Enter a reader's name: ")
symbol = input("Enter a symbol: ")
rating = input("Enter a rating: ")
if name not in 'ratings.txt':
print("No such reader " + name)
print("bye!")
return
if symbol not in {">", "<", "="}:
print("please use >,<,=")
return
if rating not in {-5, -3, 0, 1, 3}:
print("please use -5,-3,0,1,3")
return
if name == []:
print('no books found')
return
Finally, the line
if name not in "ratings.txt":
does not check if name is in the contents of the file ratings.txt, but rather if it is a substring of that filename. For checking the file contents, you can try this question.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
How to validate person names? - Python/Django
(4 answers)
Closed 4 years ago.
I am at the part where I ask the user for their name. So far I got this:
# Import stuff
import time
# Create empty variable
Name = ""
# Ask their name
while Name = ""
Name = input("What is your name? ")
print("")
print(Name)
print("")
time.sleep(3)
So if the user inputs nothing, it repeats the question. But when the user inputs an integer or a float it registers this as a valid name.
How will I be able to make it so that if the Name variable is an integer or a float, it will respond with "Please enter a valid name" and repeat the question?
I'm updating my answer to simplify the code and make it more readable.
The below function is a function that I would use in my own code, I would consider it to be more "proper" than my old answer.
from string import ascii_letters
def get_name():
name = input("What is your name?\n: ").strip().title()
while not all(letter in ascii_letters + " -" for letter in name):
name = input("Please enter a valid name.\n: ").strip().title()
return name
To break this down, the line all(letter in ascii_letters + " -" for letter in name) means "if each letter in name is not an alphabetical character, a space, or a hyphen".
The part letter in ascii_letters + " -" checks to see if a letter is in the string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -".
This is repeated by the next part, for letter in name, for every character in the string. This will effectively return a list of booleans, [True, True, True, ...] where any False is a character that did not pass the conditional. Next, this list is passed to the all() function, which returns True if all of the list items are True.
After the all() is executed, conditional is reversed, allowing the loop to continue on the existence of a single failed character.
Old answer is as follows, it will still be useful.
This function should work well for you. Simply check if the string the user entered is alpha characters only, otherwise ask again.
Notice the use of str.isalpha().
def get_name():
name = input("What is your name?\n: ").strip().title()
while not (name.replace("-", "") and
name.replace("-", "").replace(" ", "").isalpha()):
name = input("Please enter a valid name.\n: ").strip().title()
return name
Checking if name will check if the string is empty, and using str.strip() on the values returned will remove any surrounding whitespace (stray spaces) to the left or right of the user input.
The str.replace("-", "") eliminates hyphens while checking validity. Thanks for pointing this out #AGN Gazer.
Now you can just call the function later in your script, or store it for later.
name = get_name().title()
print("You said your name was " + name + ".)
The str.title() converts the letter of each word in a string to uppercase. For example, if I entered my name "jacob birkett", the output (and subsequent value of name would be "Jacob Birkett".
Take a look at the documentation for str.isalpha(), str.strip(), str.replace() and str.title().
You can try this :
while Name == "" or Name.isnumeric() == True:
Name = input("What is your name? ")
print("")
Here if the Name is any numeric value it will ask again, But if the name is like alphanumeric it will accept.
You can use a function like .isalpha() as this will return True if all the string contains all the alphabets:
while True:
Name = input("Please enter a valid name.\n: ")
if name.isalpha()
break
else:
print("Please enter a valid name.")
continue
print(Name)
Or You can try exception handling in python as (but this should be prevented):
try :
int(Name)
print("Please enter a valid name")
...
except:
print("Accepted")
...
This will check if the input is an integer print the error.
You can try:
This will check if variable Name containing numeric data or not.
import time
Name = ""
while Name == "" :
Name = input("What is your name? ")
if not Name.isalpha():
print "It is containing numberic characher or characters"
Name = ""
print("")
print(Name)
print("")
time.sleep(3)
You also can try if name is like "harsha-biyani":
import time
Name = ""
while Name == "" :
Name = input("What is your name? ")
if any(i.isdigit() for i in Name):
print "It is containing numberic characher or characters"
Name = ""
print("")
print(Name)
print("")
time.sleep(3)
You can use:
Name.isalpha()
"3".isalpha()
False
"anna".isalpha()
True
I am new to Python. Working with 2.7 for class.
The teacher set a project in which we are to code a program that takes a piece of a Monty Python script (input by user), stores it in a list of lists, replaces a specific name in the script with the user's name and prints the revised script out to console.
The issue I am running into is in my third function replace_name, the parameters are the list of lists, old name, new name.
However, I am getting
NameError:'word_list' is not defined
I understand that if a variable is not defined in the Main then it is local to its function.
I thought though, that by using return in the function that that information is stored to be used by subsequent functions.
Am I wrong?
def new_name(): #prompts for user's name. checks if input is valid
while True:
name = raw_input("Please enter your name.\n")
if len(name) < 1:
print "Invalid, please enter your name.\n"
else:
return name
def orig_script():#reads in script, splits into list of lists
word_list = []
script = raw_input("Please enter script, one line at a time. Enter 'done' to exit. \n")
if len(script) < 1:
print "Empty text field. Please try again.\n"
while script != 'done':#splits string input,adds to list
words = script.split()
word_list.append(words)
script = raw_input("Please enter script, one line at a time. Enter 'done' to exit.\n ")
if len(script) < 1:
print "Empty text field. Please try again.\n"
return word_list
def replace_name(word_list,old_name,new_name):#replaces old name with new name in list. creates new list from changes.
new_list = []
for sentences in range(word_list):
sentence = word_list[sentences]
for words in range(sentece):
word = sentence[words]
if word == old_name:
sentence[words] == new_name
new_list.append(sentence)
print new_list#debugging-change to return
new_name()
orig_script()
replace_name(word_list, Robin, new_name)
If my indentation is a bit off here, I apologize.
I tried to correct it from the copy/paste.
There are no indentation errors given in repl.it.
Traceback (most recent call last):
File "python", line 45, in <module>
NameError: name 'word_list' is not defined
You did not assign any of the word_list, Robin, new_name variables. Returning a variable of a particular name does not bind it to any type of external variable on its own, especially not one of the same name.
For example, you need to assign the return value explicitly to its own variable.
word_list = orig_script()
name = new_name()
replace_name(word_list, "old name", name)
Also
for sentences in range(len(word_list)):
sentence = word_list[sentences]
Is the same as
for sentence in word_list:
Note: You do have a typo in sentece and this is a comparison, not an assignment sentence[words] == new_name
Bonus, I think you can rewrite replace_name as
def replace_name(word_list,old_name,new_name):
return [[new_name if w == old_name else old_name for w in sentence] for sentence in word_list]
Pass the parameter in you function argument.
Ex.
#take the o/p of variable in another one and pass in funcation
return_val = orig_script()
old_name = ["jack", "mike" , "josh"]
new_name= ["jen" , "ros" , "chan"]
#calling replace name funcation
replace_name(return_val,old_name,new_name)
This question already has answers here:
Function name not defined
(2 answers)
Closed 4 years ago.
dict={"key":"lock","kailas":"name boy","kerala":"city","kalyani":"name girl","bady":"horse"}
search_word = raw_input("enter a word")
if search_word in dict:
print dict[search_word]
print writeword(search_word)
else:
Y = search_word[0]
print Y
print writeword(Y)
for word in dict:
if word[0]==Y:
print "whether you want '"+word+"' this word"
def writeword(search_word ):
with open("spast_history", 'w')as file:
for item in search_word:
file.write(str(item)+'\n')
I define function call it but still it show name error.Give any solution to solve this.
Python is executed iterative form the interpreter. But the function write_word is defined after your function call. The best way would be wrap the code block in a function and execute it at the bottom of your file. Your file should look like this.
def main():
dict={"key":"lock","kailas":"name boy","kerala":"city","kalyani":"name girl","bady":"horse"}
search_word = raw_input("enter a word")
if search_word in dict:
print dict[search_word]
print writeword(search_word)
else:
Y = search_word[0]
print Y
print writeword(Y)
for word in dict:
if word[0]==Y:
print "whether you want '"+word+"' this word"
def writeword(search_word):
with open("spast_history", 'w')as file:
for item in search_word:
file.write(str(item)+'\n')
main()
Note you can also define the dict outside of the method.
This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 5 years ago.
python 2.7.9 so i wanted to make a script to run constantly where i can take notes on names and characteristics but i don't know why its throwing this error. eventually i would like it to be exported to a file so it can save the inputted information.
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\PythonFiles\Dictionary.py", line 18, in
key = input("Enter a player name: ")
File "", line 1, in
Name Error: name 'bob' is not defined
basket = {}
print("""
Note Program:
___________
1: Add Item
2: Remove Item
3: View
0: Exit Program
""")
option = int(input("Enter an Option: "))
while option != 0:
if option == 1:
key = input("Enter a player name: ")
if key in basket:
print("Name Found!...")
value = input("adding notes: ")
basket[key] += value
else:
value = input("Notes: ")
basket[key] = value
elif option == 2:
key = input("Enter a player name: ")
del(basket[key])
elif option == 3:
for key in basket:
print(key,":",basket[key])
elif option !=0:
print("please enter a valid option")
option = str(input("\n\nEnter an option: "))
else:
print("Note Program Closed.")
You should use raw_input() instead of input(), as input is trying to eval() which is causing the exception.
raw_input() takes the input and passes it back as a string.
input() will actually run as eval(raw_input()).