Name error in Python3 when name is defined [duplicate] - python

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 4 years ago.
I am in spyder trying to run a fairly simple python code (python 3.6.4), but when I run the code and use the input statements, it says the names are not defined, even though they should be.
#Module 4 project
#4/25/18
#Henry Degner
#This project is meant to determine whether or not certain people are qualified to go to an exclusive concert
#create function askAge, which will use an input statement and comparison operators to see if the user is old enough
def askAge():
age = int(input("How old are you? "))
if( age >= 18 ):
ageReq = "true"
elif( age < 18 ):
ageReq = "false"
else:
print("Please print you're age with only numerical characters, in years")
age = int(input("How old are you? "))
#create function askHearing, yes or no question to do you have sensitive hearing
def askHearing():
hearing = str(input("Do you have sensitive hearing? "))
if( str(hearing) == "yes","y" ):
hearingReq = "do"
elif( str(hearing) == "no","n"):
hearingReq = "don't"
else:
print("Please type yes, or y, if you have sensitivehearing. If not, type no or n.")
hearing = str(input("Do you have sensitive hearing? "))
#create function askTicket, yes or no question to do you have a ticket
def askTicket():
ticket = str(input("Do you have a ticket for the concert? "))
if( str(ticket) == "yes","y" ):
ticketReq = "do"
elif( str(ticket) == "no","n"):
ticketReq = "don't"
else:
print("Please type yes if you have a ticket, or no if you don't.")
ticketReq = str(input("Do you have a ticket for the concert"))
#create function askFun, yes or no question to are you willing to have an awesome time
def askFun():
fun = str(input("Are you willing to have a great time?"))
if( str(fun) == "yes","y"):
funReq = "do"
elif( str(fun) == "no","n" ):
funReq = "don't"
else:
print("Please type 'yes' or 'no'")
fun = str(input("Are you willing to have a great time?"))
#use def main():
def main():
#print situation, will ask some questions to see if you can attend concert
print("Welcome to the Henry Degner Concert Venue! We have to ask you a few questions before we let you into the venue.")
#use askAge
askAge()
#use askHearing
askHearing()
#use askTicket
askTicket()
#use askFun
askFun()
#print user's answers
print("You said you are " + age + " years old, you " + hearingReq + " have sensitive hearing, you " + ticketReq + " have a ticket, and you " + funReq + " want to have a great time!")
#use if-else statement, if all three conditions match requirements, print you can attend concert. If not, print you can't attend
#use main()
main()
the error outputs as
File "C:/Users/henry/Documents/Current Classes/Foundations of Programming/Module 4 project/Module 4 project script.py", line 60, in main
print("You said you are " + age + " years old, you " + hearingReq + " have sensitive hearing, you " + ticketReq + " have a ticket, and you " + funReq + " want to have a great time!")
NameError: name 'age' is not defined
It also says that all of the other names in line 60 aren't defined. Thanks in advance!

You are getting NameError: name 'age' is not defined because variables from different functions are not shared until you declare them global or you return them from one method to another.
Read more about Python Scopes and Namespaces
Just return value from function to main method.
Returning value from method
def askAge():
age = int(input("How old are you? "))
if( age >= 18 ):
ageReq = "true"
elif( age < 18 ):
ageReq = "false"
else:
print("Please print you're age with only numerical characters, in years")
age = int(input("How old are you? "))
return age
def main():
...
age = askAge()
.....
Same you need to do it for all methods,
askHearing()
askTicket()
askFun()

Related

