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.
Related
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()
I am creating an Among Us ripoff (for fun!) and the while True & if/elif/else statements will only return false (not An Impostor) with the inputs. I had created a list for the names and 2 random elements from the list will be chosen as An Impostor. However, whenever I input a name that is The Impostor, it will only return
(player) was not An Impostor.
Here is my code;
import sys, time, random
names = ["player1", "player2", "player3", "player4", "player5", "player6", "player7", "player8", "player9", "player10"]
print("Players: ")
for x in names:
print(x)
print('—————————————————————————')
impostor1 = random.choice(names)
impostor2 = random.choice(names)
crewmates = 8
impostors = 2
tries = 6
while True:
talk = input("Guess who The Impostor(s) are. " + str(crewmates) + " Crewmates are left. " + str(impostors) + " Impostors are left. You have " + str(tries) + " tries left.")
if talk in names:
print(talk + " was voted for.")
time.sleep(0.1)
if talk != impostor1 or talk != impostor2:
notimp = talk + " was not An Impostor. "
names.remove(talk)
for y in notimp:
sys.stdout.write(y)
sys.stdout.flush()
time.sleep(0.05)
crewmates -= 1
tries -= 1
elif talk == impostor1 or talk == impostor2:
wasimp = talk + " was An Impostor. "
names.remove(talk)
for v in wasimp:
sys.stdout.write(v)
sys.stdout.flush()
time.sleep(0.1)
impostors -= 1
else:
print("That player was either ejected or is not a valid player.")
However, whenever I put the Impostor in the input, it says it isn't An Impostor?
I think this line is the source of the problem:
if talk != impostor1 or talk != impostor2:
Let's say impostor1 is player1 and impostor2 is player2 and someone input in player1, according to Python Boolean expression operator or that if statement will evaluate like this:
if player1 != impostor1 evaluated to False because player1 is indeed equals to impostor1.
So far so good, but because the first test is a False, Python simply evaluates and returns the right side operand which may be either True or False. In your case Python will evaluate if talk != impostor2 and return True, thereafter executes the nested block.
Ok I have a feeling that this is a simple simple issue but I have been staring at this code for about 10 hours now.
The issue I am having is in mastermind is that once I get it to recognize that I have the correct colors in the right spot I can get it to display the right spots with X and the wrong spots with O. I need to be able to convert that so instead of X and O I need it to tell the user that he/she has 2 blacks and one white
For example: The secret code is RGYB The user enters RGOY so then Python relays "You have 2 blacks(The R and G spots) and one 1 White (The Y because it's the right color just in the wrong index) As of right now I got it to display X for the right color in the right spot and anything else it is an O
I will post what I have been working with now but today I am at my wit's end
https://pastebin.com/HKK0T7bQ
if correctColor != "XXXX":
for i in range(4):
if guess[i] == tempCode[i]:
correctColor += "X"
if guess[i] != tempCode[i] in tempCode:
correctColor += "O"
print (correctColor + "\n")
if correctColor == "XXXX":
if attempts == 1:
print ("You think you are sweet because you got it right on the first try? Play me again!")
else:
print ("Well done... You needed " + str(attempts) + " attempts to guess.")
game = False
A few comments
X and O
you use X and 0 to denote the success, it will be easier and faster to use a list or tuple or booleans for this, that way you can use sum() to count how many colors and locations were correct. Then whether you represent that with X and O or red and white pins is a matter for later
compartmentalization
Your game logic (guess input, input validation, do you want to continue, etc) is mixed with the comparison logic, so it would be best to separate the different functions of your program into different methods.
This is an fineexample to introduce object oriented programming, but is so simple it doesn't need OO, but it can help. What you need is a method which takes a series of colours and compares it to another series of colours
Standard library
Python has a very extended standard library, so a lot of stuff you want to do probably already exists
Correct colours
to count the number of letters which occur in 2 strings, you can use collections.Counter
guess = "RGOY "
solution = "RGYB"
a = collections.Counter(guess)
b = collections.Counter(solution)
a & b
Counter({'G': 1, 'R': 1, 'Y': 1})
correct_colours = sum((a & b).values())
3
So the user guessed 3 colours correctly
Correct locations
can be solved with an easy list comprehension
[g == s for g, s in zip(guess, solution)]
[True, True, False, False]
sum(g == s for g, s in zip(guess, solution))
2
so the used put 2 colours on the correct location
This is a MasterMind I made in Python. Hope you like it and it helped you! :)
import random
import time
from tkinter import *
def select_level():
global level
level = level_selector.get()
root.destroy()
root = Tk()
level_selector = Scale(root, from_=1, to=3, tickinterval=1)
level_selector.set(0)
level_selector.pack()
Button(root, text="Select a difficulty level", command=select_level).pack()
mainloop()
cpc_1_digit = 0
cpc_2_digit = 0
cpc_3_digit = 0
cpc_4_digit = 0
p_1_digit = 0
p_2_digit = 0
p_3_digit = 0
p_4_digit = 0
correct_correct = 0
correct_wrong = 0
chances = 0
if level == 1:
chances = 15
elif level == 2:
chances = 10
else:
chances = 7
cpc_1_digit = random.randint(0, 9)
while cpc_2_digit == cpc_1_digit or cpc_2_digit == cpc_3_digit or cpc_2_digit ==
cpc_4_digit:
cpc_2_digit = random.randint(0, 9)
while cpc_3_digit == cpc_1_digit or cpc_3_digit == cpc_2_digit or cpc_3_digit ==
cpc_4_digit:
cpc_3_digit = random.randint(0, 9)
while cpc_4_digit == cpc_1_digit or cpc_4_digit == cpc_2_digit or cpc_4_digit ==
cpc_3_digit:
cpc_4_digit = random.randint(0, 9)
while chances > 0:
correct_correct = 0
correct_wrong = 0
answer = input("Enter a four-digit number with different digits (e.g 1476): ")
p_1_digit = int(answer[0])
p_2_digit = int(answer[1])
p_3_digit = int(answer[2])
p_4_digit = int(answer[3])
if p_1_digit == cpc_1_digit:
correct_correct = int(correct_correct) + 1
elif p_1_digit == cpc_2_digit or p_1_digit == cpc_3_digit or p_1_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_2_digit == cpc_2_digit:
correct_correct = correct_correct + 1
elif p_2_digit == cpc_1_digit or p_2_digit == cpc_3_digit or p_2_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_3_digit == cpc_3_digit:
correct_correct = int(correct_correct) + 1
elif p_3_digit == cpc_1_digit or p_3_digit == cpc_2_digit or p_3_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_4_digit == cpc_4_digit:
correct_correct = int(correct_correct) + 1
elif p_4_digit == cpc_1_digit or p_4_digit == cpc_3_digit or p_4_digit ==
cpc_2_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
print("")
if int(correct_correct) == 4:
print("Congratsulations! You found the computer's number!")
break
elif int(correct_wrong) > 0 or int(correct_correct) >= 1 and int(correct_correct)
< 4:
print("You got " + str(correct_correct) + " correct digit(s) in the correct
place, and " + str(correct_wrong) + " correct digit(s) but in wrong place.")
elif int(correct_correct) == 0 and int(correct_wrong) == 0:
print("You didn't guess any number, try again!")
else:
raise Exception("CheckError: line 69, something went wrong with the
comparings.")
exit()
print("")
chances = chances - 1
if chances == 0:
print("You lost... The secret number was " + str(cpc_1_digit) + str(cpc_2_digit)
+ str(cpc_3_digit) + str(cpc_4_digit) + ". Try again by rerunning the program.")
time.sleep(4)
I am trying to create a battleships game to practice my coding, however I am having trouble changing the value of a global variable.
turnsover = 0
diff = 0
ship_row = 0
ship_col = 0
def difficulty():
global diff
global turnsover
diff = input("Please select a difficulty\n 1=Easy \n 2=Meduim \n 3=Hard \n 4=VS Machine\n")
if diff.isdigit():
diff = int(diff)
if int(diff) not in range(1,5):
print("Please select a correct difficulty level")
difficulty()
if diff == 1:
turnsover == 20
print("Difficulty level: Easy")
if diff == 2:
turnsover == 15
print("Difficulty level: Meduim")
if diff == 3:
turnsover == 10
print("Difficulty level: Hard")
if diff == 4:
turnsover == randint(1, 26)
print("Difficulty level: Vs Machine")
####REMOVE AFTER PROD####
print(turnsover)
else:
print("Please select a correct difficulty level")
difficulty()
The prod test print of turnsover returns 0 instead of returning the new amount of turnsover (aka lifes remaining)
As #MorganThrapp says, you are checking turnsover equality with code such as turnsover == 10 and not assigning a value to it like so: turnsover = 0. = means assignment and == means equality. This should be obvious as you're assigning values to the global variables at the beginning of your code.
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: