Variable not Defined in Python 3.5.1 - python-3.x

I am a new coder with Python and I was wondering how I can fix this bug. Every time i put in the correct input in the code that I have, it spits out an error message, like so.
The code
total = 12
print ("I will play a game, you will choose 1, 2, or 3, and I will do the same, and I should always win, do you want to play?")
yesnoA = input("Yes or No?")
if yesnoA == yes:
print ("Yay, your turn!")
turnAA = input('Your First Move')
if turnAA == 1:
print ("I choose 3")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 2:
print ("I choose 2")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 3:
print ("I choose 1")
total = total - 4
print ("Total = ",total)
else:
print ("Cheater, try again")
else:
yesnoB = input("Ok, you sure?")
if yesnoB == yes:
print ("Yay, your turn")
turnAA = input('Your First Move')
if turnAA == 1:
print ("I choose 3")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 2:
print ("I choose 2")
total = total - 4
print ("Total = ",total)
else:
if turnAA == 3:
print ("I choose 1")
total = total - 4
print ("Total = ",total)
else:
print ("Cheater, try again")
else:
print ("Well, goodbye")
The Output
Yes or No?yes
Traceback (most recent call last):
File "C:/Users/*user*/Desktop/Code/Python/Nim Game.py", line 5, in <module>
if yesnoA == yes:
NameError: name 'yes' is not defined
This is in version 3.5.1

You need to either declare a variable yes with a value 'yes', or compare your variable yesnoA with a string 'yes'. Maybe something like this:
if yesnoA.lower() == 'yes': # using lower(), so that user's input is case insensitive
# do the rest of your work
Your code afterwards has some more issues. I will give you a clue. input always returns the user's input as string. So if you need integer from user, you will have to convert the user input into integer using int(your_int_as_string) like so:
turnAA = int(input('Your First Move'))
# turnAA is now an integer, provided the user entered valid integer value
Your take from this question on SO:
Look at the Traceback. It says clearly which line the error is in, and also what the error is. In your case it is NameError
Take a look at docs for NameError
Study this tutorial. It will help you get used to with some basic errors commonly encountered.

You have not defined the variable yes. You should do something like:
yes = "Yes"
At the start of the code

You're attempting to compare yesnoA to a variable named yes, which, indeed was not defined, instead of the string literal 'yes' (note the quotes!). Add the quotes and you should be fine:
if yesnoA == 'yes':
# Here --^---^

Related

python simple help (NameError: name is not defined)

Whenever I run this is get:
Traceback (most recent call last):
File "main.py", line 130, in <module>
while is_playing_cg:
NameError: name 'is_playing_cg' is not defined
I want the user to be able to press 1 or 2 to select which game mode to use and then once pressed it starts. I don't know why it's doing this. Whenever it's fixed it should run through just fine.
New edit
Now it just loops and says 1 or 2 over and over again.
import random
is_playing_cg = False
is_playing_hg = False
def game_select_screen():
#Game Select Screen
print("""
._________________________________.
| |
| ~ Welcome To Guess-A-Number ~ |
| ~~~ |
| ~ Press 1 OR Press 2 ~ |
| You ^ Guess | PC ^ Guess |
|_________________________________|""")
selecting = True
while selecting:
print()
game_mode = input("1 OR 2: ")
try:
int(game_mode)
except ValueError:
print("This is not a Number.")
else:
game_mode = int(game_mode)
if game_mode == 1:
is_playing_hg = True
elif game_mode == 2:
is_playing_cg = True
#Defining Random Number for human guess
def play_human_guess():
num = random.randint (1,10)
print()
print("Im Thinking of a Number 1 Through 10.")
print("You Have 3 Chances.")
chances = 3
game_fisnished = False
#Game is playing (Human Guesses)
while not game_fisnished:
guess = input("> Take A Guess: ")
#Accept only numbers
try:
int(guess)
except ValueError:
print("This is not a Number.")
else:
guess = int(guess)
if guess < num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too Low. ("+str(chances)+") Chance(s) Remaining.")
elif guess > num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too High. ("+str(chances)+") Chance(s) Remaining.")
else:
print()
print("Congradulations, You Won!")
game_fisnished = True
#Game Ended
def end():
print()
print("Thanks For Playing!")
#Setting up for computer guess
def play_computer_guess():
print()
print("Pick a Number 1 Through 10")
print("I Have 3 Chances to Guess Your Number.")
chances = 3
game_fisnished = False
#Game is playing (Computer Guess)
while not game_fisnished:
guess1 = input("Is your number 5?")
#Show Game Select Screen
game_select_screen()
while is_playing_cg:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while is_playing_hg:
#Start Game
selecting = False
play_human_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_hg = False
end()
The variable is_playing_cg is only available in the "block" that creates it.
Block is function / loop / if statement / etc.
In your program you need to initialize the variable globally so you can call them in multiple functions.
Good luck!
You are defining is_playing_cg inside of a conditional statement at the top of your code. So if that option is not selected, then when you get to the latter conditional statement, it has never heard of that variable.... and it is not defined in the namespace. So you could either define it at the top and give it a default (False) or more better, because you only have 2 options, just use one variable to control the computer / human.
Here is a toy example:
selection = int(input('enter 1 for human, 2 for computer: '))
if selection == 1:
human_play = True
elif selection == 2:
human_play = False
else:
# make some loop that asks for input again or such...
pass
# later on...
if human_play:
# ask human for input...
else:
# have AI make turn
#if needed, you can also handle special cases like this:
if not human_play:
# do something unique to computer turn ...
Additional info...
So you got bit by the scope of the variables in your update. You are defining these variables inside of a function and when you put the defaults outside of the function, they are not in the same scope, so whatever you do inside the function is lost. So, you need to change your function into something that returns the mode you want, and catch that in the function call like such:
def ... :
# input ...
if game_mode == 1:
human_playing = True
selecting = False
elif game_mode == 2:
human_playing = False
selecting = False
return human_playing # this will return T/F back to the function call
And then later:
#Show Game Select Screen
human_playing = game_select_screen()
while not human_playing:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while human_playing:
#Start Game
This (above) works for me, but there are still other logic errors popping up! :) Have fun
This particular error is probably there because you have not defined is_playing_cg as global before using it in your function game_select_screen. Simply put global is_playing_cg at the start of your game_select_screen function to tell python you want to use the global variable instead of creating a scoped variable.

