Python program error - python

I'm new to programming, and I tried to make a python program. Here it is:
import time
gravity = 0
space = 0
print "Welcome to the 'Find out who is in space' program"
person_messy = raw_input("Enter a name:")
person = person_messy.lower()
if len(person) < 5:
print "Make sure you put the first AND last name"
else:
space = 1
print "Searching database....."
if person == "oleg kotov" or "mike hopkins" or "sergey ryazanskiy" or "fyodor yurchikhin" or "karen nyberg" or "luca permitano":
gravity = 1
else:
gravity = 0
time.sleep(1)
if space == 1:
print "loading..."
time.sleep(1)
if space == 1:
print "loading..."
time.sleep(1)
if space == 1:
print "loading..."
if gravity == 1:
print person + "is in space!"
else:
print "You and " + person + "are on the same planet."
this is the error I got:
Internal error: ReferenceError: _select is not defined

I had the same problem on similar code... You can't use time.sleep or it gives this. I don't know why, but that fixed my code(not using time.sleep)

Related

cant seem to get this procedure to print outut in bash

So when I run this on sublime ctrl-b I get the following output:
2
this is a example string with a _x_
ok so you have 3 left
What is your guess?
However when I run this in git-bash it simply runs, no errors, no output, no request for user input. I am new at this, and this is just a small part of a school quiz I am doing. Any suggestions?
string1 = "this is a example string with a _x_"
sample_list = [1, 2, 3]
def main():
print (sample_list[1])
print (string1)
chances = 3
while chances > 0:
print ("ok so you have " + str(chances) + " left")
answer = input("What is your guess?")
if answer == sample_list[0]:
print ("Great, here is your new string!")
print (string1.replace('_x_', str(sample_list[1])))
elif answer != sample_list[1]:
print ("Aw Schucks")
chances -= 1
print ("Out of chances")
main()

Python program does not behave as intended

