why label is not being configured in function? - python

my score label or chances count is not configured when i run the function. can anyone help on this? the question label changes perfectly but the score label does not change and i am unable to understand why is that so.
def checkans(self):
chances = 0
score = 0
count = 0
while chances == 3:
break
else:
operations=['+', '-', '*']
a = random.randint(1,15)
b = random.randint(1,15)
random.shuffle(operations)
op = operations[0]
self.label.configure(text=(a,op,b))
if op == '+':
ans = a + b
if op == '-':
ans = a - b
if op == '*':
ans = a * b
self.e.focus_set()
if self.e.get() == ans:
score += 1
self.scorelabel.configure(text=('score', score))
else:
chances += 1

Try this:
def checkans(self):
chances = 0
score = 0
count = 0
while chances < 3:
operations=['+', '-', '*']
a = random.randint(1,15)
b = random.randint(1,15)
random.shuffle(operations)
op = operations[0]
self.label.configure(text=(a,op,b))
if op == '+':
ans = a + b
if op == '-':
ans = a - b
if op == '*':
ans = a * b
self.e.focus_set()
if self.e.get() == ans:
score += 1
self.scorelabel.configure(text=('score', score))
else:
chances += 1
When you use while with else the else only executes once.

Related

Break function does not work when the elif line is true

start = input('Enter quadratic equation: ')
w = start.split()
while len(w) != 7:
start = input('Enter quadratic equation correctly: ')
w = start.split()
while x < len(w):
if "x" in w[x] and '^2' in w[x]:
a = w[x]
if a == "x^2":
a = 1
else:
a = a.replace('x^2', '')
a = int(a)
if w[x-1] == '-':
a = a * (-1)
else:
a = a
elif 'x' in w[x] and '^' not in w[x]:
b = w[x]
if b == 'x':
b = 1
else:
b = b.replace('x', '')
b = int(b)
if w[x-1] == '-':
b = b * (-1)
else:
b = b
elif w[x].isdigit() and 'x' not in w[x] and w[x] != '0':
c = w[x]
elif w[x] == '-' or '+' or '=':
s = 0
elif not w[x].isdigit() and 'x' not in w[x] and w[x] != '-' or '+' or '=':
print('Mistake')
break #Would not this code here work?
x += 1
I have tried just doing 'else' block, but still it wouldn't work. What I am trying to do is to check whether the input is actually a quadratic equation.
The wrong condition is elif not w[x].isdigit() and 'x' not in w[x] and w[x] != '-' or '+' or '=':, it doesn't do what you want/need
The w[x] != '-' or '+' or '=': part :
is like (w[x]!='-') or ('+') or ('='):
not like w[x] != ('-' or '+' or '='):
What you want is w[x] not in '-+=': and same for the previous one
elif w[x] in '-+=':
s = 0
elif not w[x].isdigit() and 'x' not in w[x] and w[x] not in '-+=':
print('Mistake')
break

Why random is giving wrong output

I wrote a program for math game which calculates score based on right answers. It will ask the user twice for the answer of a given question, if its correct it will add 10. However the score is not adding properly and I can't figure out why.
import random
def game():
l = ['*','+']
score = 0
for _ in range(2):
x = random.randint(1,5)
y = random.randint(1,5)
z = int(input("Enter the val of {} {} {} \n".format(x, random.choice(l), y)))
if random.choice(l) == '*':
o = x * y
elif random.choice(l) == '+':
o = x + y
if z == o:
score = score + 10
print(score)
return("Your score is {}".format(score))
game()
You need to remember your choice. Every time you call random.choice(l) it picks a new one:
import random
def game():
l = ['*','+']
score = 0
for _ in range(2):
choice = random.choice(l)
x = random.randint(1, 5)
y = random.randint(1, 5)
z = int(input("Enter the val of {} {} {} \n".format(x, choice, y)))
if choice == '*': # Here you chose something random
o = x * y
elif choice == '+': # and here you chose something random
o = x + y
if z == o:
score = score + 10
print(score)
return("Your score is {}".format(score))
print(game())
Also, a couple recommendations:
1) I would recommend using f-strings, it reads nicer:
z = int(input(f"Enter the val of {x} {choice} {y} \n".))
2) Use more meaningful variable names instead of x, y, z, and o.
Lastly an advanced tip. If you want to make this game more generic you can use the operator module. Then you can easily add more operations.
import random
import operator
def game():
operators = {
'*': operator.mul,
'+': operator.add,
'-': operator.sub,
}
score = 0
for _ in range(2):
choice = random.choice(list(operators.keys()))
x = random.randint(1, 5)
y = random.randint(1, 5)
user_answer = int(input(f"Enter the val of {x} {choice} {y} \n"))
actual_answer = operators[choice](x, y)
if user_answer == actual_answer:
score = score + 10
return("Your score is {}".format(score))
print(game())

How to add the value in string and go to next letter?