We are getting an error with this while loop but cannot see why

The error we are getting is that it is looping infinitely and does not appear to be picking a number to be the correct choice
import random
print ("Guess a random number between 1 and 10")
number = random.randint(1,10)
guessTaken = 0
print ("Guess!")
guess = int( input())
while guessTaken < 6:
guess != guess+1
print ("Wrong!, guess again")
if guess == input():
print ("Correct")
print ( )
The loop's termination is based on the value of guessTaken; since that is never changed, once the loop is entered, it will never end.
Your code has many mistakes but I will try my best to fix them here:
First of all guess != guess+1 serves no purpose you are checking if guess is not equal to guess+1 (it isn't) which means that this line is always returning True and you aren't event doing anything with it.
I believe you meant to write:
guessTaken += 1
Which increments the number of guesses taken by 1
Next you will need to convert the second input to an int to compare it to guess so I recommend doing:
if guess == int(input()):
instead of
if guess == input():
Finally I suspect you want to exit the loop once the number has been guessed so I would add a break statement in the if condition as such:
if guess == int(input()):
print ("Correct")
break
You have many mistakes in your code. Not sure what you need, but you can try below:
import random
print ("Guess a random number between 1 and 10")
number = random.randint(1,10)
guessTaken = 0
wrong = True
print (number)
guess = int( input())
while guessTaken < 6: #Maximum guesses are 6
if guess != number:
print ("Wrong!, guess again")
guess = int( input())
else:
print ("Correct")
break #remember to put break when found correct number
guessTaken += 1
if guessTaken == 6:
print ("Maximum guessed")
I have tried to modify your code:
import random
print ("Guess a random number between 1 and 10")
number = random.randint(1,10)
guessTaken = 1
while guessTaken < 6:
if guessTaken == 1:
print('Guess!')
guess = input()
else:
print('Guess Again')
guess = input()
if int(guess) == number:
print('Correct')
break
else:
print('Wrong')
guessTaken = guessTaken + 1 #counter

Python 3 Count and While Loop

I am trying to figure out an error in the code below. I need the following conditions to be met:
1) If equal to zero or lower, I need python to state "Invalid Input"
2) If greater than zero, ask whether there is another input
3) As long as there is another input, I need the program to keep asking
4) If "done", then I need Python to compute the lowest of inputs. I have not gotten to this part yet, as I am getting an error in the "done" portion.
print ("Lowest Score for the Racer.")
number = float(input("Please enter score: "))
if number < 0 or number == 0:
print ("Input should be greater than zero.")
while True:
number = float(input('Do you have another input? If "Yes" type another score, if "No" type "Done": '))
if number < 0 or number == 0:
print ("Input should be greater than zero. Please enter score: ")
if number == "Done":
print ("NEED TO COUNT")
break
I tried to modify your code according to your desired output. I think this should give you an idea. However there is still small things to deal in code. I suppose you can manage rest of it.
empthy_list = []
print ("Lowest Score for the Racer.")
while True:
number = float(input("Please enter score: "))
if number < 0 or number == 0:
print ("Input should be greater than zero.")
if number > 0:
empthy_list.append(number)
reply = input('Do you have another input? If "Yes" type another score, if "No" type "Done": ')
if reply == "Yes" :
number = float(input("Please enter score: "))
empthy_list.append(number)
if reply == "Done":
print("NEED TO COUNT")
print("Lowest input is: ",min(empthy_list))
break
I wrote an alternative solution which is more robust regarding input errors. It might include some ideas for improving your code but probably isn't the best solution, either.
print ("Lowest score for the racer.")
valid_input = False
num_arr = []
while not valid_input:
foo = input('Please enter score: ')
try:
number = float(foo)
if number > 0:
num_arr.append(number)
valid_input = True
else:
raise ValueError
while foo != 'Done' and valid_input:
try:
number = float(foo)
if number > 0:
num_arr.append(number)
else:
raise ValueError
except ValueError:
print('Invalid input! Input should be number greater than zero or
"Done".')
finally:
foo = input('Do you have another input? If yes type another score,
if no type "Done": ')
except ValueError:
print('Invalid input! Input should be number greater than zero.')
print("Input done! Calculating lowest score...")
print("Lowest score is ", min(num_arr))

Python variable checking

How would I get Python to check a variable to see if it is an integer and below a specific number then carry on depending on the result perhaps breaking from a loop.
so something roughly like this:
x = input
if x is integer AND below 10:
print ("X is a number below 10")
break from loop
elif x is NOT an integer:
print ("X is not an integer try again")
ask again
Else:
print ("Error")
ask again
pretty sure this works :D thanks
while True:
x = input("Enter Something: ") #user input
if x.isdigit() == True:
if (int(x)>=1) and (int(x)<=2): #if it is 1 or 2
print (x)
break
elif (int(x)>2): #or if its above 2
print ("To Large")
else:
print ("Else")
elif x.isdigit() == False: #data non integer
print ("please try again")
else:
print ("ERROR") #error with input
print ("Hello") #show the loop broke correctly

i want to setup a score count in python 3.3.2

**count = 0**
player = input("Player Name: ")
print("WELCOME TO MY QUIZ %s" % player, )
print("Would You like to play the quiz ??")
start = input()
if start == "Yes" or start == "yes":
print("Lets Start %s" % player, )
print("Q1. What is the capital of India ?")
print("A. Delhi")
print("B. Mumbai")
q1 = input()
if q1 == "A":
**count += 1**
else:
print("")
print("Q2. How many states are there in India ?")
print("A. 28")
print("B. 29")
q2 = input()
if q2 == "B":
count += 1
else:
print("")
print("Q3. What is the capital of Maharashtra ?")
print("A. Delhi")
print("B. Mumbai")
q3 = input()
if q3 == "B":
count += 1
else:
print("")
***print("You got"),str(count)+"/3 right!"***
else:
print("Thank You, Goodbye")
I have done this so far but im not getting the proper score any help ?
I dont get any output regarding the score or the count
i only get "You Got:
that's it
You are not using print() correctly.
Print the score with
print("You got {0}/3 right!".format(count))
print("You got"), str(count)+"/3 right!"
is a tuple. print("You got") is a function call in Python3; it prints to the screen but returns None. str(count)+"/3 right!" is a string. The comma between the two expressions makes the combined expression a tuple. You don't see the second part because it was never passed to the print function. Python just evaluates the expression and then leaves it to get garbage collected since it is not assigned to anything.
So to fix your code with minimal changes, move the parenthesis and remove the comma:
print("You got" + str(count) + "/3 right!")
But building strings with + is not recommended.
Matt Bryant shows the preferred way. Or, since you are using a Python version greater than 2.6, you can shorten it a wee little bit:
print("You got {}/3 right!".format(count))
The {} gets replaced by count. See The Format String Syntax for more info.
Also, instead of multiple calls to print:
print("Lets Start %s" % player, )
print("Q1. What is the capital of India ?")
print("A. Delhi")
print("B. Mumbai")
you can print a single multiline string:
print("""Lets Start {}
Q1. What is the capital of India ?
A. Delhi
B. Mumbai""".format(player))
Fewer function calls makes it faster, and it is more readable and requires less typing.
I think you do it like this. (Not Sure)
score = 0
ans = input('What is 2+2')
if ans == '4':
print('Good')
score = +1
else:
print('Wrong')
score = +0
To Show The Score Do This
print(score, 'Out Of 1')

Resources