I'm writing my first short programs with Python. This program should stop after the third wrong guess. The program works as expected with the first question, and stops itself after three wrong guesses.
However, I cannot understand why, with the second question, after the third wrong guess, the first question is repeated.
easy_text = '''Hello __1__!' In __2__ this is particularly easy; all you
have to do is type in: __3__ "Hello __1__!" Of course, that isn't a very
useful thing to do. However, it is an example of how to output to the user
using the __3__ command, and produces a program which does something, so it
is useful in that capacity..'''
def split_string():
global easy_text_splitted
easy_text_splitted = easy_text.split(" ")
return None
def level1():
print """You will get 3 guesses per problem
The current paragraph reads as such:"""
print easy_text
return first_question(3)
def first_question(guesses):
while guesses > 0:
split_string()
first_answer = raw_input("What should be substituted in for __1__?")
if first_answer.lower() == "world":
easy_text_splitted[1] = first_answer
easy_text_splitted[19] = first_answer
new_easy_text = " ".join(easy_text_splitted)
print new_easy_text
second_question(3)
else:
guesses -= 1
print "That's not the answer I expected. You have " +
str(guesses) + " guess(es) left"
return first_question(guesses)
def second_question(guesses):
while guesses > 0:
split_string()
second_answer = raw_input("What should be substituted in for 2?")
if second_answer.lower() == "python":
easy_text_splitted[4] = second_answer
new_easy_text = " ".join(easy_text_splitted)
print new_easy_text
else:
guesses -= 1
print "That's not the answer I expected. You have \n " +
str(guesses) + " guess(es) left"
return second_question(guesses)
def level_selection(index):
level = raw_input("Choose the desired level of difficulty: easy, \n
medium, or hard ")
if level.lower() == "easy":
return level1()
if level.lower() == "medium":
return level2
if level.lower() == "hard":
return level3
else:
print "Error"
index -= 1
if index > 0:
return level_selection(index)
return "Bye!"
print level_selection(3)
level2 = "You selected medium"
level3 = "You selected hard"
Whatever the value of guesses was in first_question when second_question was called, it is the same when it returns, so the loop continues, and repeats the first question.
Using a debugger will help you follow how this works.

Variable is not defined: but I think it is

I'm new to coding, especially in python. I started learning python using codeacademy about 1 day ago and I have progressed quickly. After reaching the end of the battleship unit, it challenged me to challenge myself by seeing what I can do. So, I set out to make the game two-player. However, after finishing the program, it tells me that the column variable on the second player's ship is not defined. Why?
Here is the code:
board1 = []
board2 = []
for i in range(5):
board1.append(["O"] * 5)
board2.append(["O"] * 5)
# Creates 2 boards, one for each player to view
def printboard(board):
for row in board:
print " ".join(row)
# Prints one of the boards, depending on which player is meant to see it
def boardset1():
print "Player 1, set your coordinates!"
ship_col1 = int(raw_input("X:"))
ship_row1 = int(raw_input("Y:"))
if ship_col1 not in range(1,6) or ship_row1 not in range(1,6):
print "Invalid coordinates!"
boardset1()
else:
ship_col1 = abs(ship_col1 - 5)
ship_row1 = abs(ship_row1 - 5)
for i in range(10):
print ""
print "Coordinates set!"
def boardset2():
print "Player 2, set your coordinates!"
ship_col2 = int(raw_input("X:"))
ship_row2 = int(raw_input("Y:"))
if ship_col2 not in range(1,6) or ship_row2 not in range(1,6): #< Issue is here, I think
print "Invalid coordinates!"
boardset2()
else:
ship_col2 = abs(ship_col2 - 5) #< Might be here
ship_row2 = abs(ship_row2 - 5)
for i in range(10):
print ""
print "Coordinates set!"
# 2 above functions set coordinates based on player input
def play1():
printboard(board1)
print "Player 1: Where is the opponent's ship?"
guess_col1 = int(raw_input("X:"))
guess_row1 = int(raw_input("X:"))
if guess_col1 not in range(1,6) or guess_row1 not in range(1,6):
print "Invalid coordinates!"
play1()
else:
guess_col1 = abs(guess_col1 - 5)
guess_row1 = abs(guess_row1 - 5)
if board1[guess_col1][guess_row1] == "X":
print "You already guessed here!"
play1()
elif guess_col1 == ship_col2 and guess_row1 == ship_row2:
win = True
print "You have won!"
else:
board1[guess_col1][guess_row1] = "X"
print "You have missed!"
def play2():
if win == False:
printboard(board2)
print "Player 2: Where is the opponent's ship?"
guess_col2 = int(raw_input("X:"))
guess_row2 = int(raw_input("X:"))
if guess_col2 not in range(1,6) or guess_row2 not in range(1,6):
print "Invalid coordinates!"
play2()
else:
guess_col2 = abs(guess_col2 - 5)
guess_row2 = abs(guess_row2 - 5)
if board2[guess_col2][guess_row2] == "X":
print "You already guessed here!"
play2()
elif guess_col2 == ship_col1 and guess_row2 == ship_row1:
win = True
print "You have won!"
else:
board2[guess_col2][guess_row2] = "X"
print "You have missed!"
# Play functions are for gameplay
win = False
boardset1()
boardset2()
for i in range(25):
if win == False:
play1()
play2()
else:
break
Immediately after player 1 makes a guess, this error occurs:
Traceback (most recent call last):
File "python", line 97, in <module>
File "python", line 59, in play1
NameError: global name 'ship_col2' is not defined
Any advice or solution is welcome. The more detailed, the better, as I am still learning.
Thanks!
Your problem is that the variable ship_col2 is defined within a function. That means that it only exists until that function is done running, and then it is deleted. In order to make it available outside that function and in other functions, you must declare it as a global variable, which you can do by defining it with a default value under board1 and board2 at the top of the file. You must define all variables that you want to use in multiple functions like that.
Here is some further reading that might help you understand better: http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html

second game starts itself with wrong conditions in a python simle gui program

I am new to python and trying to make a simple game using simplegui in python. In this game, a number is guessed between either 0-100 or 0-1000 (depending upon user's choice) and then the user guess that number. The user gets maximum 7 attempts. The new game starts after the user lose or guess the correct number. The game should run continously.
Problem: When the first game finishes...second game normally and then third game starts which prints the message You lose!.
My code is following:
import simplegui
import random
import math
# initialize global variables used in your code
numOfTurns = 0
numberThought = 2000
maxAllowedTurns = 0
flag = 0 # 1: range is (0, 100] and 2: range is (0,1000]
# define event handlers for control panel
def range100():
# button that changes range to range [0,100) and restarts
global flag
flag = 1
new_game()
def range1000():
# button that changes range to range [0,1000) and restarts
global flag
flag = 2
new_game()
def input_guess(string_guess):
guess = int(string_guess)
global numberThought , numOfTurns, maxAllowedTurns, flag
numOfTurns = numOfTurns + 1
if ( numberThought > 1000 ):
print "Please Select the Range First"
print
return
# main game logic goes here
guessLeft = maxAllowedTurns - numOfTurns
if(numberThought < guess):
print "Your guess was = ", guess
print "Number of Guesses remaining = ", (maxAllowedTurns - numOfTurns)
print "Lower !"
print
if (guessLeft == 0):
print "You Lose!!"
print "The Number was = ", numberThought
print "<<<<<<<<<<<<<<<<<<<<<<<<",">>>>>>>>>>>>>>>>>>>>"
print
print
new_game()
elif (guess < numberThought):
print "Your guess was = ", guess
print "Number of Guesses remaining = ", (maxAllowedTurns - numOfTurns)
print "Higher !"
print
if (guessLeft == 0):
print "You Lose!!"
print "The Number was = ", numberThought
print "<<<<<<<<<<<<<<<<<<<<<<<<",">>>>>>>>>>>>>>>>>>>>"
print
print
new_game()
elif (guess == numberThought):
print "Your guess was = ", guess
print "Correct !"
print
new_game()
if (guessLeft == 0):
print "You Lose!!"
print "The Number was = ", numberThought
print "<<<<<<<<<<<<<<<<<<<<<<<<",">>>>>>>>>>>>>>>>>>>>"
print
print
new_game()
# create frame
frame = simplegui.create_frame("Guess The Number", 300, 300)
# register event handlers for control elements
frame.add_button("range (0,100]", range100)
frame.add_button("range (0,1000]", range1000)
frame.add_input("Enter",input_guess, 100)
# call new_game and start frame
# helper function to start and restart the game
def new_game():
global numberThought , numOfTurns , flag, maxAllowedTurns
numOfTurns = 0
print "<<<<<<<<<<<<<<<<<<<<<<<<",">>>>>>>>>>>>>>>>>>>>"
print "NEW GAME !!!!"
# Defining the number of turns allowed based upon the range type
if(flag == 1):
maxAllowedTurns = 7
numberThought = random.randrange(0,100)
print "Range is from 0 - 100"
print "Max allowed turns = " , maxAllowedTurns
print "Number of Guesses remaining = " , maxAllowedTurns-numOfTurns
print
elif(flag == 2):
maxAllowedTurns = 10
numberThought = random.randrange(0,1000)
print "Range is from 0 - 1000"
print "Max allowed turns = " , maxAllowedTurns
print
frame.start()
(Copy-pasted comment)
I only looked at the code, I didn't test it (didn't want to install simplegui), but I think it prints you lose when you guess the correct number using exactly the allowed turns. Try removing the if block "if (guessLeft == 0): ... " in the last elif block in input_guess.

Python Not Running Code [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I wrote a python script which just stopped working suddenly. I'm not sure why so any help would be appreciated. The console just doesn't display anything. I called the function start on the bottom but no luck.
import random
year = 1
our_score = 0
their_score = 0
games_played = 0
#opponent's strategy:
def op_strategy():
for i in range (0,1):
rand = random.randint(0,1)
if rand == 0:
return "war"
if rand == 1:
return "peace"
def start():
global our_score, their_score, year
print "====="
print "Year " + str(year)
print "Our Score: " + str(our_score)
print "Their Score: " + str(their_score)
print ""
strategy = raw_input("What is your strategy this year? ")
inputs(strategy)
def inputs(strategy):
our_score = 0
global our_score, their_score, year
if str(strategy) == "peace" or str(strategy) == "war":
print "You chose: " + str(strategy)
op_strat = str(op_strategy())
print "They chose: " + op_strat
if str(strategy) == "war" and str(op_strat) == "war":
print ">>> Everyoner to arms!"
our_score = our_score + 1
their_score = their_score + 1
year = year + 1
elif str(strategy) == "peace" and str(op_strat) == "peace":
print ">>> Peace for everyone!"
our_score = our_score + 3
their_score = their_score + 3
year = year + 1
elif str(strategy) == "peace" and str(op_strat) == "war":
print ">>> They crushed us!"
our_score = our_score
their_score = their_score + 5
year = year + 1
elif str(strategy) == "war" and str(op_strat) == "peace":
print ">>> We crushed them!"
our_score = our_score + 5
their_score = their_score
year = year + 1
if str(year) == "11":
print "====="
print "Final"
print str(our_score)
print str(their_score)
if our_score > their_score:
print ">>>>> We win! <<<<<"
if their_score > our_score:
print ">>>>> They win! <<<<<"
if their_score == our_score:
print ">>>>> It's a tie! <<<<<"
play = raw_input("Play again?")
if play == "y":
start()
if play == "n":
pass
else:
play = raw_input('Invalid response. Please enter "y" or "n".')
if str(strategy) != "peace" and str(strategy) != "war":
strategy = raw_input('Invalid strategy. Enter "peace" or "war": ')
inputs(strategy)
start()
start()
The code is executing, but it is stuck at the raw_input call, and not printing until it completes, which of course the user does not know to do because nothing has printed.
The buffer is not automatically flushed. If you start python with the -u option, the buffer will be flushed with the raw_input call, and the prompt will be apparent.
Load this up in Idle and you'll see the following error:
SyntaxError: name 'our_score' is assigned to before global declaration (, line 1)
One these lines:
def inputs(strategy):
our_score = 0
global our_score, their_score, year
As detailed here:
If the global statement occurs within a block, all uses of the name
specified in the statement refer to the binding of that name in the top-level
namespace... i.e. the namespace of the module containing the code block
You've assigned to a local variable our_name and then you're telling the function to use a global variable of the same name. There should be no problems after fixing this.

Categories