Two people participate in competition . There will be one easy, difficult and medium question
Difficulty Score
E 1
M 3
H 5
User will enter two strings e and b , and function should find out greater scores or tie.
My code is:
def winner(e, b):
sume = 0
sumb =0
highest = 0
x = False
for i in (range(len(erica))):
if (erica[i] =='E'):
sume +=1
x = True
elif (erica[i] =='M'):
sume = sume+3
x = True
elif (erica[i] =='H'):
sume +=5
x = True
return sume
if __name__ == '__main__':
erica = input()
bob = str(input())
print(winner(e,b))
When I enter HEM for e, it should give 9 but it only gives 5.
There is a problem with the return statement indentation. Try Below.
Also, you are not passing the correct variables.
def winner(e, b):
sume = 0
sumb =0
highest = 0
x = False
for i in (range(len(e))):
if (e[i] =='E'):
sume +=1
x = True
elif (e[i] =='M'):
sume = sume+3
x = True
elif (e[i] =='H'):
sume +=5
x = True
return sume
if __name__ == '__main__':
e = input()
b = str(input())
print(winner(e,b))
def winner(e, b):
sume = 0
sumb =0
highest = 0
for i in (range(len(e))):
if (e[i] =='E'):
sume +=1
elif (e[i] =='M'):
sume = sume+3
elif (e[i] =='H'):
sume +=5
for i in (range(len(b))):
if (b[i] =='E'):
sumb +=1
elif (b[i] =='M'):
sumb = sumb+3
elif (b[i] =='H'):
sumb +=5
if(sume>sumb):
return "Erica"
else:
return "Bob"
if __name__ == '__main__':
e = input()
b = str(input())
print(winner(e,b))

Logic Gate implementation fails

I have made a logic gate that takes in two inputs which will then feed through into a AND gate in this case. For example the user will enter 0 and 0 then the AND gate will process as 0.
The problem here is when we use the IF statement to determine our two inputs, they are not recognised otherwise everything else in the program to process the two inputs along with a temporary storage for the output.
A = input("Enter a value of 1 or 0: ")
B = input("Enter a value of 1 or 0: ")
print(A)
print(B)
So the part above I am able to enter the inputs and create a storage for it.
The program tells me that A and B are unrecognised so does anyone know what I am doing wrong here?
this is where the problem takes place: everything from here to the else statement is ignored.
def first_AND ():
if A == 0 and B == 0:
AND_1()
print(AND)
print("Now solve the XOR gate")
gate_path_A()
elif A == 1 and B == 0:
AND_2()
print(AND)
print("Now solve the XOR gate")
gate_path_A()
elif A == 0 and B == 1:
AND_3()
print(AND)
print("Now solve the XOR gate")
gate_path_A()
elif A == 1 and B == 1:
AND_4()
print(AND)
print("Now solve the XOR gate")
gate_path_A()
else:
print("Error")
it skips all my elif statements and just prints an error.
def AND_1():
print(A & " AND " & B & " = 0")
AND = 0
def AND_2():
print(A & " AND " & B & " = 0")
AND = 0
def AND_3():
print(A & " AND " & B & " = 0")
AND = 0
def AND_4():
print(A & " AND " & B & " = 1")
AND = 1
I cleaned up your code for you: you should read up on python syntax, f.e. https://docs.python.org/2/reference/index.html (for 2.7.x) and do some tutorials
# define global
AND = None
#define the used functions
def gate_path_A():
print("Reached gate_path_A()")
return
def first_AND (A,B):
if A == 0 and B == 0:
AND_1(A,B)
print(AND)
print("Now solve the XOR gate")
gate_path_A()
elif A == 1 and B == 0:
AND_2(A,B)
print(AND)
print("Now solve the XOR gate")
gate_path_A()
elif A == 0 and B == 1:
AND_3(A,B)
print(AND)
print("Now solve the XOR gate")
gate_path_A()
elif A == 1 and B == 1:
AND_4(A,B)
print(AND)
print("Now solve the XOR gate")
gate_path_A()
else:
print("Error")
return
def AND_1(A,B):
print(A , " AND " , B , " = 0")
AND = 0
return
def AND_2(A,B):
print(A , " AND " , B ," = 0")
AND = 0
return
def AND_3(A,B):
print(A , " AND " , B , " = 0")
AND = 0
return
def AND_4(A,B):
print(A , " AND " , B , " = 1")
AND = 1
return
MAIN Program
# get one integer from user
a = None
while a is None:
try:
a = int(input("Enter a number: "))
except ValueError:
print("Not an integer value...")
print(str(a));
# get second integer from user
# you should really put this in a def and return the integer: DRY principle
b = None
while b is None:
try:
b = int(input("Enter a number: "))
except ValueError:
print("Not an integer value...")
print(str(b));
# call to the first and thing and supply the params your got from user
first_AND(a,b);

Always Says Its The Wrong Answer?

I'm making a simple maths quiz its working fine except when I ask if its the correct answer it always says Incorrect if its correct or not. I'm not sure where I went wrong any help on this would be appreciated.
import random
QuestN = 1
QNC = 0
CS = 0
WS = 0
while True:
#Number Of Questions:
QNC = QNC + 1
if QNC == 10:
break
#Choosing The Questions
ops = ['+', '-', '*', '/']
num1 = random.randint(0,12)
num2 = random.randint(1,10)
operation = random.choice(ops)
#Simplifying The Operations
if operation == "+":
NEWOP = "+"
elif operation == "-":
NEWOP = "-"
elif operation == "*":
NEWOP = "x"
elif operation == "/":
NEWOP = "รท"
#Asking The Questions
print("Awnser This:")
print(num1)
print(NEWOP)
print(num2)
maths = eval(str(num1) + operation + str(num2))
#Awnsering The Questions
PLAYERA = input(": ")
print(maths)
#Keeping Score
if PLAYERA == maths:
print("Correct")
CS = CS +1
else:
print("Incorrect")
WS = WS +1
print()
#RESTART
The variable PLAYERA will be a string. The variable maths will be an integer. In Python, "7" isn't the same thing as 7, so your if statement will never be true.
You therefore need to this:
if int(PLAYERA) == maths:
print("Correct")
CS = CS +1
Note that this code will cause an error it the player's input isn't a number. You could avoid that by doing this instead:
if PLAYERA == str(maths):
print("Correct")
CS = CS +1

Categories

Resources