When I run clear() as below it does not print the 'else' statement. It only works for the 'if' part. When I run it one indent outside, it clears without doing the print for both if and else. Please guide on where I should place it.
import random
from art import logo,vs
from game_data import data
from replit import clear
def game_question():
return random.choice(data)
def format_data(account):
account_name = account["name"]
account_description = account["description"]
account_country = account["country"]
return f"{account_name}, {account_description}, {account_country}"
def count(num_a, num_b):
if num_a > num_b:
return "a"
else:
return "b"
win = 0
play_on = False
while not play_on:
print (logo)
account_a = game_question()
account_b = game_question()
if account_a == account_b:
account_b = game_question()
num_a = account_a["follower_count"]
num_b = account_b["follower_count"]
print(f"Account A : {format_data(account_a)}")
print (vs)
print(f"Compare to Account B: {format_data(account_b)}")
ans = input("Which account has more followers? A or B: ").lower()
if ans == count(num_a,num_b):
win += 1
print ("A win")
else:
print (f"Wrong. You lose. Win = {win}")
play_on = True
clear()
The clear() function is not indented properly in else:. Try this for the if else statement
if ans == count(num_a,num_b):
win += 1
print ("A win")
else:
print (f"Wrong. You lose. Win = {win}")
play_on = True
clear()
Related
I am making a python Higher Lower game and I'm having a weird syntax error. Please help
import art
from game_data import data
from replit import clear
import random
print(art.logo)
Continue_Game = True
score = 0
while Continue_Game == True:
def er():
global A_value = data[random.randint(0,49)]
global B_value = data[random.randint(0,49)]
if A_value == B_Value:
global B_value = game_data.data[random.randint(0,49)]
if A_Value == B_Value:
er()
elif A_Value != B_Value:
return
else:
er()
er()
A_Name = A_value["name"]
A_Description = A_value["description"]
A_Country = A_value["country"]
A_Follow = A_value["follower_count"]
B_Name = B_value["name"]
B_Description = B_value["description"]
B_Country = B_value["country"]
B_Follow = B_value["follower_count"]
print(f"Compare A: {A_Name}, a {A_Description}, from {A_Country}.")
print(art.vs)
print(f"Against B: {B_Name}, a {B_Description}, from {B_Country}.")
User_follower = input("Who has more followers? Type 'A' or 'B': ")
if User_follower.lower() == "a" and int(A_Follow) > int(B_Follow):
clear()
print(art.logo)
score = score + 1
print(f"You're right! Current score: {score}.")
Continue_Game == True
elif User_follower.lower() == "a" and int(A_Follow) < int(B_Follow):
clear()
print(art.logo)
print(f"Sorry, that's wrong. Final score: {score}")
Continue_Game == False
elif User_follower.lower() == "b" and int(B_Follow) > int(A_Follow):
clear()
print(art.logo)
score = score + 1
print(f"You're right! Current score: {score}.")
Continue_Game == True
elif User_follower.lower() == "b" and int(B_Follow) < int(A_Follow):
clear()
print(art.logo)
print(f"Sorry, that's wrong. Final score: {score}")
Continue_Game == False
I'm getting a syntax error at line global A_value = data[random.randint(0,49)]
The weird thing is that I don't get this error at line global B_Value = data[random.randint(0,49)] Have any Ideas to fix this error? I found out the red line or the error or where the console says the syntax error was at the =.
The global statement does not accept an expression (e.g. a = b); it only accepts one or more identifiers (e.g. a).
The reason you're only getting one syntax error is Python stopping parsing altogether at the first syntax error, but all of those global x = y lines are erroneous.
Split them, e.g.
global A_value, B_value
A_value = data[random.randint(0,49)]
B_value = data[random.randint(0,49)]
etc.
Trying to create a fill in the blanks quiz.
If I use a for loop when the answer is incorrect will always return to FIRST element on the list, is there any way to bypass this? or use a different loop?
See my full code below.
IT IS NOT FINAL
Will only work on EASY answer selection.
The issue will appear when answering correctly FIRST blank(Imagine) and failing on the second one.
Any help will be highly apreciatted.
imag = '***1*** there is no heaven, It is ***2*** if you try, No hell below us, Above us only sky, ***1*** all the people living for today, ***1*** there is no ***3***, It is not hard to do, Nothing to kill or die for, And no religion too, ***1*** all the people living life in ***4***.'
imag_ans = ['Imagine', 'easy', 'heaven', 'peace']
blanks = ['***1***', '***2***', '***3***', '***4**']
def level():
print 'Please select Level? (Easy / Medium / Hard)'
global a
a = raw_input()
if a == 'Easy':
return attempts()
if a == 'Medium':
return 'Med'
if a == 'Hard':
return 'Hard'
else :
print 'Invalid option'
print '\n'
return level()
def attempts():
print 'How many attempts will you need?'
global numberofatt
numberofatt = raw_input()
try:
float(numberofatt)
except ValueError:
print "Please enter a number for attempts"
return attempts()
numberofatt = int(numberofatt)
if numberofatt <= 0 :
print 'Please enter a positive number'
return attempts()
else :
return quiz(a)
def quiz(level):
i = 0
global user_ans
global i
print 'Please fill in the blanks, you have ' + str(numberofatt) + ' attempts'
for blank in blanks:
print 'Fill in blank' + blank
user_ans = raw_input()
if user_ans == imag_ans[i]:
i = i + 1
global imag
imag = imag.replace(blank, user_ans)
print "Correct!"
print imag
else :
return att()
n = 1
def att():
if n == numberofatt :
return 'Game Finished'
if user_ans != imag_ans[i]:
global n
n = n + 1
#blank = 0
print 'Try Again'
return quiz(a)
print level()
You could use while loop:
def level():
global a
a = raw_input('Please select Level? (Easy / Medium / Hard): ')
pending = True
while pending:
if a == 'Easy':
pending = False
return attempts()
elif a == 'Medium':
pending = False
return 'Med'
elif a == 'Hard':
pending = False
return 'Hard'
else :
print 'Invalid option'
print '\n'
Something similar could be applied for quiz(). As commented, you should check how global works. Also, revise the indentation (e.g.: in att()).
This question already has answers here:
Defining lists as global variables in Python
(3 answers)
Slicing list inside a method (Python 3)
(1 answer)
Closed 5 years ago.
I have the following code:
import sys
import os.path
import ConfigParser
import copy
import time
import colorama
from colorama import init
from colorama import Fore, Back, Style
init()
#init variables
discoveredelements = []
discoveredgroups = []
combo = []
savefile = ConfigParser.ConfigParser()
os.chdir(os.getcwd())
#init other stuff
class style:
BOLD = '\033[1m'
END = '\033[0m'
def combos():
#all combos
combo.append(('Air', 'Air', 'Wind'))
combo.append(('Earth', 'Earth', 'Pressure'))
combo.append(('Fire', 'Fire', 'Explosion'))
combo.append(('Water', 'Water', 'Sea'))
combo.append(('Air', 'Earth', 'Dust'))
combo.append(('Air', 'Fire', 'Energy'))
combo.append(('Air', 'Water', 'Steam'))
combo.append(('Earth', 'Fire', 'Lava'))
combo.append(('Earth', 'Water', 'Swamp'))
combo.append(('Fire', 'Water', 'Alcohol'))
def mainmenu():
print(style.BOLD + "ALCHEMY" + style.END)
print(style.BOLD + "Load Game" + style.END)
print(style.BOLD + "New Game" + style.END)
print(style.BOLD + "Exit" + style.END)
print("Type \"load\" or \"new\" or \"exit\" ")
mainmenuinput = raw_input()
if mainmenuinput == "exit":
sys.exit()
elif mainmenuinput == "load":
if os.path.exists('save.ini'):
savefile.read('save.ini')
discoveredelements = savefile.get('Elements','discoveredelements')
print("Game Loaded")
rungame()
else:
print("Save file not found, check file directory or start a new game.")
mainmenu()
elif mainmenuinput == "new":
if os.path.exists("save.ini"):
print("Current save file will be overwritten. Proceed?")
print("Y or N")
overwriteinput = raw_input()
if overwriteinput == "Y":
newgame()
rungame()
elif overwriteinput == "N":
mainmenu()
else:
newgame()
rungame()
def newgame():
save = open('save.ini','w')
#reset data
savefile.add_section('Elements')
savefile.add_section('Groups')
savefile.set('Elements','discoveredelements',"")
savefile.set('Groups','discoveredgroups',"")
#adds the default elements
discoveredelements.append("Air")
discoveredelements.append("Earth")
discoveredelements.append("Fire")
discoveredelements.append("Water")
savefile.set('Elements','discoveredelements',discoveredelements)
discoveredgroups.append("Air")
discoveredgroups.append("Earth")
discoveredgroups.append("Fire")
discoveredgroups.append("Water")
savefile.set('Groups','discoveredgroups',discoveredgroups)
savefile.write(save)
save.close()
print("Game Loaded")
def gameloop():
#actual gameplay
print("Type two elements (seperately) or \"list\" or \"hint\" or \"save\" or \"exit\"")
gameinput = raw_input()
if gameinput == "list":
displayelements = copy.copy(discoveredelements)
print(','.join(map(str, displayelements)))
gameloop()
elif gameinput == "hint":
if (time.time() - timerstart) >= 10:
print('hint')
timerstart = time.time()
gameloop()
else:
print("Hint is still on cooldown")
gameloop()
elif gameinput == "save":
savefile.set('Elements','discoveredelements',discoveredelements)
savefile.set('Groups','discoveredgroups',discoveredgroups)
print("Game saved")
elif gameinput == "exit":
savefile.read('save.ini')
savelist = savefile.get('Elements','discoveredelements')
if len(savelist) < len(discoveredelements):
print("Game not saved! Do you wish to exit without saving?")
print("Y or N")
overwriteinput = raw_input()
if overwriteinput == "Y":
mainmenu()
else:
gameloop()
else:
elementA = gameinput
elementB = raw_input()
if (elementA in discoveredelements) and (elementB in discoveredelements):
i = 0
created = 0
while True:
if (combo[i][0] == elementA and combo[i][1] == elementB) or (combo[i][1] == elementA and combo[i][0] == elementB):
print("You created " + combo[i][2])
discoveredelements.append(combo[i][2])
created = 1
break
i += 1
if i == len(combo):
break
if created == 0:
print("No elements created")
gameloop()
else:
print("Error, using non-existent or not yet discovered elements")
gameloop()
def rungame():
#initializing game
timerstart = time.time()
displayelements = copy.copy(discoveredelements)
print(','.join(map(str, displayelements)))
gameloop()
#game starts here
print(Style.RESET_ALL)
combos()
mainmenu()
When I type "load" into the console, nothing is outputted for displayelements. So I tried to see if the list contained anything (and if the copy.copy() worked or not) by doing print(displayelements) and it printed []
Then I checked if discoveredelements contained anything and it did:
['Air', 'Earth', 'Fire', 'Water']
Why isn't the copy.copy() working?
EDIT:
I declared discoveredelements as global:
global discoveredelements
discoveredelements = []
The copying still doesn't work, displayelements is still an empty list.
To assign to a global var in function you must declare is as global:
discoveredelements = []
def func():
# a new var is created in the scope of this function
discoveredelements = [1,2,3,4]
func()
print (discoveredelements)
discoveredelements = []
def func():
# declare as global
global discoveredelements
# assign to the global var
discoveredelements = [1,2,3,4]
func()
print (discoveredelements)
I am trying to use a while statement like so:
o = 0
while o == 0:
try:
n = int(raw_input("Which number do you want to begin with?"))
o = 1
except:
o = 0
print "Please use a valid number."
However, when I try to use variable n later, it gives me the "local variable 'n' referenced before assignment' UnboundLocalError. That means that n cannot be recognized as a variable in the def I am using, because it only exists in the while statement? Is this possible?
The whole code:
import time
from sys import argv
import os
os.system("cls")
print "Welcome to Number counter 2.0!"
a = True
def program():
global a
if a == False:
os.system("cls")
o = 0
while o == 0:
try:
n = int(raw_input("Which number do you want to begin with?"))
o = 1
except:
o = 0
print "Please use a valid number."
if n == "/historyKeep false":
if a == False:
print "Command historyKeep is already set to false."
else:
a = False
print "Command set successfully."
elif n == "/historyKeep true":
if a == True:
print "Command historyKeep is already set to true."
else:
a = True
print "Command set successfully."
if n == "/historyKeep false":
n = raw_input("Which number do you want to begin with?")
elif n == "/historyKeep true":
n = raw_input("Which number do you want to begin with?")
d = raw_input("How many seconds between each number?")
d = int(d)
total_s = n * d
while n > 0:
print n
time.sleep(d)
n = n - 1
print "Done in", total_s, "seconds in total!"
end_q = raw_input("Exit or retry? (e/r)")
if end_q == "e":
os.system("cls")
print "Exiting."
time.sleep(0.5)
os.system("cls")
print "Exiting.."
time.sleep(0.5)
os.system("cls")
print "Exiting..."
time.sleep(0.5)
os.system("cls")
exit(0)
elif end_q == "r":
program()
program()
You set a = True at the beginning. You then test if a == False and only set n if it is. But then you test n == "/history.... n has not been set at this point.
You need to make sure n is assigned before you use it. It is not enough to just mention it in a branch that is not taken.
n is not defined in the scope that you are trying to use it to fix this define it outside of the while loop and the if statement the while loop is in:
global a
n = 0
Then when you ask the user for what number to start with, that value will replace 0, and you should be good to go. Also instead of declaring global a, why not just make a an input argument for the program() function?
Just to make sure, declare n outside of the loop first:
n = None
while True:
try:
n = int(raw_input("Text..."))
break
except:
print("Please enter a valid number!")
Note: Usually, you would use break to exit a loop. This is because your method requires an extra variable, which uses more memory (not much, but if you keep doing it, it will stack up).
I'm not sure what seems to be the problem with my code, I need some help. When I try running my program, it says invalid syntax next to my first if, I thought I may be an indentation error but nothing is working.
Here is my code:
import random
def montyHall():
car = random.randint(1,3)
guess1 = random.randint(1,3)
for i in range(1,3):
if ((not(i == car) and not(i == guess1)):
return i
newGuess = not(i) and not(guess1)
if (newGuess == car):
stay = True
elif (guess1 == car):
switch = False
return strategyOne
NUM_OF_TRIALS = 1000
stay = 0
switch = 0
for i in range(NUM_OF_TRIALS):
if(montyHall()):
stay += 1
else:
switch += 1
print("Staying wins", stay/NUM_OF_TRIALS, "% of the time")
print("Switching wins", switch/NUM_OF_TRIALS, "% of the time")
To many brackets and you do not need brackets in python.
Try changing:
if ((not(i == car) and not(i == guess1)):
to
if i != car and i != guess1: