if statement only executes else block - python

I am making a program which makes a mark list with a letter grade in python.
But the problem is the if-else statements to decide letter grade is only executing else statement when given inputs. But the if statement for 'A+' grade is working if maximum marks are given. I am a newbie and I can't understand where the bug is, please help. Below is my python code, here datails.html collects information from the user and mark list is displayed in the results.html page.
from flask import Flask, render_template, request
app=Flask(__name__)
#app.route("/")
def index():
return render_template('details.html')
#app.route("/send",methods=['POST','GET'])
def send():
if(request.method=='POST'):
getname=request.form['name']
getregno=request.form['regno']
getcollege=request.form['college']
getsem=request.form['sem']
getsub1=request.form['sub1']
getsub1m=request.form['sub1m']
getsub2=request.form['sub2']
getsub2m=request.form['sub2m']
getsub3=request.form['sub3']
getsub3m=request.form['sub3m']
getsub4=request.form['sub4']
getsub4m=request.form['sub4m']
malayalam_mark = int(getsub1)
malayalam_maxmark = int(getsub1m)
english_mark = int(getsub2)
english_maxmark = int(getsub2m)
maths_mark = int(getsub3)
maths_maxmark = int(getsub3m)
computer_mark = int(getsub4)
computer_maxmark = int(getsub4m)
percent_malayalam = malayalam_mark/malayalam_maxmark*100
percent_english = english_mark/english_maxmark*100
percent_maths = maths_mark/maths_maxmark*100
percent_computer = computer_mark/computer_maxmark*100
slist= [percent_malayalam,percent_english,percent_maths,percent_computer]
result_list=[]
for i in slist:
if i>=50 and i<58:
grade='D+'
result='pass'
elif i>=58 and i<65:
grade='C'
result='Pass'
elif i>=65 and i<72:
grade='C+'
result='Pass'
elif i>=72 and i<79:
grade='B'
result='Pass'
elif i>=79 and i<86:
grade='B+'
result='Pass'
elif i>=86 and i<93:
grade='A'
result='Pass'
elif i>=93 and i<=100:
grade='A+'
result='Pass'
else:
grade='D'
result='Fail'
result_list.append(grade)
result_list.append(result)
return render_template('/results.html',list=result_list,a=getname,b=getregno,c=getsem,d=getcollege,e=getsub1,e1=getsub1m,f=getsub2,f1=getsub2m,g=getsub3,g1=getsub3m,h=getsub4,h1=getsub4m)
if(__name__=='__main__'):
app.run(debug=True)
I am including a result page, here I included the final list in the bottom for reference, you can find that every input gives grade 'D' and result 'Fail' except maximum marks.

I guess this is being run in Python 2 which doesn't automatically promote integer division. If you rearrange your calculations like:
percent_malayalam = malayalam_mark * 100 / malayalam_maxmark
you might get the right answer… Previously all non-100% results were being (implicitly) rounded to 0%. 2 / 3 in Python 2 will be 0, not ~0.6. The defaults have been changed in Python 3 so it tends to do the right thing more often.
You could then read about integer division in Python 2 from various places, here's one at this site: What is the difference between '/' and '//' when used for division?

Related

How to go through while loop again?

