I'm making a short little test, and I'm planning to have achievements and such. However the code doesn't work
All of this is the achievements and the variables, this message is displayed after reaching this point:
Traceback (most recent call last): File "<string>", line 106, in
<module> NameError: name 'leader' is not defined
if sad == 1:
if fear == 0 and leader == 1 and known == 1:
print("Congrats, you are the 'Foolish Leader'1/13")
elif fear == 1 and leader == 1 and known == 0:
print("Congrats, you are the 'Smart, yet scared Leader'2/13")
elif fear == 0 and leader == 1 and known == 0:
print("Congrats, you are the 'Smart Leader'3/13")
elif fear == 1 and leader == 0 and known == 1:
print("Congrats, you are the 'Scared Fool'4/13")
elif sad == 1 and coward == 1:
print("Congrats, you are the 'Sad Coward'5/13")
elif fear == 1 and coward == 1:
print("Congrats, you are the 'Scared Coward'6/13")
elif sad == -1:
if mind_changed == 1:
print("Congrats, you can't make up your mind.7/13")
elif mind_changed == 0:
print("Congrats, you can make up your mind.8/13")
elif insane == 1:
print("Congrats, you are a horrible person and I never want to see you again.9/13")
elif lazy == 1:
print("Congrats, you are lazy.10/13")
elif suic == True:
print("I hope that you're ok.11/13")
elif envy == 1:
print("Congrats, you're a good person.12/13")
elif fear == 1:
print("Congrats, you're scared easily.13/13")
if suic == True:
print("I hope you're ok.... Due to you choosing 'C' on the Multiple Choice, I suggest you stop playing.?/13")
I was expecting to get achievements and such.
The error you posted Traceback (most recent call last): File "<string>", line 106, in <module> NameError: name 'leader' is not defined tells you that on line 106 your program tries to access the variable 'leader' without it being defined first.
Are you defining this variable before you use it (e.g. leader = 0)? Maybe you're defining it in an if-statement which might not always execute?
Related
so basically I am trying to figure out how to make an error return if the user inputs the incorrect string type. For example, if someone were to type "y" instead of the six button on the keyboard, because they were typing their score to get the grade in the program, what would I do? I tried using an else statement to say that there was an error, but PyCharm gives me the green checkmark and then my program errors out saying:
Traceback (most recent call last): line 3, in
if int(score) >= 90: ValueError: invalid literal for int() with base 10: 'H'
this is confusing to me as I would think that the code would be read by the interpreter as checking if the input was an integer and then moving on through all the elifs i typed, then into the else statement, but I am wrong. What would be a better way to do this? Here is my code I wrote.
score = input("type your score on the exam as an integer to receive your letter grade\n")
if int(score) >= 90:
print("A")
elif int(score) >= 80:
print("B")
elif int(score) >= 70:
print("C")
elif int(score) >= 60:
print("D")
elif int(score) < 60:
print("F")
else:
input("ERROR: type your score on the exam as an integer to receive your letter grade\n")
Normally, you would wrap your "user menu" with a while, like this:
while True:
score = input("type your score on the exam as an integer to receive your letter grade\n")
try:
score = int(score)
except ValueError:
print("That's not an int!")
continue
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
elif score < 60:
print("F")
else:
print("Please write a valid option")
You can also add an option for user to leave or just let them press CTRL + C to close the process.
So i'm trying to do a turtle controller program in Python but a message appears saying:
Traceback (most recent call last):
File "C:\Users\Sony\Desktop\PythonCode\TurtleController.py", line 35, in <module>
string_artist(t_program)
NameError: name 'string_artist' is not defined
I've tried removing the string_artist and the problem didn't occur anymore. However without string_artist the turtle controller doesn't work anymore.
from turtle import *
def turtle_controller(do, val):
do = do.upper()
if do == 'F':
forward(val)
elif do == 'B':
backward(val)
elif do == 'R':
right(val)
elif do == 'L':
left(val)
elif do == 'U':
penup()
elif do == 'D':
pendown()
elif do == 'N':
reset()
else:
print('unrecognized command')
instructions = '''Enter a program for the turtle:
example F100
N = New drawing
U/D = Pen Up/Down
F100 = Forward 100 (you can choose another number if you want)
B50 = Backwards 50
R90 = Right 90 deg
L45 = Left 45 deg'''
screen = getscreen()
while True:
t_program = screen.textinput('Deseneaza in Python!', instructions)
print(t_program)
if t_program == None or t_program.upper() == 'END':
break
string_artist(t_program)
Exception Name: EOFError
Exception Message: EOF when reading a line
The code failed some test cases due to this error which was shown in line number 1,the test case failed where always different:
t=int(input())
for _ in range(t):
n=int(input())
x=n%12
if x==1:
print(n+11,"WS")
elif x==2:
print(n+9,"MS")
elif x==3:
print(n+7,"AS")
elif x==4:
print(n+5,"AS")
elif x==5:
print(n+3,"MS")
elif x==6:
print(n+1,"WS")
elif x==7:
print(n-1,"WS")
elif x==8:
print(n-3,"MS")
elif x==9:
print(n-5,"AS")
elif x==10:
print(n-7,"AS")
elif x==11:
print(n-9,"MS")
elif x==0:
print(n-11,"WS")
This was the code which passed all the test cases:
for _ in range(int(input())):
n=int(input())
x=n%12
if x==1:
print(n+11,"WS")
elif x==2:
print(n+9,"MS")
elif x==3:
print(n+7,"AS")
elif x==4:
print(n+5,"AS")
elif x==5:
print(n+3,"MS")
elif x==6:
print(n+1,"WS")
elif x==7:
print(n-1,"WS")
elif x==8:
print(n-3,"MS")
elif x==9:
print(n-5,"AS")
elif x==10:
print(n-7,"AS")
elif x==11:
print(n-9,"MS")
elif x==0:
print(n-11,"WS")
So is there a difference when you take the input inside the loop and when you take the input outside one?
Both of your code snippets are raising EOFError but this was because I pressed Ctrl+D on my keyboard, and input() is designed to raise EOFError in this case. But if I type the numbers on each line without pressing Ctrl+D then both of your code snippets work just fine.
To answer your question, there is no difference whether you call input() inside or outside a loop. Since you're dealing with standard input which is a terminal, the EOFError comes from pressing Ctrl+D.
As one of my first projects trying to learn python I decided to make an RC car. But now I've been stuck with the same 2 problems for a long time, and can't find a real good answer. In my code for the moment, I connect to my raspberry through bluetooth from my phone. When I send simple commands, the care moves. But I also added 3 sensors so I could build some sort of autopilot, where the car evades objects in his path.
My code: https://pastebin.com/ggUFcrpT
def serialread():
while True:
line = ser.read()
print line
if line == 's':
ser.write("Abandom ship! \n")
resetmotorpins()
elif line == 'f':
ser.write("Going forward, captain! \n")
resetmotorpins()
forward()
elif line == 'r':
ser.write("Dizzy! \r\n")
resetmotorpins()
right()
elif line == 'l':
ser.write("If nothing goes right, go left! \n")
resetmotorpins()
left()
elif line == 'b':
ser.write("nah fam, i'm out, f*ck this shiet. \r\n")
resetmotorpins()
reverse()
elif line == "t":
ser.write("autoPilot activate \n")
auto = 1
resetmotorpins()
while auto == 1:
line = ser.read()
if line == "y":
ser.write("autoPilot deactivated \n")
resetmotorpins()
auto = 0
else:
meet()
elif line == "m":
meet()
elif line == 'o':
servomotorright()
elif line == 'x':
servomotorleft()
elif line == 'q':
waardesVragen()
I think it gets stuck at the line = ser.read() and that it needs a line to run through the code. But I have no idea how to make it just loop constantly and make somekind of interupt when I send a letter/command.
On top of that I'm trying to initialize mulithreading so I can print my values from the 3 sensor constantly and make an interrupt when it's close to hitting an object. But the multithreading seems to not be working, once I got into the sensor value printing, it never leaves that loop and doesn't listen to my bluetooth connection anymore.
Any suggestions? I hope I posted this right, it's my first question here.
I'm using python 2.7.5 on a raspberry pi B
I am using Python and I am trying to write a simple program that simulates a rock, paper, scissors game. Everything works except for when I enter an invalid response (something other than rock, paper, or scissors) when I get this error.
Traceback (most recent call last):
File "C:/Users/home/Desktop/BAGARDNER/Python/rock_pape_scissors.py", line 88, in <module>
main()
File "C:/Users/home/Desktop/BAGARDNER/Python/rock_pape_scissors.py", line 14, in main
number = user_guess()
File "C:/Users/home/Desktop/BAGARDNER/Python/rock_pape_scissors.py", line 48, in user_guess
return number
UnboundLocalError: local variable 'number' referenced before assignment
I understand that this is telling me that number isn't referenced, but from what I understand of the code, it shouldn't need a number when the qualifier is false.
#import random module
import random
#main function
def main():
#intro message
print("Let's play 'Rock, Paper, Scissors'!")
#call the user's guess function
number = user_guess()
#call the computer's number function
num = computer_number()
#call the results function
results(num, number)
#computer_number function
def computer_number():
#get a random number in the range of 1 through 3
num = random.randrange(1,4)
#if/elif statement
if num == 1:
print("Computer chooses rock")
elif num == 2:
print("Computer chooses paper")
elif num == 3:
print("Computer chooses scissors")
#return the number
return num
#user_guess function
def user_guess():
#get the user's guess
guess = input("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
#while guess == 'paper' or guess == 'rock' or guess == 'scissors':
if is_valid_guess(guess):
#if/elif statement
#assign 1 to rock
if guess == 'rock':
number = 1
#assign 2 to paper
elif guess == 'paper':
number = 2
#assign 3 to scissors
elif guess == 'scissors':
number = 3
return number
else:
print('That response is invalid.')
user_guess()
def is_valid_guess(guess):
if guess == 'rock' or 'paper' or 'scissors':
status = True
else:
status = False
return status
def restart():
answer = input("Would you like to play again? Enter 'y' for yes or \
'n' for no: ")
#if/elif statement
if answer == 'y':
main()
elif answer == 'n':
print("Goodbye!")
else:
print("Please enter only 'y' or 'n'!")
#call restart
restart()
#results function
def results(num, number):
#find the difference in the two numbers
difference = num - number
#if/elif statement
if difference == 0:
print("TIE!")
#call restart
restart()
elif difference % 3 == 1:
print("I'm sorry! You lost :(")
#call restart
restart()
elif difference % 3 == 2:
print("Congratulations! You won :)")
#call restart
restart()
main()
Thank you for your help!
Here's your problem:
if guess == 'rock' or 'paper' or 'scissors':
This line in is_valid_guess doesn't do what you think it does. Instead, it always returns True. What you're looking for is something like this:
if guess == 'rock' or guess == 'paper' or guess == 'scissors':
or more concisely:
if guess in ('rock', 'paper', 'scissors'):
The problem is that what you have always returns True because of how Python evaluates strings in a boolean context. The line if guess == 'rock' or 'paper' or 'scissors': evaluates as:
if (guess == 'rock') or ('paper') or ('scissors'):
What this means is that Python checks to see if guess == 'rock'. If that's true, the conditional evaluates to True. If it's false, the interpreter tries to evaluate bool('paper'). This always evaluates to True because all non-empty strings are "truthy". Therefore, your whole conditional is always True, and every string is "valid".
As a result, your code considers all strings "valid" and then blows up when it fails to assign a number to a guess that is not actually supported.
As a final note, your is_valid_guess method could be trimmed a bit, since you're just returning the result of your boolean expression. Rather than using the status variable as an intermediate, you can just compute the expression and return it right away. I also use the lower() method of string objects to allow for case-insensitive guessing, in case that's something you want to allow.
def is_valid_guess(guess):
return guess.lower() in ('rock', 'paper', 'scissors')
You've got another issue, which you mentioned in the comments: you've implemented user_guess in a recursive fashion, so that it calls itself if the user enters an invalid guess. However, in this case, it does not return the result of the recursive call. You need to either return the recursive result by changing the last line of user_guess to:
return user_guess()
Or else you should make that function use a loop instead of recursion, which is what I would do, since the function is not inherently recursive. You can do something like this:
def user_guess():
# get first guess
guess = input("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
# If that guess is invalid, loop until we get a valid guess.
while not is_valid_guess(guess):
print('That response is invalid.')
guess = input("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
# Now assign the (valid!) guess a number
# This dictionary is just shorthand for your if/elif chain.
guess_table = {
'rock' : 1,
'paper' : 2,
'scissors' : 3
}
# Return the number associated with the guess.
return guess_table[guess.lower()]
Change
if guess == 'rock' or 'paper' or 'scissors':
to
if guess == 'rock' or guess == 'paper' or guess == 'scissors':
In fact, to make the function as streamlined as possible, just do this:
def is_valid_guess(guess):
return guess == 'rock' or guess == 'paper' or guess == 'scissors'
As other users have pointed out, you need to change your validation in is_valid_guess to:
if guess == 'rock' or guess == 'paper' or guess == 'scissors':
While this won't solve your immediate problem, it is good (upvote-worthy) advice, and will let you avoid some errors you would have run into.
Additionally, no matter what the user inputs, you always return what they type in. To prevent this, you must return user_guess() in your else block:
if is_valid_guess(guess):
#if/elif statement
#assign 1 to rock
if guess == 'rock':
number = 1
#assign 2 to paper
elif guess == 'paper':
number = 2
#assign 3 to scissors
elif guess == 'scissors':
number = 3
return number
else:
print('That response is invalid.')
return user_guess() # <-- right here
Just change input to raw_input