Python - NameError name [variable] is not defined - python

Original question for context:
I was working on a quick little password program and came across the error:
NameError name 'confirm' is not defined.
I am using Python 3.3, I am trying to use a password then enter no (2) it then supplys me with the error.
Here is my code:
password=input ("Enter a password: ")
print ('Are you sure ' +password+ ' is a safe password?')
print ("1. YES")
print ("2. NO")
confirm=input ("Insert a number: ")
if comfirm is 2:
password=input ("Enter a password: ")
print ('Are you sure ' +password+ ' is a safe password?')
print ("1. YES")
print ("2. NO")
confirm=input ("Insert a number: ")
if confirm is 2:
password=input ("Enter a password: ")
print ('Are you sure ' +password+ ' is a safe password?')
print ("1. YES")
print ("2. NO")
confirm=input ("Insert a number: ")
Edit, a few years later:
Please ensure you always look over your code for spelling and syntaxical mistakes, especially in new lines of code you have just deployed/built/executed. Mistakes can range from spelling mistakes to incorrect case or to syntax and beyond.

Just a typo error-if comfirm is 2:

Related

Python: How do I make it so that an input has to match the input entered previously

this is my first day of coding in python so I don't know how "clean" my code is. I am trying to make a fun piece of code, that makes you add your name, and correctly re-enter it right after
name = input ("Insert name:")
print ("re-enter your name")
answer = name
if answer == name
print ("excellent")
elif
print ("You have entered the wrong name")
exit()
since you create variable answer = name, the result will always be true because the answer variable and name variable will have the same contents in memory.
Oh yes, I ran your code and there was an error. After the code if some_condition must be added a colon after it in one line, elif is like that, in using elif you must have a conditional after elif and then a colon. If you only have one conditional for the if, then use else instead of elif.
Here's your code after fixing:
name = input("Insert name:")
answer = input("re-enter your name")
if answer == name:
print ("excellent")
else:
print ("You have entered the wrong name")
exit()
CMIWW
You need to take a second input to re-enter your name. answer=name is basically assigning answer name. So you will always end up with answer==name
Also, a colon missing after if.... The elif statement is completely useless. You might want to use else there because you only want answer==name else redirect them to You have entered the wrong name
name = input ("Insert name: ")
answer = input("re-enter your name: ")
if answer == name:
print ("excellent")
else:
print ("You have entered the wrong name")
Output 1:
Insert name: John
re-enter your name: jon
You have entered the wrong name
Output 2:
Insert name: Mike
re-enter your name: Mike
excellent
name = input("Insert your nme : ")
rename_name = input("Re-enter your name : ")
if name == rename_name:
print("excellent")
else:
print("You have entered the wrong name")
It's unclear whether objective is just to verify that second entry is same as first or make sure that they match. If latter then second input must be in loop ('while first answer is not equal to second print warning and ask again, if answers match print Excellent') :
first = input("Enter your name: ")
while first != input("Enter your name again: "):
print("Names entered don't match!")
else:
print('Excellent')
Here is one of the cleanest code you would like😊😊😊 You don't have to exit from condition using any exit function. And in second line, you were just printing "re-enter your name: " not receiving any inputs.
name = input ("Insert name: ")
answer = input("re-enter your name: ")
print ("excellent" if answer == name else "You have entered the wrong name")

Ending the program without the rest - need support

I have wrote this simple login and registartion program:
import os
from os import path
def start():
startup = input ('are you an existing user? y/n : ')
if startup == "y":
print ("Lets login then")
login()
if startup == "n":
print ("Lets make you an account")
new_account()
else:
print ("That is an invalid input, please try again")
start()
def new_account():
new_username = input ('what do you want your username to be? ')
print ('okay...')
new_pass = input ('your new password... ')
checker_pass = input ('retype it... ')
if new_pass == checker_pass:
print ('you have entered correct passwords')
print ('Now please login ')
print (' ')
print ('..................................')
print (' ')
saveFile = open( new_username + '.txt','w')
saveFile.write(new_pass)
saveFile.close()
login()
else:
print ('you have done something wrong. Please start again')
new_account()
def login():
print (' ')
print ('..................................')
print ("")
user_name = input ('enter username: ')
file_check = path.exists(user_name + '.txt')
if file_check == False:
print ("That username dosent exist, please start again")
start()
if file_check == True:
Pass_check = open(user_name + '.txt' , 'r').read()
password = input ('enter your password: ')
if Pass_check != password:
print('That didnt quite match. Please start again')
start()
elif Pass_check == password:
print ('Welcome to your account.')
start()
once i have entered a valid username or password it then says:
That is an invalid input, please try again
are you an existing user? y/n :
this is part of the program but isnt supposed to occur once you have been welcomed to your account.
has anyone got a soulution so that once you recieve "welcome to your account" nothing else happens.
i would like it done so that the program dosent fully stop as im looking to put this code into another program.
thanks fin.
THE OUTPUT:
are you an existing user? y/n : y
Lets login then
..................................
enter username: finndude
enter your password: test
Welcome to your account.
That is an invalid input, please try again
are you an existing user? y/n :
i dont want the last two lines to appear
Add a boolean flag value to the start() function that says whether to display the line or not. When calling from login() pass True, when calling recursively from start() then pass False.

