My input in if statement is not working as expected - python

My input in my if statement is not working. I am using Python3 and the problem is at the first if statement in the defined function.
import random
random1 = random.randint(1, 11)
random2 = random.randint(1, 11)
correct = random1 * random2
list_of_correct = []
list_of_wrong = []
def ex():
proceed = input("Proceed?: ")
if proceed.lower == "yes":
ans = input("What is " + str(random1) + " * " + str(random2) + "?: ")
if int(ans) == correct:
print("Correct!")
list_of_correct.append(str(random1 + ":" + str(random2) + ":" + str(ans)))
print(ex())
else:
print("Incorrect!")
list_of_wrong.append(str(random1) + ":" + str(random2) + ":" + str(ans))
elif proceed.lower == "mfm":
print(list_of_correct)
print(list_of_wrong)
print(ex())

You compare a function proceed.lower against a string 'yes' - they are never the same.
You need to call the function:
if proceed.lower() == "yes":
to convert your input to lower case for your comparison.
print("".lower) # <built-in method lower of str object at 0x7fc134277508>

Fixed code
import random
random1 = random.randint(1, 11)
random2 = random.randint(1, 11)
correct = random1 * random2
list_of_correct = []
list_of_wrong = []
def ex():
proceed = input("Proceed?: ")
if proceed.lower() == "yes":
ans = input("What is " + str(random1) + " * " + str(random2) + "?: ")
if int(ans) == correct:
print("Correct!")
list_of_correct.append(str(random1 + ":" + str(random2) + ":" + str(ans)))
print(ex())
else:
print("Incorrect!")
list_of_wrong.append(str(random1) + ":" + str(random2) + ":" + str(ans))
elif proceed.lower() == "mfm":
print(list_of_correct)
print(list_of_wrong)
print(ex())

Related

How to verify input using try, except and assertion in python?

I have made a program to calculate GPA of student but i need to verify that if the letter grade inputted by the user is between A+ to F or not by using try, except and assert. Here's my code:
from num2words import num2words
courses = {}
total = 0
while True:
course_name = input("Enter course name: ")
if(course_name == "" or course_name == " "):
break
else:
courses[course_name] = []
def pointvalue(x):
if x == "A+" or x == "a+":
return "4.2 points"
elif x == "A" or x == "a" :
return "4.0 points"
elif x == "B+" or x == "b":
return "3.5 points"
elif x == "B" or x == "b":
return "3.0 points"
elif x == "C+" or x == "c+":
return "2.5 points"
elif x == "C" or x == "c":
return "2.0 points"
elif x == "D+" or x == "d+":
return "1.5 points"
elif x == "D" or x == "d":
return "1 points"
for i in range(len(courses)):
cnames = list(courses.keys())[i]
letter_grades = input("Enter letter grade for " + str(cnames) + ": ")
course_credit = float(input("Enter course credit for " + str(cnames) + ": " ))
pointg = pointvalue(letter_grades)
courses[cnames].append(letter_grades)
courses[cnames].append(pointg)
courses[cnames].append(course_credit + " credits")
print("")
print("")
for i in range(len(courses)):
cnames = list(courses.keys())[i]
print("Course " + str(cnames) + " student grade as follows: " + str(courses[cnames]))
print("")
print("")
print("The GPA for this student with " + str((num2words(len(courses)).upper())) + " courses would be: ")
for x in range(len(courses)):
cnames = list(courses.keys())[x]
gradepoints = courses[cnames][1]
credits = courses[cnames][2]
total = total + (int(gradepoints) * int(credits))
if x == 0:
print(" ( " + str(gradepoints) + " * " +str(credits) + " )")
else:
print(" + ( " + str(gradepoints) + " * " +str(credits) + " )")
print("----------------------------------------------")
print("Total of above "+ str(total) + " ." )
All the courses and their grade points, and credit points must be saved in a single dictionary. :)
Thanks <3
You can rewrite the pointValue function in less lines like this
#!/usr/bin/python
grades ={
"A+" : "4.2 Points",
"A" : "4.0 Points",
"B+" : "3.5 Points",
"B" : "3.0 Points",
"C+" : "2.5 Points",
"C" : "2.0 Points",
"D+" : "1.5 Points",
"D" : "1.0 Points"
}
def pointValue(x):
if x in grades:
return grades.get(x)
g = input("Enter Grade\n")
while True:
try:
assert g.upper() in grades
print(pointValue(g.upper()))
break
except AssertionError:
print("Invalid Entries")
g = input("Enter Grade\n")
converting the input to upper() case , will reduce the duplicate entries for A and a
try:
letter_grades = input("Enter letter grade for ")
assert letter_grades in grades
except AssertionError:
print(f"Input should be: {grades}")
I have add one function verify_letter_grades to support verify letter_grades:
from num2words import num2words
import re
regex = r"\s*[a|a+|b|b+|c|c+|d|d+|A|A+|B|B+|C|C+|D|D+]"
courses = {}
total = 0
while True:
course_name = input("Enter course name: ")
if(course_name == "" or course_name == " "):
break
else:
courses[course_name] = []
def pointvalue(x):
if x == "A+" or x == "a+":
return "4.2 points"
elif x == "A" or x == "a" :
return "4.0 points"
elif x == "B+" or x == "b":
return "3.5 points"
elif x == "B" or x == "b":
return "3.0 points"
elif x == "C+" or x == "c+":
return "2.5 points"
elif x == "C" or x == "c":
return "2.0 points"
elif x == "D+" or x == "d+":
return "1.5 points"
elif x == "D" or x == "d":
return "1 points"
def verify_letter_grades(letter_grades):
re_letter_grades = re.compile(regex)
if letter_grades is not None:
m_letter_grades = re_letter_grades.search(letter_grades)
assert m_letter_grades is None, 'Please make sure input in range'
else:
assert letter_grades is None, 'Please make sure input is not None'
for i in range(len(courses)):
cnames = list(courses.keys())[i]
letter_grades = input("Enter letter grade for " + str(cnames) + ": ")
verify_letter_grades(letter_grades)
course_credit = float(input("Enter course credit for " + str(cnames) + ": " ))
pointg = pointvalue(letter_grades)
courses[cnames].append(letter_grades)
courses[cnames].append(pointg)
courses[cnames].append(course_credit + " credits")
print("")
print("")
for i in range(len(courses)):
cnames = list(courses.keys())[i]
print("Course " + str(cnames) + " student grade as follows: " + str(courses[cnames]))
print("")
print("")
print("The GPA for this student with " + str((num2words(len(courses)).upper())) + " courses would be: ")
for x in range(len(courses)):
cnames = list(courses.keys())[x]
gradepoints = courses[cnames][1]
credits = courses[cnames][2]
total = total + (int(gradepoints) * int(credits))
if x == 0:
print(" ( " + str(gradepoints) + " * " +str(credits) + " )")
else:
print(" + ( " + str(gradepoints) + " * " +str(credits) + " )")
print("----------------------------------------------")
print("Total of above "+ str(total) + " ." )