Im making a simple question and answer app in python , in this specific example it displays a word in simple chinese and gives two answers to pick wrong or right , i'm struggling to present a new question without restarting my code. This my go at making an app that helps me learn chinese and I wanted to use minimum help , hence the weird code.
For example :
the question is what is 1+1 and the user answered two then I want to go thourgh the code again an present the next question.
the specific section im trying the run from inside a function, so when the user answers correctly or incorrectly by pressing the button in the function I want to go through the code again and present my next question
`
# ans
def button_1(event):
if Ans_option1.text == ans_or_not["ans"]:
print('correct')
return 'correct'
else:
print("incorrect")
def button_2 (event):
if Ans_option2.text == ans_or_not["ans"]:
print('correct')
return 'correct'
else:
print("incorrect")
Ans_option1 = gp.Button(app,return_1(), button_1)
Ans_option2 = gp.Button(app,return_2(),button_2)
app.add(Ans_option1,3,2, align = 'center')
app.add(Ans_option2,3,4, align = 'center')
app.run()
`
whole code
import gooeypie as gp
import random
app = gp.GooeyPieApp ('hello')
app.set_size (1000,500)
i = 2
n =3
while True :
# use dictionary instead of lists so we c an have an answer to the questions
question_dict = {
'xihuan' : 'like',
'Wo': 'I',
'Ni': 'you'
}
# random picks a value from a list of values made here
picker = random.choice(list(question_dict.values()))
# I remake the same list here again as the indexing stays the same then find the index for the random value
ind = list(question_dict.values()).index(picker)
# I make a list of the keys and they have mathing indexes to their values and we use the index number given to us previously to find the key
final = list(question_dict.keys())[ind]
# print(final)
test = 1
def question ():
question_dict.pop(final)
print(question_dict)
# return final
return final
ans_or_not = {
# this works first before the item is popped so it can cause a they same two words to appear on the buttons
# varialbe from inside the functions arent stected outside , making this whole dictionary meaningless
'ans' : picker,
'non' : random.choice(list(question_dict.values()))
}
print(ans_or_not["non"])
print(ans_or_not["ans"])
while ans_or_not["non"] == ans_or_not["ans"]:
ans_or_not.pop('non')
print(ans_or_not)
ans_or_not['non'] = random.choice(list(question_dict.values()))
print(ans_or_not["non"])
print(ans_or_not["ans"])
nums = random.randrange(1,3)
print(nums)
def return_1():
# while anss == nons :
# anss = random.randrange(0,2)
# print(anss + ','+ nons)
if nums == 1 :
return ans_or_not["ans"]
if nums == 2:
return ans_or_not["non"]
def return_2():
# while anss == nons :
# anss = random.randrange(0,2)
# print(anss + ','+ nons)
if nums == 1 :
return ans_or_not["non"]
elif nums == 2:
return ans_or_not["ans"]
# design and layout
def menu_select (event):
pass
menu_path = ' > '.join(event.menu)
status.text = menu_path
app.add_menu_item('Menu 1', 'Item 1', menu_select)
# grid setup
app.set_grid(4,5)
question_lbl = gp.Label(app,question())
app.add(question_lbl,2,3, align = 'center')
# ans
def button_1(event):
if Ans_option1.text == ans_or_not["ans"]:
print('correct')
return 'correct'
else:
print("incorrect")
def button_2 (event):
if Ans_option2.text == ans_or_not["ans"]:
print('correct')
return 'correct'
else:
print("incorrect")
Ans_option1 = gp.Button(app,return_1(), button_1)
Ans_option2 = gp.Button(app,return_2(),button_2)
app.add(Ans_option1,3,2, align = 'center')
app.add(Ans_option2,3,4, align = 'center')
app.run()
What i've tried
i've tried using the continue function
ways to restart while loops
You have the problem wrong.
This is going to sound really complicated, but stay with me. So what app.run() does is start the program, and it displays what you have already added to it. By putting app.run() in the while loop, despite calling it multiple times, will only call once. What you need to do is draw the label and buttons, run the app, then start the while loop. In fact, I wouldn't use a while loop here at all. Instead, I would have is so you have a dictionary for the right and wrong answers, then simply modify that and the button text when you get the answer correct. I don't really understand your code, but it would look something like:
#function for choosing answer
#function for checking button one
#function for checking button two
#draw button one and two and label
app.run()
Also, you would have it so that if you got the answer right, you would choose a new one.

trying to make progrm to format chemical equation