I'm trying to make a quiz on Python but my code keeps repeating

So, I'm trying to make a basic quiz in Python and when I get to a certain point when I'm testing the program my code will repeat for reasons I can't seem to work out...
My code:
`if choice == "2": #If the user enters 2 they will be taken here.
print (" ") #Makes a break between lines.
username=input ("Please enter your username:")
print (" ") #Makes a break between lines.
password=input ("Please enter your password:")
file=open ("userinformation.txt","r")
for line in file:
if username and password in line:
print (" ") #Makes a break between lines.
print ("Thank you for logging in " + username+".")
time.sleep (3)
#file.close()
print (" ") #Makes a break between lines.
print ("Please choose a topic and a difficulty for your quiz.")
time.sleep (4)
print (" ") #Makes a break between lines.
print("a.History - Easy.")
print (" ") #Makes a break between lines.
print("b.History - Medium.")
print (" ") #Makes a break between lines.
print("c.History - Hard.")
print (" ") #Makes a break between lines.
print("d.Music - Easy.")
print (" ") #Makes a break between lines.
print("e.Music - Medium.")
print (" ") #Makes a break between lines.
print("f.Music - Hard.")
print (" ") #Makes a break between lines.
print("g.Computer Science - Easy.")
print (" ") #Makes a break between lines.
print("h.Computer Science - Medium.")
print (" ") #Makes a break between lines.
print("i.Computer Science - Hard.")
print (" ") #Makes a break between lines.
topic = input("To choose a topic please enter the corrosponding letter:")
if topic == "a":
print (" ") #Makes a break between lines.
time.sleep(2)
print ("You have selected option a, History - Easy.") #Tells the user what subject they picked (Same result but with a different topic and difficulty displayed for each one
print (" ")
print ("Rules: You have an unlimited amount of time to anwser each question. You will be anwsering 2 questions and each question anwsered correctly")
print ("will reward you with 10 points.")
time.sleep(9)
print (" ")
print ("The maximum amount of points you can get is 20.")
time.sleep(3)
print (" ")
print ("Good luck!")
print (" ")
time.sleep(2)
print ("Question 1 -")
print ("When did World War 1 begin and end?")
print ("a. 1913 - 1917") #Incorrect anwser
print (" ")
print ("b. 1914 - 1919") #Incorrect anwser
print (" ")
print ("c. 1914 - 1918") #Correct anwser
anwserq1he = input ("Please pick an anwser:")
if anwserq1he == "b":
print(" ")
print("Sorry, that's the wrong anwser...")
time.sleep(3)
print(" ")
hisready = input ("Type ok when you are ready to proceed to the next question.")
elif anwserq1he == "a":
print(" ")
print("Sorry, that's the wrong anwser...")
time.sleep(3)
print(" ")
hisready = input ("Type ok when you are ready to proceed to the next question.")
elif anwserq1he == "c":
print(" ")
print ("That's the right anwser!")
print(" ")
time.sleep(2)
print ("Adding 10 points to your score...")
score = score +10
print(" ")
time.sleep(3)
hisready = input ("Type ok when you are ready to proceed to the next question.")
if hisready == "ok":
print(" ")
time.sleep(2)
print ("Question 2-")
print ("Which historical figure is commonly known as 'The lady with the lamp'?")
print ("a. Margaret Fuller")
print (" ")
print ("b. Florence Nightingale")
print (" ")
print ("c. Rosa Luxemburg")
anwserq2he = input ("Please pick an anwser:")
if anwserq2he == "a":
print ("Sorry, that's the wrong anwser...")
results = input("Please type results to get your results")
elif anwserq2he == "c":
print ("Sorry, that's the wrong anwser...")
results = input("Please type results to get your results")
elif anwserq2he == "b":
print (" ")
time.sleep(2)
print ("That's the right anwser!")
print(" ")
time.sleep(2)
print ("Adding 10 points to your score...")
score = score + 10
results = input("Please type results to get your results.")
if results == "results":
print(" ")
time.sleep(3)
print ("Getting your results...")
if score == 20:
print ("Congratulations, you scored 20 points. That's the best score you can get!")
elif score == 10:
print ("Well done, you scored 10 points. Almost there!")
elif score == 0:
print ("You scored 0 points. Try again and you might do better!")`
When I complete the quiz everything beyond print ("Thank you for logging in " + username+".")repeats...I'd appreciate it if anyone could help me. Thank you.
Sidenote: The #file.close is intentional.
Alright, so first of all we need to improve the program layout , maybe call in some functions would be useful. Here is some tips to fix the program.
First of all use : if username.strip() and password.strip() in line: [Use the .strip() function so it will match a word.
Your program is inefficient because if you press another value as in 2 it will break the program. You want to loop it and loop it over and over again therefore use the while True statement and create a function.
Add a function called exampleFunction() (I.E) and then on the bottom of the code ad this line but obviously indent it.
while True:
exampleFunction()
You don't need to use a or r just do file=open("your file.txt")
For example,
genre=input("What is the film you would like to search?: ")
f=open("Films.txt")
for line in f:
if genre in line.strip():
print(line)
I would personally fix this myself and post a copy of the code however this is too minor to fix therefore i'm leaving it to you.
Goodluck,
Matin

local variable referenced before assignment python issue

So I'm coding a small project and I'm struggling with a certain aspect so far.
Here is the code:
import re
def clientDetails():
print("Welcome to the InHouse Solutions Room Painting Price Calculator")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = input(">>>")
print("Please enter your post code")
postCode = input(">>>")
print("Is your house a number, or a name?")
nameOrNumber = input(">>>")
if nameOrNumber == "number" or nameOrNumber == "Number":
print("Please enter your house number")
houseNumber = input(">>>")
elif nameOrNumber == "Name" or nameOrNumber == "name":
print("Please enter your house name")
houseName = input(">>>")
else:
print("Invalid")
house = (houseNumber) + (houseName)
address = (postCode) + ", " + (house)
print("Thank you for your information")
print (userName)
print (address)
print (" ")
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = input(">>>")
if clientDetailsCorrect == "no" or clientDetailsCorrect == "No":
clientDetails()
clientDetails()
Not sure what's going wrong as I haven't actually referenced the variable anywhere else. Someone help.
It would help if you posted the traceback.
That said, this line is the likely source of the problem:
house = (houseNumber) + (houseName)
The way your code is currently written, only one of houseNumber or houseName will be defined. So Python is likely complaining about the missing one.
Given how your code looks so far, it's probably better to just do:
print("Please enter your house name or number")
house = input(">>>")
And remove the house = (houseNumber) + (houseName) line.
Try this:
def clientDetails():
print("Welcome to the InHouse Solutions Room Painting Price Calculator\n")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = raw_input(">>>")
print("Please enter your post code")
postCode = raw_input(">>>")
print("Please enter your hose number or name")
house = raw_input(">>>")
address = "{}, {}".format(postCode, house)
print("Thank you for your information.\n")
print (userName)
print (address)
print (" ")
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = raw_input(">>>")
if clientDetailsCorrect.lower().startswith('n'):
clientDetails()
Using raw_input is better, it will input everything as a string. Also it will allow users to not type quotations to input text (I assume you will run this from CLI). If you later on need to separate houses that are numbers from names Python has very good string methods you can use to do so many wonderful things, I used a couple of them to simplify your code :)
N