I don't know how to make a while loop last until a list doesn't have any values left

I am trying to recreate the card game "War" in python and cant figure out how to loop the code under the comment until every value in the list is gone. So basically the code generates a shuffled deck of cards and pops the cards from the list. I want to have the code repeat until all the cards have been popped from the deck and I have no idea how to do that.
import random
def shuffled_deck():
deck = list(range(2, 15)) *4
random.shuffle(deck)
return deck
userdeck = shuffled_deck()
print("welcome to War!")
user1 = input("Player-1 name: ")
user2 = input("Player-2 name: ")
u1points = 0
u2points = 0
drawturns = 0
# - I want to loop the segment of code under this comment
usercard = userdeck.pop()
u1card = usercard
print(user1 + ": " + str(u1card))
usercard = userdeck.pop()
u2card = usercard
print(user2 + ": " + str(u2card))
if u1card > u2card:
print(str(u1card) + " is greater than " + str(u2card) + ".")
print(user1 + " won this round.")
u1points +=1
elif u2card > u1card:
print(str(u2card) + " is greater than " + str(u1card) + ".")
print(user2 + " won this round.")
u2points +=1
else:
print("It's a draw, try again.")
while u1card == u2card:
drawturns +=1
usercard = userdeck.pop()
u1card = usercard
print(user1 + ": " + str(u1card))
usercard = userdeck.pop()
u2card = usercard
print(user2 + ": " + str(u2card))
if u1card > u2card:
print(str(u1card) + " is greater than " + str(u2card) + ".")
print(user1 + " won this round.")
u1points +=1
u1points + drawturns
elif u2card > u1card:
print(str(u2card) + " is greater than " + str(u1card) + ".")
print(user2 + " won this round.")
u2points +=1
u1points + drawturns
else:
print("It's a draw, try again.")
if u1card == u2card == False:
drawturns = 0
break
You can do:
while len(userdeck)>0:
or, you can write smartly as:
while userdeck:
This is because an empty list is considered as False, whereas a non empty list is considered as True. So, when userdeck is empty, while loop will assume it to be False case, so the loop will stop. This same concept can also be applied for if statements.

How to not break, but restart the while True statement

ok so i was coding the "hangman" game on python and I basically want to know how to tell what position in the word the letter is in, and then ask the question what letter do I choose again. Instead it keeps spamming the position of the letter that it is in the word. Any help?
while True:
for i in range(0, len(word)):
if word[i] == guess and i > 2:
print("Your letter is " + str(i + 1) + "th" + "!")
elif word[i] == guess and i == 2:
print("Your letter is " + str(i + 1) + "rd" + "!")
elif word[i] == guess and i == 1:
print("Your letter is " + str(i + 1) + "nd" + "!")
elif word[i] == guess and i == 0:
print("Your letter is the " + str(i + 1) + "st" + "!")
guess = (str(input("Guess one letter!: ")))
I don't really know what youre base programm was, your code gives out lots of indent problems when I copy-pasted it. I only moved the "guess" input to the begin and fixed the indentation. I think this is what you want (I added an example).
word = ["w","o","r","d"]
while True:
guess = (str(input("Guess one letter!: ")))
for i in range(0, len(word)):
if word[i] == guess and i > 2:
print("Your letter is " + str(i + 1) + "th" + "!")
elif word[i] == guess and i == 2:
print("Your letter is " + str(i + 1) + "rd" + "!")
elif word[i] == guess and i == 1:
print("Your letter is " + str(i + 1) + "nd" + "!")
elif word[i] == guess and i == 0:
print("Your letter is the " + str(i + 1) + "st" + "!")

