Python 3.3 programs not working? - python

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.

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.

My input in if statement is not working as expected

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())

How to alter a class using a method based off user input within a function

Building a simple to-do list app to teach myself classes. Nearly everything works (so far, you can add items, view the list, and remove items). But, I can't seem to figure out how to implement a change item feature. This is supposed to change the name of an already created item, but the code I'm working on isn't doing it.
# counters for telling if a slot is empty or not
a = 0
b = 0
c = 0
d = 0
e = 0
# overarching class for entire program
# outlines how a list item is structured
class Item():
def __init__(self, thingToDo, dueDate, priority):
self.thingToDo = thingToDo
self.dueDate = dueDate
self.priority = priority
def thingChange(self):
thingChange = input("What would you like to change it to? ")
self.thingToDo = thingChange
def whatToChange():
global whatToChange
whatToChange = input("What in the item would you like to change (1. thing, 2. due date, 3. priority)?")
if "1" in whatToChange:
itemChange = input("What would you like to change it to? ")
item1.thingToDo = itemChange
printCurrentList()
# takes inputs to add an instance of to do item
def getItem():
global thing
thing = input("What do you want to do?")
global time
time = input("When do you need to do it by?")
global importance
importance = input("Priority (rate out of 5): ")
# each of these takes the inputs from getItem(), and puts them into the slots
def runItem1():
getItem()
global item1
item1 = Item(thing, time, importance)
print("1. You need to " + item1.thingToDo + " by " + item1.dueDate + ", and the priority is " + item1.priority + "/5.")
global a
a = a + 1
def runItem2():
getItem()
global item2
item2 = Item(thing, time, importance)
print("2. You need to " + item2.thingToDo + " by " + item2.dueDate + ", and the priority is " + item2.priority + "/5.")
global b
b = b + 1
def runItem3():
getItem()
global item3
item3 = Item(thing, time, importance)
print("3. You need to " + item1.thingToDo + " by " + item1.dueDate + ", and the priority is " + item1.priority + "/5.")
global c
c = c + 1
def runItem4():
getItem()
global item4
item4 = Item(thing, time, importance)
print("4. You need to " + item4.thingToDo + " by " + item4.dueDate + ", and the priority is " + item4.priority + "/5.")
global d
d = d + 1
def runItem5():
getItem()
global item5
item5 = Item(thing, time, importance)
print("5. You need to " + item5.thingToDo + " by " + item5.dueDate + ", and the priority is " + item5.priority + "/5.")
global e
e = e + 1
# pretty self explanatory, prints out the current slots in a list-type format
def printCurrentList():
if a > 0:
print("1. You need to " + item1.thingToDo + " by " + item1.dueDate + ", and the priority is " + item1.priority + "/5.")
else: print("Slot 1 is empty.")
if b > 0:
print("2. You need to " + item2.thingToDo + " by " + item2.dueDate + ", and the priority is " + item2.priority + "/5.")
else:
print("Slot 2 is empty.")
if c > 0:
print("3. You need to " + item1.thingToDo + " by " + item1.dueDate + ", and the priority is " + item1.priority + "/5.")
else:
print("Slot 3 is empty.")
if d > 0:
print("4. You need to " + item4.thingToDo + " by " + item4.dueDate + ", and the priority is " + item4.priority + "/5.")
else:
print("Slot 4 is empty.")
if e > 0:
print("5. You need to " + item5.thingToDo + " by " + item5.dueDate + ", and the priority is " + item5.priority + "/5.")
else:
print("Slot 5 is empty.")
# adds an item to the list, but first, checks to see if list slots are already used -- uses a,b,c,d,e
def add():
printCurrentList()
if a > 0 and b > 0 and c > 0 and d > 0 and e > 0:
print("You need to empty a slot before you add another item.")
whichToRemove = input("Which slot would you like to remove?")
if input == "1":
print("What would you like to add in its place?")
runItem1()
else:
slot = input("Which slot would you like to use?: ")
if slot == "1":
runItem1()
elif slot == "2":
runItem2()
elif slot == "3":
runItem3()
elif slot == "4":
runItem4()
elif slot == "5":
runItem5()
else:
print("Error. Please try again.")
add()
# main loop of the program
def main():
prompt = input("What do you want to do (add, remove, change, or view)?: ")
if prompt == "add":
add()
elif prompt == "remove":
printCurrentList()
whichToRemove = input("Which one would you like to remove?: ")
if whichToRemove == "1":
print("Item 1, " + item1.thingToDo + ", has been removed.")
global a
a = 0
elif whichToRemove == "2":
print("Item 2, " + item2.thingToDo + ", has been removed.")
global b
b = 0
elif whichToRemove == "3":
print("Item 3, " + item3.thingToDo + ", has been removed.")
global c
c = 0
elif whichToRemove == "4":
print("Item 4, " + item4.thingToDo + ", has been removed.")
global d
d = 0
elif whichToRemove == "5":
print("Item 5, " + item5.thingToDo + ", has been removed.")
global e
e = 0
printCurrentList()
elif prompt == "view":
print("Here is your current list: ")
printCurrentList()
elif prompt == "change":
whichToChange = input("Which one would you like to change?: ")
if "1" in whichToChange:
oldItem = item1.thingToDo
whatToChange()
thingChange()
print("Item 1, " + oldItem + ", has been changed to " + item1.thingToDo)
elif "2" in whichToChange:
print("Item 2, " + item2.thingToDo + ", has been changed to _____________.")
elif "3" in whichToChange:
print("Item 3, " + item3.thingToDo + ", has been changed to _____________.")
elif "4" in whichToChange:
print("Item 4, " + item4.thingToDo + ", has been changed to _____________.")
elif "5" in whichToChange:
print("Item 5, " + item5.thingToDo + ", has been changed to _____________.")
printCurrentList()
main()
main()
Is there a way to get this working?
It looks like you're mixing procedural methods with object orientated methods.
One of the principles of object orientated design is determining where the functions belong ... which functions belong to which class.
Once I had that sorted out for myself moving from thinking just procedurally to thinking in terms of objects became much easier for me.
I suggest creating a list [], or a dictionary {} to store your items.
Then print current list can be handled by
item_list = []
# ... create items and add to item_list using item_list.append(item)
for item in item_list:
print(item)
or
item_dictionary = {}
# create items and add to item_dictionary using item_dictionary[some_key] = item
for key in item_dictionary:
item = item_dictionary[key]
Then add whatever functions you need for your item class and use methods to add/remove/edit those items in the list of the dictionary.
I'd also drop the globals as the commentators suggested. I don't use globals at all in the python code I write.