Python if statements [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am new to Python
I have a if: else statement.
my problem : right now after print "Welcome to the Script" my script exits , but I want it exits just after else and also when my condition was true continue to line name=raw_input("Enter your name: ") and so on not exit ...
How can I exit from the if else and continue in the script?
script_username="test"
script_password="1"
login_username=raw_input('Please Enter the script username:')
login_password=getpass.getpass('Please Enter the script password:')
if login_password == script_password and login_username == script_username:
print "Welcome to the Script"
else:
print "your Username or Password is false"
exit()
name=raw_input("Enter your name: ")
family=raw_input("Enter your family: ")
sex=raw_input("Enter your Sex: ")
print "hello " + sex + name + family
raw_input("press<enter>")
Try that (see the new indention)
script_username="test"
script_password="1"
login_username=raw_input('Please Enter the script username:')
login_password=getpass.getpass('Please Enter the script password:')
if login_password == script_password and login_username == script_username:
print " Welcome to the Script "
else:
print " your Username or Password is false "
exit()
name=raw_input("Enter your name: ")
family=raw_input("Enter your family: ")
sex=raw_input("Enter your Sex: ")
print "hello " + sex + name + family
raw_input("press<enter>")
I think I found the problem. getpass.getpass('prompt') doesn't return a string. Either fix that or use this:
script_username="test"
script_password="1"
login_username=raw_input('Please Enter the script username:')
login_password=raw_input('Please Enter the script password:')
if login_password == script_password and login_username == script_username:
print " Welcome to the Script "
else:
print " your Username or Password is false "
exit()
name=raw_input("Enter your name: ")
family=raw_input("Enter your family: ")
sex=raw_input("Enter your Sex: ")
print "hello " + sex + name + family
raw_input("press<enter>")
Output:
Please Enter the script username:test
Please Enter the script password:1
Welcome to the Script
Enter your name: Louis
Enter your family: Mom, Dad, Dog
Enter your Sex: Male
hello MaleLouisMom, Dad, Dog
press<enter>
IMPORTANT
This block:
name=raw_input("Enter your name: ")
family=raw_input("Enter your family: ")
sex=raw_input("Enter your Sex: ")
print "hello " + sex + name + family
raw_input("press<enter>")
was indented incorrectly in your question. It should be at the level below (i.e. no spaces) the stuff in the if statement. This would also break your program (because it'd think everything was in the if statement.
EDIT 2: Screenshot:

Categories

Resources