I'm getting a type error and I'm not sure why

I am using Python 2.5. I am not sure what's going wrong. I've tried this a million different ways and I am so confused.
Here is my code:
import math
quad_function = "(a * x^2) + b * x + c"
print "A quadratic function is:" + quad_function
a_input = raw_input("Is 'a' given?")
b_input = raw_input("Is 'b' given?")
c_input = raw_input("Is 'c' given?")
x_input = raw_input("Are any of the solutions given?")
if a_input == "yes":
a = int(raw_input("What is 'a'?"))
if b_input == "yes":
b = int(raw_input("What is 'b'?"))
if c_input == "yes":
c = int(raw_input("What is 'c'?"))
if x_input == "one":
x_1 = int(raw_input("What is the first solution?"))
if x_input == "both":
x_1 = int(raw_input("What is the first solution"))
x_2 = int(raw_input("What is the second solution"))
print 'The quadratic function is:' + str(a) + 'x^2' + '+' + str(b) + 'x' + "+" + str(c)
d = b ** 2 - 4*a*c
if d > 1:
num_roots = 2
if d == 1:
num_roots = 1
if d < 1:
num_roots = 0
print "There are " + str(num_roots) + " roots"
if x_input == "no" and d > 2 and a_input == 'yes' and b_input == 'yes' and c_input == 'yes':
x1 = float(((-b) + math.sqrt(d))/(2*a))
x2 = float(((-b) - math.sqrt(d))/(2*a))
print "The two solutions are: " + str(x1) * "and " + str(x2)
You've used an asterisk where you intended to use a plus sign. Replace
print "The two solutions are: " + str(x1) * "and " + str(x2)
with
print "The two solutions are: " + str(x1) + "and " + str(x2)

Python 3.3 programs not working?

I've made a few programs in Python now, but I'm still pretty new. I've updated to 3.3, and most of my programs are broken. I've replaced all of the raw_inputs now with input, but this still isn't working, and I get no errors.
Could one of you fine programmers help?
a = 1
while a < 10:
StartQ = input("Would you like to Start the program, or Exit it?\n")
if StartQ == "Exit":
break
elif StartQ == "Start":
AMSoD = input("Would you like to Add, Multiply, Subtract or Divide?\nPlease enter A, M, S or D.\n")
if AMSoD == "A":
Add1 = input("Add this: ")
Add2 = input("By this: ")
AddAnswer = int(Add1) + int(Add2)
AAnswer = Add1 + " " + "+" + " " + Add2 + " " + "=",AddAnswer
print(AAnswer)
print("The answer is:"),AddAnswer
elif AMSoD == "M":
Mul1 = input("Multiply this: ")
Mul2 = input("By this: ")
MulAnswer = int(Mul1) * int(Mul2)
MAnswer = Mul1 + " " + "*" + " " + Mul2 + " " + "=",MulAnswer
print(MAnswer)
print("The answer is:"), (MulAnswer)
elif AMSoD == "S":
Sub1 = input("Subtract this: ")
Sub2 = input("From this: ")
SubAnswer = int(Sub2) - int(Sub1)
SAnswer = Sub2 + " " + "-" + " " + Sub1 + " " + "=",SubAnswer
print(SAnswer)
print("The answer is:"), (SubAnswer)
elif AMSoD == "D":
Div1 = input("Divide this: ")
Div2 = input("By this: ")
DivAnswer = int(Div1) / int(Div2)
DAnswer = Div1 + " " + "/" + " " + Div2 + " " + "=",DivAnswer
print(DAnswer)
print("The answer is:"), (DivAnswer)
DivQoR = input("Would you like to Quit or restart?\nAnswer Quit or Restart.\n")
if DivQoR == "Restart":
a = 1
elif DivQoR == "Quit":
DivQoRAyS = input("Are you sure you want to quit? Answer Yes or No.\n")
if DivQoRAyS == "Yes":
break
elif DivQoRAyS == "No":
a = 1
Put all items you want to print in the parenthesis of the print() function call:
print("The answer is:", AddAnswer)
and
print("The answer is:", MulAnswer)
etc.
Where you build your strings, it'd be easier to do so in the print() function. Instead of
AAnswer = Add1 + " " + "+" + " " + Add2 + " " + "=",AddAnswer
print(AAnswer)
(where you forgot to replace the last comma with +), do this:
print(Add1, '+', Add2, '=', AddAnswer)
and so on for the other options.

Categories

Resources