How do I return to the previous while loop?

x, y = raw_input("Enter 2 numbers separated by a space.").split()
answer = 0
#Enter the 2 numbers to be calculated.
print "You have selected, A = "+ x + " and B = " + y + "."
while int(y):
if (not int(y) % 2 == 0):
# this checks if y is even or odd
answer = int(answer) + int(x)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is odd so we'll add A to the total."
print "The running total is " + str(answer) + "."
else: (int(y) % 2 == 0)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is even, so we'll ignore that number."
x = int(x) * 2
y = int(y) / 2
print "The product is " + str(answer) + "."
while True:
a = raw_input("Would you like to make another calculation? Y or N")
if str(a) == "Y" or str(a) == "y":
continue
if str(a) == "N" or str(a) == "n":
print "Thank you have a nice day!"
break
else:
print "Invalid entry. Ending program."
break
I'm trying to get my program to go back to the top while loop if "Y" or "y" is entered for 'Would you like to make another calculation?'. So far what I have returns me to the bottom while loop. Any help? Thanks!
It looks like your second loop should actually be an outer loop (in this case often called a "game loop"). The entire application loops until the user specifies to end the application. Something like this:
a = "Y"
while (a == "Y"):
##########
# All of your "first loop" logic goes here.
# This is the primary "step" of any given instance of the "game".
##########
# Then, prompt the user to continue or not...
a = raw_input("Would you like to make another calculation? Y or N")
if str(a) == "Y" or str(a) == "y":
continue
if str(a) == "N" or str(a) == "n":
print "Thank you have a nice day!"
break
else:
print "Invalid entry. Ending program."
break
(Note: This is freehand code and I'm not entirely familiar with Python, so there may need to be some tweaking on the specifics. This is meant to demonstrate the structure, not to be copied/pasted as production code.)
Try nesting the first while loop inside of the second. It'll run your calculation code first, check to see if you'd like to do another, and then return to the top of the while True: loop to do another calculation.
Like this:
while True:
x, y = raw_input("Enter 2 numbers separated by a space.").split()
answer = 0
#Enter the 2 numbers to be calculated.
print "You have selected, A = "+ x + " and B = " + y + "."
while int(y):
if (not int(y) % 2 == 0):
# this checks if y is even or odd
answer = int(answer) + int(x)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is odd so we'll add A to the total."
print "The running total is " + str(answer) + "."
else: (int(y) % 2 == 0)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is even, so we'll ignore that number."
x = int(x) * 2
y = int(y) / 2
print "The product is " + str(answer) + "."
a = raw_input("Would you like to make another calculation? Y or N")
if str(a) == "Y" or str(a) == "y":
continue
if str(a) == "N" or str(a) == "n":
print "Thank you have a nice day!"
break
else:
print "Invalid entry. Ending program."
break
Hope that helps
Depending on what you're trying to do, and where this particular code appears in your program, it's usually advised to wrap your code inside of functions. That way, it doesn't automatically run when you import your module. You have to call a function to make the code run.
If you want to make this an executable script, you'd want to wrap the main loop code in a if __name__ == '__main__: block so that it only executes if it's being executed directly.
e.g.:
def perform_calculation():
while True:
x, y = raw_input("Enter 2 numbers separated by a space.").split()
answer = 0
#Enter the 2 numbers to be calculated.
print "You have selected, A = "+ x + " and B = " + y + "."
while int(y):
if (not int(y) % 2 == 0):
# this checks if y is even or odd
answer = int(answer) + int(x)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is odd so we'll add A to the total."
print "The running total is " + str(answer) + "."
else: (int(y) % 2 == 0)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is even, so we'll ignore that number."
x = int(x) * 2
y = int(y) / 2
print "The product is " + str(answer) + "."
def run_loop():
while True:
perform_calculation()
a = raw_input("Would you like to make another calculation? Y or N")
if str(a) == "Y" or str(a) == "y":
continue
if str(a) == "N" or str(a) == "n":
print "Thank you have a nice day!"
break
else:
print "Invalid entry. Ending program."
break
if __name__ == '__main__':
run_loop()

Categories

Resources