name string_artist is not defined - python-3.x

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)

Related

Getting "NameError: name 'leader' is not defined". What does this mean?

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?

My boolean flag isn't triggering when it's supposed to

At the play_again input, whenever I input "n" to end the loop, python seems to ignore it and prints :
Your cards: [x, x], current score: xx
Computers first card: x.
Would you like to draw another card? Press 'y' to draw or 'n' to stand.
Even though I have set end_game back to True.
What gives?
import random
from art import logo
from replit import clear
def deal_card():
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
card = random.choice(cards)
return card
def calculate_score(card_list):
if len(card_list) == 2 and sum(card_list) == 21:
return 0
if 11 in card_list and sum(card_list) > 21:
card_list.remove(11)
card_list.append(1)
return sum(card_list)
def compare(user, computer):
if user == computer:
return "I'ts a draw!"
elif user == 0:
return "You win with a BlackJack!"
elif computer == 0:
return "Computer wins with a BlackJack!"
elif computer > 21:
return "You win! Computer busts."
elif user > 21:
return "Computer wins, you bust!"
elif user > computer:
return "You win!"
else:
return "You lose!"
def main_loop():
print(logo)
user_cards = []
computer_cards = []
game_end = False
for _ in range(2):
user_cards.append(deal_card())
computer_cards.append(deal_card())
while not game_end:
user_score = calculate_score(user_cards)
computer_score = calculate_score(computer_cards)
print(f"Your cards: {user_cards}, current score: {user_score}")
print(f"Computers first card: {computer_cards[0]}.")
if user_score == 0 or computer_score == 0 or user_score > 21:
game_end = True
else:
play_again = input("Would you like to draw another card? Press 'y' to draw or 'n' to stand.")
if play_again == "y":
user_cards.append(deal_card())
else:
end_game = True
while computer_score != 0 and computer_score < 17:
computer_cards.append(deal_card())
computer_score = calculate_score(computer_cards)
print(f"Your final hand: {user_cards}, Your final score{user_score}.")
print(f"Computers final hand: {computer_cards}, Computers final score {computer_score}." )
print(compare(user_score, computer_score))
while input("Would you like to play a game of BlackJack?: ") == 'y':
clear()
main_loop()
else:
print('Goodbye!')
quit()
Please check your variable name game_end in "while not game_end:" loop,
if user_score == 0 or computer_score == 0 or user_score > 21:
game_end = True
else:
play_again = input("Would you like to draw another card? Press 'y' to draw
or 'n' to stand.")
if play_again == "y":
user_cards.append(deal_card())
else:
end_game = True
I think it's "game_end" in else: , you put end_game , please change it, other function working fine.

Python IDLE TypeError: int object not subscriptible

I am making a code that makes a map (not visible), and you can move in it.
I have been working on this code for a week now.
It has a TypeError.
import map
def basicRealm():
player=[0,0]#this is you
Home=[0,0]
Shops=[2,7]
Park=[8,2]
locations = [Home, Shops, Park]
desternation=Park
RealmSize = grid(10)
choice = input("Move north, south, east, or west?[north/south/east/west]")
no = int(input("Number of spaces to move: "))
if choice=='north':
axis=y
elif choice=='south':
axis=y
elif choice=='east':
axis==x
elif choice=='west':
axis=x
else:
pass
nothing=''
if choice=='south' or choice=='east':
no = 0 - no
else:
pass
you_are_here = move(no, player, axis)
basicRealm()
And my map module to run it is :
def atDesternation(location):
global desternation
if desternation==location:
return True
else:
return False
def atLocation(Object,locations):
pos = position(Object)
for i in locations:
if pos==i:
return i
else:
return None
def position(Object):
pos = (Object[0], Object[1])
return pos
def grid(size):
size = ListRange(0, size)
return size
def move(spaces, thing, axis):
here= position(thing)
pos = here[axis] + spaces
return pos
The Output is as follows:
Move north, south, east, or west?[north/south/east/west]north
Number of spaces to move: 1
Traceback (most recent call last):
File "C:\Users\lewis\Desktop\Map1.py", line 35, in <module>
basicRealm()
File "C:\Users\lewis\Desktop\Map1.py", line 29, in basicRealm
print(position(you_are_here))
File "C:\Users\lewis\Desktop\map.py", line 13, in position
pos = (Object[0], Object[1])
TypeError: 'int' object is not subscriptable
>>>
How do I solve this error? Please help.
I am newish to Python and find it very hard to slove Errors.

TypeError: list indices must be integers, not _io.TextIOWrapper

I am trying to search for a certain number within a Text Document. It reads the file fine, and using the same code later can print fine, but when I tell it to find a certain number in the Text Document it tells me TypeError: list indices must be integers, not _io.TextIOWrapper. I have looked all around but all questions say 'not str' whereas mine says 'not _io.TextIOWrapper'
This is my code (I am going down route 'A' under 'menuOptions'
import time
import linecache
print("Welcome to the League Fixture Manager!")
time.sleep(3)
print("What would you like to do?")
time.sleep(1)
print("Press A to search for a fixture.")
time.sleep(0.1)
print("Press B to view Outstanding fixtures.")
time.sleep(0.1)
print("Press C to display the leader board")
time.sleep(0.1)
print("Or press Q to quit, this will exit the application.")
time.sleep(0.1)
menuOptions = input("What would you like to do? A, B, C, or Q.")
if menuOptions == 'A':
print("Please enter the fixture number you are looking for... ")
fixtureQuestion = input(int())
fixtureQuestion = int(fixtureQuestion)
fixtureQuestion = fixtureQuestion - (1)
time.sleep(3)
if fixtureQuestion < 1:
print("This fixture is not available, please re-run the application...")
time.sleep(2)
exit()
elif fixtureQuestion > 190:
print("This fixture is not available, please re-run the application...")
time.sleep(2)
exit()
else:
searchData = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\\firesideFixtures.txt")
lines = searchData.readlines()
print(lines[searchData])
time.sleep(1)
print("Return to menu?")
menuReturn = input("Y or N")
if menuReturn == 'Y':
print("Press B to view outstanding fixtures.")
time.sleep(0.1)
print("Press C to display the leaderboard")
time.sleep(0.1)
print("Or press Q to exit the application.")
time.sleep(0.1)
print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
time.sleep(0.1)
menuOptions2 = input("What would you like to do? B, C, or Q?")
if menuOptions2 == 'B':
print("~~incomplete~~")
elif menuOptions2 == 'C':
print("~~incomplete~~")
elif menuOptions2 == 'Q':
print("Exiting Application...")
time.sleep(1)
exit()
elif menuReturn == 'N':
print("Exiting Application...")
time.sleep(2)
exit()
elif menuOptions == 'B':
print("Searching for fixtures...")
time.sleep(3)
data = [line.strip() for line in open(r"Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideFixtures.txt").readlines()]
for line in data:
print(line)
time.sleep(1)
print("Return to menu?")
menuReturn = input("Y or N")
if menuReturn == 'Y':
print("Press A to search for a fixture")
time.sleep(0.1)
print("Press C to display the leaderboard")
time.sleep(0.1)
print("Or press Q to exit the application.")
time.sleep(0.1)
print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
time.sleep(0.1)
menuOptions2 = input("What would you like to do? B, C, or Q?")
if menuOptions2 == 'A':
fixtureQuestion = input(int("Please enter the fixture number you are looking for... "))
fixtureQuestion = fixtureQuestion - 1
time.sleep(3)
if fixtureQuestion < 1:
print("This fixture is not available, please re-run the application...")
time.sleep(2)
exit()
elif fixtureQuestion > 190:
print("This fixture is not available, please re-run the application...")
time.sleep(2)
exit()
else:
searchData = open(r"Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideFixtures.txt").readlines()
lines = searchData.readlines()
print(lines[fixtureQuestion])
time.sleep(1)
print("Return to menu?")
menuReturn = input("Y or N")
if menuReturn == 'Y':
print("Press C to display the leaderboard")
time.sleep(0.1)
print("Or press Q to exit the application.")
time.sleep(0.1)
print("You cannot review the fixture list now you have seen it however you can scroll up to view it again.")
time.sleep(0.1)
menuOptions2 = input("What would you like to do? B, C, or Q?")
if menuOptions2 == 'C':
print("~~incomplete~~")
elif menuOptions2 == 'Q':
print("Exiting Application...")
time.sleep(1)
exit()
elif menuReturn == 'N':
print("Exiting Application...")
time.sleep(2)
exit()
elif menuOptions2 == 'Q':
print("Exiting Application...")
time.sleep(1)
exit()
elif menuOptions == 'C':
while RetryForC == "Yes":
RetryForC == "No"
fireRead = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideResults.txt")
for line in fireRead:
fireRead = open("Y:\Computing & Business\Students\Computing\Year 10\CA 2017 Edexcel\firesideResults.txt")
InfoOne = line.split(',')[0]
InfoTwo = line.split(',')[1]
InfoThree = line.split(',')[2]
InfoFour = line.split(',')[3]
PointCounter = int(line.split(',')[2])
PointCounter = PointCounter * 3
fireRead.close()
print("Player:",InfoOne,"Has played:",InfoTwo,", has won:",InfoThree,", has lost:",InfoFour,", and therefore has",PointCounter,"many points.")
print("Retry?")
RestForC = str(input("Yes/No "))
print("The program will now close...")
time.sleep(5)
exit()
elif menuOptions == 'Q':
print("Exiting Applicaion...")
time.sleep(2)
exit()
And this is my result:
Welcome to the League Fixture Manager!
What would you like to do?
Press A to search for a fixture.
Press B to view Outstanding fixtures.
Press C to display the leader board
Or press Q to quit, this will exit the application.
What would you like to do? A, B, C, or Q.A
Please enter the fixture number you are looking for...
016
Traceback (most recent call last):
File "E:\Python\Python Work\League\League3.py", line 33, in <module>
print(lines[searchData])
TypeError: list indices must be integers, not _io.TextIOWrapper
What can I do to fix this?
This line:
print(lines[searchData])
Doesn't make any sense. Indices of a list must be integers, so you can do:
>>> my_list = [1, 2, 3]
>>> my_list[0]
1
lines is a list which contains the lines of the file and search_data is a file object. It looks like you're missing some basic python concepts. Please do read the documentation I pasted in your other question you asked 10 minutes ago!

While loop stops after 1 iteration

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

Categories

Resources