Given an input of something like Na(Cl2)3Al(AlCl2)4 I am trying to make a program without any libraries to do this and the code that I made is not working and I cant figure out why.
can someone show me exactly where i am going wrong (or fix it for me)? the output for the example input should look like NaCl6AlAl4Cl8 where brackets are removed also. thanks in advance for any help.
def format(equation):
equation_list = list(equation)
formated = ''
for i in range(len(equation_list)):
if equation_list[i] == '(':
opening = i
if equation_list[i] == ')':
closing = i
for i in range(opening+1,closing):
if equation_list[i].isdigit():
equation_list[i] = str(int(equation_list[i])*mult)
if equation_list[i].upper():
if equation_list[i+1].isupper():
equation_list[i+1] = str(mult)
elif equation_list[i+1].isdigit():
equation_list[i+1] = str(int(equation_list[i+1])*mult)
else:
if equation_list[i+2].isupper():
equation_list[i+2] = str(mult)
elif equation_list[i+2].isdigit():
equation_list[i+2] = str(int(equation_list[i+2])*mult)
else:
if equation[i+3].isdigit():
equation_list[i+3] = str(int(equation_list[i+3])*mult)
else:
equation[i+3] = str(mult)
for i in equation_list:
formated+=i
return formated
print(format('Na(Cl2)3Al(AlCl2)4'))
As the pointed duplicate has no voted-up answered, I'd like to propose one, based on regexes. I'm pretty sure it doesn't match all cases, but yours at least
import re
EQ_PATTERN = re.compile(r"([A-Z][a-z]+\d*|\((?:[A-Z][a-z]+\d*)+\)\d*)")
BLOCK_PATTERN = re.compile(r"\(((?:[A-Z][a-z]+\d*)+)\)(\d*)")
ELEMENT_PATTERN = re.compile(r"([A-Z][a-z]+)(\d*)")
def format_element(element: str, amount: str, factor: int):
return f"{element}{int(amount or '1') * factor}"
def format_block(block: str):
if '(' not in block:
return block
inside, factor = BLOCK_PATTERN.findall(block)[0]
return "".join(format_element(element, amount, int(factor))
for element, amount in ELEMENT_PATTERN.findall(inside))
def format_equation(eq: str):
return "".join(map(format_block, EQ_PATTERN.findall(eq)))
With some tests
for eq in ('(Al3Cl2Ag6Au)4', 'Na(Cl2)3Al(AlCl2)4', 'Na2(Cl2)3Al(Al3Cl2)4'):
print(f"{eq:20s} ==> {format_equation(eq)}")
(Al3Cl2Ag6Au)4 ==> Al12Cl8Ag24Au4
Na(Cl2)3Al(AlCl2)4 ==> NaCl6AlAl4Cl8
Na2(Cl2)3Al(Al3Cl2)4 ==> Na2Cl6AlAl12Cl8

I am trying to add a value , when a person have the right answer

I am trying to make a code in Python for a Otree aplication.
The main idea is to add $20 to a fixed payment when a person have the same answer that I put in my constants.
For example in this code I have a value of 3 in Constants.retemv if a person put a response of 3 in the J11 form the will get the $20
I try to use the next code, payment is a constant with a $20 value.
def set_payoff(self):
self.payoff = Constants.participation_fee + Constants.iat
if self.J11 == Constants.retemv:
self.payoff += Constants.payment
I expect the output of $45 when the people put the same answer that my retemv”
This is probably what you are looking for:
def set_payoff(self):
if self.J11 == Constants.retemv:
self.payoff = Constants.participation_fee + Constants.iat + Constants.payment
else:
self.payoff = Constants.participation_fee + Constants.iat

How to prevent printing from previous function in current function?

