Python Not Running Code [closed] - python

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.

Related

Variable in function python [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 12 months ago.
Improve this question
i have a little problem with my code.
How can i make global variable in my code and functions?
Example in my project ( it's simple game ) i want have a wallet - so its must be a global to earn and lose gold. In this code player is in minigame and can lose or earn more money but I would like this wallet to be variable throughout the file and react along with the minigame and other things in the code.
How to do it correctly?
leave_action = 'n'
print("Welcome in dice poker.")
while leave_action.lower() != 'y':
wallet = 5
bounty_from_dice = 0
if wallet == 0:
leave_action = input("Do you want leave from table? \nY. \nN. \n")
bet = int(input("Ile chcesz postawic? "))
wallet = wallet - bet
dice = sorted([ri(1, 6) for _ in range(5)])
print(dice)
for i in range(5):
print(f'{i + 1} throw a dice, the drawn value is {dice[i]} ')
result = pair(dice)
result2 = triple(dice)
resultf = full(dice)
resultp = poker(dice)
resultk = kareta(dice)
resultss = smallstreet(dice)
if result:
print('PAIR!')
bounty_from_dice = bounty_from_dice + 1
else:
print('No pair here')
if result2:
print('FAIR!')
bounty_from_dice = bounty_from_dice + 2
else:
print('No fair here')
if resultf:
print("FULL!")
bounty_from_dice = bounty_from_dice + 5
else:
print("No FULL here")
if resultk:
print("KARETA!")
bounty_from_dice = bounty_from_dice + 5
else:
print("No kareta here")
if resultp:
print("POKER!")
bounty_from_dice = bounty_from_dice + 10
else:
print("No poker here")
if resultss:
print("Smallstreet!")
bounty_from_dice = bounty_from_dice + 15
else:
print("No smallstreet here")
hazard_award = bounty_from_dice * int(bet)
wallet = wallet + hazard_award
print("Your win ratio is : " + str(bounty_from_dice))
print("You won from dice poker : " + str(hazard_award))
leave_action = input("Do you want leave from table? \nY. \nN. \n")
print("Your current gold: " + str(wallet))
if leave_action == 'y':
print("You left from dice poker.")
```
Assuming the code you shared is within a function, you can do multiple things to have a global wallet.
Pass as an argument
wallet = 5
def playDicePoker(wallet):
# [your code here but without the wallet=5 line in the while loop]
return wallet # to recover the new wallet value
# Usage:
wallet = playDicePoker(wallet)
Make it a global variable
This will need more work if you split the code over multiple file.
global wallet
wallet = 5
def playDicePoker():
global wallet
# [your code here but without the wallet=5 line in the while loop]
# Usage:
playDicePoker()
# now wallet is updated
Have a Player class
This will allow you to easily store other informations about your player as well, like the number of wins, the number of game played for each game, and so on
class Player:
def __init__(self, initialWallet):
self.wallet = initialWallet
def playDicePoker(player):
# [your code here but replacing wallet by player.wallet]
# (also no player.wallet = 5 since it's already initialized)
# Usage:
player = Player(5)
playDicePoker(player)

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.

Function is not getting called

I have below code where I have two functions print_menu() and pStockName()
def print_menu():
print ("\t\t\t\t 1. Get Stock Series ")
print ("\t\t\t\t 2. Invoke Stocks.")
print ("\t\t\t\t 3. Generate DC Stock List . ")
print ("\t\t\t\t 4. QUIT")
def pStockName():
global StockList, fStockList
pStockList = []
fStockList = []
StockList = str(raw_input('Enter pipe separated list of StockS : ')).upper().strip()
items = StockList.split("|")
count = len(items)
print 'Total Distint Stock Count : ', count
items = list(set(StockList.split("|")))
# pipelst = StockList.split('|')
# pipelst = [i.split('-mc')[0] for i in StockList.split('|')]
# pipelst = [i.replace('-mc','').replace('-MC','').replace('$','').replace('^','') for i in StockList.split('|')]
pipelst = [i.replace('-mc', '').replace('-MC', '').replace('$', '').replace('^', '') for i in items]
# pipelst = [Stock.rsplit('-mc',1)[0] for Stock in pipelst]
filepath = '/location/Stock_data.txt'
f = open(filepath, 'r')
for lns in f:
split_pipe = lns.split(':', 1)
if split_pipe[0] in pipelst:
index = pipelst.index(split_pipe[0])
pStockList = split_pipe[0] + "|"
fStockList.append(pStockList)
del pipelst[index]
# f.close()
for lns in pipelst:
print bcolors.red + lns, ' is wrong Stock Name' + bcolors.ENDC
if lns:
uResp = str(raw_input('Do You Want To Continue with option 0 [YES|Y|NO|N] : ')).upper().strip()
if uResp == "NO" or uResp == "N":
os.system("tput clear")
print bcolors.FAIL + "\n PLEASE USE OPTION 0 TO ENTER THE Stock NAMES BEFORE PROCEEDING." + bcolors.ENDC
# StockList = None
print_menu()
else:
pStockName()
f.close()
In above code you must be seeing in 4th last line I am calling print_menu() function. But it is just printing the content of print_menu() function not doing any operation and going to pStockName() function. Follow operation I want to execute from print_menu() function when I am calling it:
while choice >= 1 and choice < 4:
if choice == 4:
os.system("tput clear")
if StockList:
uResp = str(raw_input(
bcolors.FAIL + 'Do you need to move : ' + StockList + ' ? Press Y To Go Back to Main Menu and N to Quit [YES|Y|NO|N] : ')).upper()
if uResp == "NO" or uResp == "N":
print bcolors.HEADER + "GoodBye." + bcolors.ENDC
break
I mean to say when I am calling print_menu() function in pStockName() function in 4th last line from pStockName() function it should print the content of print_menu() function and when I press 4 it should perform the operation quit. But when I pressing any of the option from 1 to 4 it going to pStockName() function only.
Please help me what I am doing wrong here.
I'm a bit new here, but I do not see where you assign the keyboard input into variable "choice". Therefore, the program will not recognize what the end user input is. My suggestion is to assign "choice" into raw_input Like so:
choice = raw_input()
if choice == "4": # alternatively, perform int(choice) == 4
print ("yes")
I hope this helps!

Python program error

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)

Categories