"If" statement gets ignored when function is recalled [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to create a simple program which will ask the user to input an age and then will ask the user to input another age to find the difference.
The problem in my program arrives when I ask the user to confirm their age.
When I ask the user to confirm the age, if the user answers confirms their choice, I want the program to keep running. But currently, I am stuck in a cycle which even if the user inputs a confirmation, the program skips my if statement and always runs my else: statement.
#This program will prompt you to state your age and then will proceed to
#calculate how long till __ age
print("Hello. ")
while True:
try:
myAge = int(input("Please enter your age: ")) #int( makes func be a #
except ValueError:
print("I'm sorry, please enter your age as a numeric value.")
continue #Continue function loops back to the function making it 'continue'
else: #If it is a # then it breaks
break
#Going to ask for the second variable
print("You are " + str(myAge) + ".")
print("What is your desired age? ")
def secondV():
desiredAge = int(input())
print("You wish to be " + str(desiredAge) + "?")
yourWish = input()
desiredAge = int(input())
print("Do you wish to be " + str(desiredAge) + "?")
yourWish = input()
def choose():
if yourWish == "Yes" and yourWish == "yes" and yourWish == "y" and yourWish == "Y":
print("Okay... calculating")
print("To be " + str(desiredAge) + ", you would have to wait " + str(desiredAge - myAge) + " years. ")
else:
print("Erm... please input your desired age now:")
secondV()
if desiredAge == 'yes' and desiredAge == 'Yes':
print(Yes())
else:
No()
choose()
print('Goodbye.')
There were some indentation errors and you used and keyword instead of or keyword
here is a working code
print("Hello. ")
while True:
try:
myAge = int(input("Please enter your age: ")) #int( makes func be a #
except ValueError:
print("I'm sorry, please enter your age as a numeric value.")
continue #Continue function loops back to the function making it 'continue'
else: #If it is a # then it breaks
break
#Going to ask for the second variable
print("You are " + str(myAge) + ".")
print("What is your desired age? ")
def secondV():
desiredAge = int(input())
print("You wish to be " + str(desiredAge) + "?")
yourWish = input()
desiredAge = int(input())
print("Do you wish to be " + str(desiredAge) + "?")
yourWish = input()
def choose():
if yourWish == "Yes" or yourWish == "yes" or yourWish == "y" or yourWish == "Y":
print("Okay... calculating")
print("To be " + str(desiredAge) + ", you would have to wait " + str(desiredAge - myAge) + " years. ")
else:
print("Erm... please input your desired age now:")
secondV()
if yourWish == 'yes' or yourWish == 'Yes':
print("Okay... calculating")
print("To be " + str(desiredAge) + ", you would have to wait " + str(desiredAge - myAge) + " years. ")
else:
print("Erm... please input your desired age now:")
secondV()
choose()
choose()
print('Goodbye.')

'while' loop in Python

I'm starting to learn Python by throwing myself in the deep end and trying a bunch of exercises.
In this particular exercise, I'm trying to make a program to ask the name and age of the user and tell the user the year they're going to turn 100.
I tried putting in a yes/no input to ask if the user's birthday has passed this year, and give the correct year they will turn 100, based on that.
I wanted to incorporate a while loop so that if the user enters an answer that isn't "yes" or "no", I ask them to answer either "yes" or "no". I also wanted to make the answer case insensitive.
print("What is your name?")
userName = input("Enter name: ")
print("Hello, " + userName + ", how old are you?")
userAge = input("Enter age: ")
print("Did you celebrate your birthday this year?")
while answer.lower() not in ('yes', 'no'):
answer = input ("Yes/No: ")
if answer.lower() == 'yes':
print ("You are " + userAge + " years old! That means you'll be turning 100 years old in the year " + str(2019 - int(userAge) + 100))
elif answer.lower() == 'no':
print ("You'll be turning " + str(int(userAge) + 1) + " this year! That means you'll be turning 100 years old in the year " + str(2019 - int(userAge) + 99))
else:
print ('Please type "Yes" or "No"')
print ("Have a good life")
You should addd the input before trying to access the answer.lower method, so it will be something like:
answer = input('Yes/No: ')
while answer.lower() not in ('yes','no'):
answer = input('Yes/No: ')
Check geckos response in the comments: just initialize answer with an empty string

Program closing when it shouldn't

I'm makeing a text based game.
the user is asked to enter:
name
difficulty
skill level
However, once the user inputs the difficulty the program closes.
Any help will be appreciated.
OH AND PLEASE COULD YOU NOT JUST DOWN-VOTE WITHOUT GIVING AN EXPLANATION, NOT EVERYONE IS A PYTHON MASTER.
P.S. sorry for broken english
while True:
print("Welcome to 'The imposible quest'")
print("""
""")
name_charter = str(input("What's your name adventurer? "))
difficulty = str(input("Please choose the difficulty level(easy, normal, hard): "))
while set_difficulty==0:
if difficulty=="easy":
max_skill_start = 35
player_max_hp = 120
set_difficulty = 1
elif difficulty=="normal":
max_skill_start = 30
player_max_hp = 100
set_difficulty = 1
elif difficulty=="hard":
max_skill_start = 25
player_max_hp = 80
set_difficulty = 1
else:
print("ERROR, the option you chose is not a valid difficulty!")
print("Hello" + nam_char + "/n /n Please choose your abilities, keep in mind that you can't spend more than" + max_skill_start + "points in your habilities: ")
strength, dexterity, intelligence, perception, charm, combat, crafting, tradeing = input("Strength: "), input("Dexterity: "), input("Intelligence: "), input("Perception: "), input("Charm: "), input("Combat: "), input("Crafting: "), input("Tradeing: ")
end_prg = str(input("Do you want to close the program(yes/no)? "))
if end_prg=="yes":
quit()
elif end_prg=="no":
print("""
""")
You just need to set the set_difficulty to 0 before the while loop. Also I see you are printing out big empty lines, you can also use the print("\n") this will create a newline. You can add multiple by *by number desired :
print("\n"*10) //prints out 10 newlines.

Why is Python 2 input() giving me 'NameError: name "____" is not defined'? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to write a function that will ask for name, last name and year of birth. Also, it will later print out the initials and the age.
First of all, it doesn't ask for any of it.
Second of all, it doesn't matter what I'll enter it will print the error:
NameError: name "____" is not defined.
I'm using Python 3.
Here is the code:
def userinfo():
name_ = input("Enter your first name: ")
last_ = input("Enter your last name: ")
year_ = input("Enter your year: ")
initials_ = name_[0] + last_[0]
age_ = (2018 - year_)
_info = ("Your initials are ") + (initials_) + (" and you are ") + (str(age_)) + (" years old.")
if (len(name_) > 0 and len(last_) > 0 and len(year_) > 0 and name_.isalpha() and last_.isalpha()):
return (_info)
else:
return ("Error")
Here is a rectified code with some corrections:
1) Replacing input with raw_input (assuming you are using python 2.***). In case you are using version 3+, then replace back raw_input by input.
2) Replacing year_ by int(year_) while calculating the age because user input is of type str.
def userinfo():
name_ = raw_input("Enter your first name: ")
last_ = raw_input("Enter your last name: ")
year_ = raw_input("Enter your year: ")
print (name_)
initials_ = name_[0] + last_[0]
age_ = (2018 - int(year_)) # Correction here
_info = ("Your initials are ") + (initials_) + (" and you are ") + (str(age_)) + (" years old.")
if (len(name_) > 0 and len(last_) > 0 and len(year_) > 0 and name_.isalpha() and last_.isalpha()):
return (_info)
else:
return ("Error")
userinfo()
Output
Enter your first name: Donald
Enter your last name: Trump
Enter your year: 1950
Donald
'Your initials are DT and you are 68 years old.'
This seems to be thrown from declaration of main().
Check the main function whether you used double underscore( __ ) or triple underscore( ___ ).
the correct synax is if __name__ == '__main__':
Hope this helps! Cheers!