I'm currently writing a test function for class to test provided cases on provided solution code. However I'm running into an issue where a print statement is executing when I don't want it to.
This is the provided solution that I'm testing:
def alphapinDecode(tone):
phone_num = ''
if checkTone(tone): #or checkTone2
while len(tone) > 0:
# retrieve the first tone
next_tone = tone[0:2]
tone = tone[2:]
# find its position
cons = next_tone[0]
vow = next_tone[1]
num1 = consonants.find(cons)
num2 = vowels.find(vow)
# reconstruct this part of the number -
# multiply (was divided) and add back
# the remainder from the encryption division.
phone = (num1 * 5) + num2
# recreate the number
# by treating it as a string
phone = str(phone)
# if single digit, not leading digit, add 0
if len(phone) == 1 and phone_num != '':
phone = '0' + phone
phone_num = phone_num + phone
# but return in original format
phone_num = int(phone_num)
else:
print('Tone is not in correct format.')
phone_num = -1
return phone_num
Here's the (partially done) code for the test function I have written:
def test_decode(f):
testCases = (
('lo', 43),
('hi', 27),
('bomelela', 3464140),
('bomeluco', 3464408),
('', -1),
('abcd', -1),
('diju', 1234),
)
for i in range(len(testCases)):
if f(testCases[i][0]) == testCases[i][1] and testCases[i][1] == -1:
print('Checking '+ f.__name__ + '(' + testCases[i][0] + ')...Tone is not in correct format.')
print('Its value -1 is correct!')
return None
When executing test_decode(alphapinDecode), I get this:
Tone is not in correct format.
Checking alphapinDecode()...Tone is not in correct format.
Its value -1 is correct!
Tone is not in correct format.
Checking alphapinDecode(abcd)...Tone is not in correct format.
Its value -1 is correct!
As you can see, because of the print statement in alphapinDecode(I think), it is printing an extra "Tone is not in correct format." above the print statement I have written.
How would I prevent this print statement from executing, and why is it printing if the print statement I wrote in my test function doesn't ask for the result of alphapinDecode?
We are not allowed to alter the code of the given solution.
I'm fairly new to stackOverflow, so sorry for any formatting issues. Thank you!
Edit: Fixed the idents of the test_decode function
One easy solution would be to pass an extra parameter say, a boolean variable debug to the function. That would go something like this.
def func1(var1, debug):
if debug:
print("Printing from func1")
# Do additional stuff
Now when you call it. You now have the option of setting the debug variable.
func1("hello", debug=True) # will print the statement
func1("hello", debug=False) # will not print statement.
If you cannot modify the called function. Then you can follow this method. explained by #FakeRainBrigand here.
import sys, os
# Disable
def blockPrint():
sys.stdout = open(os.devnull, 'w')
# Restore
def enablePrint():
sys.stdout = sys.__stdout__
print 'This will print'
blockPrint()
print "This won't"
enablePrint()
print "This will too"

How do you navigate through functions within functions in Python3

Once you are in a function, How would you be able to navigate from function to function within your original function? (I wrote pseudo code because I do not know how to accomplish this)
def main():
do...
if something == 1
access function(Success)
elif something == 2
access function(Failed)
elif something == 3
end script
else
print "choose a proper option idiot"
def menuSuc():
print 1) How many total requests (Code _____)
print 2) How many requests from _____ (IPs starting with 142.204)
print 3) How many requests for isomaster-1.3.13.tar.bz2
print q) Return to Main Menu
def menuFai():
print 1) How many total failed requests (Codes _____)
print 2) How many invalid requests for wp-login.php
print 3) List the filenames for failed requests for files in /apng/assembler/data
print q) Return to Main Menu
def success(argv):
do.....
print menuSuc
print information
def failed(argv):
do.....
print menuFai
print information
Just call the function you want to use inside the function. I would avoid calling a function a function in Python code. Don't forget that in Python 3 print is a function--add "()" around the quotes.
def main():
if something == 1:
Success() # to access function(Success)
elif something == 2:
Failed()
elif something == 3:
return print("script Done")
else:
print("choose a proper option") # no need to call people names :)
main()

Categories