Validating correct spelling of user input in Python

How would a computer program deal with user misspelling of words in such a way that forces them to reenter until it is correct? e.g. Entering Male and Female for a gender argument. I'm using this Python code:
def mean(values):
length = len(values)
total_sum = 0
for i in range(length):
total_sum += values[i]
total_sum = sum (values)
average = total_sum*1.0/length
return average
name = " "
Age = " "
Gender = " "
people = []
ages = []
while name != "":
### This is the Raw data input portion and the ablity to stop the program and exit
name = input("Enter a name or type done:")
if name == 'done' : break
Age = int(input('How old are they?'))
Gender = input("What is their gender Male or Female?")
### This is where I use .append to create the entry of the list
people.append(name)
people.append(Age)
ages.append(Age)
people.append(Gender)
### print("list of People:", people)
#### useing the . count to call how many m of F they are in the list
print ("Count for Males is : ", people.count('Male'))
print ("Count for Females is : ", people.count('Female'))
### print("There ages are",ages)
### This is where I put the code to find the average age
x= (ages)
n = mean(x)
print ("The average age is:", n)
I would like to also force an age in the 18-25 range.
"... that forces them to reenter until it is correct?... "
Since you also asked for a way to re-enter, the following snippet uses an escape sequence of the form \033[<N>A which moves the cursor up N lines and the Carriage Return escape sequence, \r, to print over the invalid data and take input again.
import sys
age = 0
gender = ""
agePrompt = "How old are they? "
genderPrompt = "What is their gender Male or Female? "
#Input for age
print("")
while not ( 18 <= age <= 25 ):
sys.stdout.write( "\033[1A\r" + " " * (len(agePrompt) + len(str(age))) )
sys.stdout.write( "\r" + agePrompt )
sys.stdout.flush()
age=int(input())
#Input for gender
print("")
while not ( gender == "Male" or gender == "Female" ) :
sys.stdout.write( "\033[1A\r" + " " * (len(genderPrompt) + len(str(gender))) )
sys.stdout.write( "\r" + genderPrompt )
sys.stdout.flush()
gender=str(input())
Another solution would be to use the escape sequence of the form \033[<N>D which moves the cursor backward N columns.
Simply use a while operator that continues until you have satisfied the condition you wish be satisfied.
Gender = ""
while Gender != "Male" or Gender != "Female":
Gender = raw_input("What is your gender, Male or Female?")
Just keep looping until they give a valid input. Do the same for the gender.
Age = ""
while True:
Age = int(input('How old are they?'))
if int(Age) >= 18 and int(Age) <= 25:
break

Categories