How to verify input using try, except and assertion in python? - 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) + " ." )

Related

Debugging Maze game in Python

Ive been learning python recently and am currently working on a small terminal game that has a character move through a maze. Im having a bug where my character is getting stuck and not allowed to move into the open spaces. Ive checked that all my movements the correct directions, and im not sure why the character is stuck.
App
played = player.Player(3, 2)
while True:
board.printBoard(played.rowPosition, played.columnPosition)
selection = input("Make a move: ")
if selection == "w":
if board.checkMove(played.rowPosition - 1, played.columnPosition):
played.moveUp()
elif selection == "s":
if board.checkMove(played.rowPosition + 1, played.columnPosition):
played.moveDown()
elif selection == "a":
if board.checkMove(played.rowPosition, played.columnPosition - 1):
played.moveLeft()
elif selection == "d":
if board.checkMove(played.rowPosition, played.columnPosition - 1):
played.moveRight()
else:
print("Invalid key")
if board.checkWin(played.rowPosition, played.columnPosition):
print("You Win!")
break;
Player:
class Player:
def __init__(self, intitalRow, initialColumn):
self.rowPosition = intitalRow
self.columnPosition = initialColumn
def moveUp(self):
self.rowPosition = self.rowPosition - 1
def moveDown(self):
self.rowPosition = self.rowPosition + 1
def moveRight(self):
self.columnPosition = self.columnPosition + 1
def moveLeft(self):
self.columnPosition = self.columnPosition - 1
Gameboard
class GameBoard:
def __init__(self):
self.winningRow = 0
self.winningColumn = 2
self.board = [
[" * ", " * ", " ", " * ", " * ", " * "],
[
" * ",
" ",
" ",
" ",
" * ",
" * ",
],
[
" * ",
" ",
" * ",
" * ",
" ",
" * ",
],
[
" * ",
" ",
" ",
" ",
" ",
" * ",
],
[" * ", " * ", " * ", " * ", " * ", " * "],
]
def printBoard(self, playerRow, playerColumn):
for i in range(len(self.board)):
for j in range(len(self.board[i])):
if i == playerRow and j == playerColumn:
print("P", end="")
else:
print(self.board[i][j], end="")
print("")
def checkMove(self, testRow, testColumn):
if self.board[testRow][testColumn].find("*") != -1:
print("Can't move there!")
return False
return True
def checkWin(self, playerRow, playerColumn):
if playerRow == 0 and playerColumn == 2:
return True
else:
return False
When the selection is "d" the same cell is being checked as when the selection is "a". I think you meant for one of these to use played.columnPosition + 1.

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.

connect four: asking for inputs without printing

I am making a connect four type game. I am trying to set up the simple playability of the game. I don't get an error, but it does keep sending me into a input when I want it to print out the board. When I type in a number for the column, it doesn't print anything, it just gives me another input I should fill, this continues until i exit the program.. I am trying to stay away from classes, given that I am not very good at programming these yet. I would like to know why this is happening, and what to do to fix it, or if I just need to reprogram the whole thing.
a = [" ", " ", " ", " ", " ", " ", " "]
b = [" ", " ", " ", " ", " ", " ", " "]
c = [" ", " ", " ", " ", " ", " ", " "]
d = [" ", " ", " ", " ", " ", " ", " "]
e = [" ", " ", " ", " ", " ", " ", " "]
f = [" ", " ", " ", " ", " ", " ", " "]
board = [a, b, c, d, e, f] # sets up the board
print("What is player 1's name?")
player1 = input()
print("What is player 2's name?")
player2 = input()
plays = 0
def print_board(): # prints the board
p = 0
for x in board:
for i in x:
print(i, end=" | ")
print()
p += 1
if p != 6:
print("- "*15)
else:
print()
def win(): # defines a boolean if one player has won
i = 0
k = 0
while i != 5:
while k != 6:
if board[i][k] == "o" or board[i][k] == "x":
if board[i+1][k] == board[i][k] == board[i+2][k] == board[i+3][k]:
return False
elif board[i][k] == board[i][k+1] == board[i][k+2] == board[i][k+3]:
return False
elif board[i][k] == board[i+1][k+1] == board[i+2][k+2] == board[i+3][k+3]:
return False
elif board[i][k] == board[i-1][k-1] == board[i-2][k-2] == board[i-3][k-3]:
return False
else:
return True
def play(): # defines the part you play.
if plays % 2 == 0:
player = "o"
else:
player = "x"
print_board()
x = int(input("Where would you like to put your chip?"))
i = 0
while i < 5:
if board[i][x] == " ":
if board[i+1][x] == "x" or board[i+1][x] == "o":
board[i][x] = player
print_board()
if win():
print(player+" won!")
play()
play() # runs the script
try this for your play loop - hopefully it will help you fix the win check also:
def play(): # defines the part you play.
plays = 0
while True:
if plays % 2 == 0:
player = "o"
else:
player = "x"
x = int(input("Where would you like to put your chip?"))
i = 0
for i in range(5):
if board[i][x] == " ":
if board[i+1][x] == "x" or board[i+1][x] == "o":
board[i][x] = player
else:
board[5][x] = player
print_board()
#if win():
# print(player+" won!")
# break
plays += 1
print_board()
play() # runs the script
i commented out the win check because it doesn't work yet

Python Hangman not working

So, I've finished my Hangman project for a coding class and it's stuck in a loop where it just keeps asking if you want to play, after that it defines the word to play but it also TELLS you which word to play you're going to play. I think the chained whiles and ifs have some wrong variables.
So, I beg for your help.
__author__ = 'Rodrigo Cano'
#Modulos
import random
import re
#Variables Globales
intentos = 0
incorrectos = 0
palabras = [(1,"disclosure"),(1,"thenational"),(1,"foals"),(1,"skepta"),(1,"shamir"),(1,"kanye"),
(1,"fidlar"),(1,"lcdsoundsystem"),(1,"lorde"),(1,"fkatwigs"),(1,"miguel"),(1,"rtj"),
(1,"boniver"),(1,"strokes"),(2,"vaporwave"),(2,"witchouse"),(2,"shoegaze"),(2,"memerap"),
(2,"paulblartisoursaviour"),(3,"glockenspiel"),(3,"aesthetic"),(3,"schadenfreude"),
(3,"bonvivant"),(3,"swag"),(3,"jue")]
Ascii_Art =[""]
Dibujo = ' '
palabra_a_jugar = ''
Array_Palabra = []
Nuevas_Letras = ''
letras = []
Vidas = 0
i = len(Array_Palabra)
#Funciones
def Definir_Palabra():
eleccion = int(input("Bienvenido, que categoria quiere usar:"
'\n'"1 - Musica que Escuche Mientras Lo Hacia"
'\n'"2 - Generos Musicales"
'\n'"3 - Palabras Pretenciosas"))
palabras_escogidas = [i for i in palabras if eleccion in i ]
palabra_a_jugar = str(palabras_escogidas[random.randint(0,len(palabras_escogidas))].__getitem__(1))
Array_Palabra = len(palabra_a_jugar) * ['*']
return palabra_a_jugar, Array_Palabra
def Letras_En_Palabra(letra):
letras = [i for i, x in enumerate(palabra_a_jugar) if x == letra]
for i in range (0, len(letras)):
Array_Palabra[letras] = letra
return letras,Array_Palabra
def Letras_Jugadas(letra):
for i in range(0,len(Nuevas_Letras)):
Nuevas_Letras = re.findall(letra,Nuevas_Letras[i])
if Nuevas_Letras != []:
return 1
return Nuevas_Letras
def Eleccion():
Choice = input("Quiere Jugar?")
if Choice == 'si':
Choice = 1
elif Choice == 'no':
Choice = 0
return Choice
# Juego
Choice = Eleccion()
def Juego(Choice):
i = len(Array_Palabra)
while Choice == 1:
print(Definir_Palabra())
while i != 0 :
tiro = str.lower(input("adivine una letra"))
if Letras_Jugadas(tiro) != 1:
Nuevas_Letras = Nuevas_Letras + tiro
letras = Letras_En_Palabra(tiro)
if Letras_Jugadas(tiro) != []:
i = len(letras) - 1
print("Letras Utilizadas",Nuevas_Letras)
print(Letras_En_Palabra(tiro))
else:
Vidas = Vidas + 1
Dibujo += Ascii_Art[Vidas]
print("WROOOONG")
print(Dibujo)
print("Letras Utilizadas",Nuevas_Letras)
if Vidas ==9:
i = 0
else:
print("Letra ya Juagada",Nuevas_Letras)
Eleccion()
Juego(Choice)
The last line in your Juego should be Choice = Eleccion(), otherwise, you're not actually changing the value of Choice, so the loop continues indefinitely.
def Juego(Choice):
i = len(Array_Palabra)
while Choice == 1:
print(Definir_Palabra())
while i != 0 :
tiro = str.lower(input("adivine una letra"))
if Letras_Jugadas(tiro) != 1:
Nuevas_Letras = Nuevas_Letras + tiro
letras = Letras_En_Palabra(tiro)
if Letras_Jugadas(tiro) != []:
i = len(letras) - 1
print("Letras Utilizadas",Nuevas_Letras)
print(Letras_En_Palabra(tiro))
else:
Vidas = Vidas + 1
Dibujo += Ascii_Art[Vidas]
print("WROOOONG")
print(Dibujo)
print("Letras Utilizadas",Nuevas_Letras)
if Vidas ==9:
i = 0
else:
print("Letra ya Juagada",Nuevas_Letras)
"""
>>>> CHANGED <<<<
"""
Choice = Eleccion()
Otherwise, the way you had it simply calls the function Eleccion but doesn't return the value to the Choice variable in scope of Juego function.
Just need to indent :)
import random
# defining the main method
def main():
print "Hello Welcome to Python Hangman!!!"
random_word()
user_input()
# defining the dictionary_list to be used as the guessing word
def random_word():
dictionary_list= ["ant", "bath", "car", "dog", "electric", "foil", "grape", "heat", "ice", "jolly",
"knight", "lemon", "money", "need", "open", "park", "quote", "rough", "salty",
"teach", "under", "village", "warmth", "xavier", "yelp", "zipper"]
# making rand global so it can be used within deifferent functions
global rand
# randomly choosing a word from the dictionary_list and assign to the variable rand
rand = random.choice(dictionary_list)
return rand
# user guessing
def user_input():
guesses = 0
wrong_guess = 0
guess_left = 10
correct_letters_list = ""
wrong_letters_list =""
print "You have \033[1;34;15m 10 \033[0;30;15m guesses"
#getting the length of the word
length = len(rand)
print "The word is: " + "\033[1;35;15m" + str(length) + "\033[0;30;15m" + " characters long"
# loops around until the user has used all their 6 guesses are used up
while guesses < 10 :
guess = raw_input("Guess a Letter [a-z]: ").lower()
# stop case sensitivity
# if the letter guessed by the user is in rand string print correct else print wrong
if guess in rand:
correct_letters_list += guess
print "\033[1;32;15mcorrect"
print "correct letters:"
print "\033[0;30;15m" + correct_letters_list
print "incorrect letters:"
print "\033[0;30;15m" + wrong_letters_list
# each time the user guesses + 1 to the guesses tally
guesses +=1
guess_cal = guess_left - guesses
print "You have: " + str(guess_cal) + " guesses left"
# if rand contains guess more than once tell user
if rand.count(guess) > 1 :
print "The word contains the letter " + str(guess) + " " + "\033[1;36;15m" + str(rand.count(guess)) + "\033[0;30;15m" + " times"
else:
wrong_letters_list += guess
print "\033[1;31;15mwrong"
print "incorrect letters:"
print "\033[0;30;15m" + wrong_letters_list
print "correct letters:"
print "\033[0;30;15m" + correct_letters_list
guesses += 1
guess_cal = guess_left - guesses
print "You have: " + str(guess_cal) + " guesses left"
wrong_guess += 1
if wrong_guess == 1:
print "________ "
print "| | "
print "| "
print "| "
print "| "
print "| "
if wrong_guess == 2:
print "________ "
print "| | "
print "| 0 "
print "| "
print "| "
print "| "
if wrong_guess == 3:
print "________ "
print "| | "
print "| 0 "
print "| / "
print "| "
print "| "
if wrong_guess == 4:
print "________ "
print "| | "
print "| 0 "
print "| /| "
print "| "
print "| "
if wrong_guess == 5:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| "
print "| "
if wrong_guess == 6:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| / "
print "| "
if wrong_guess >= 7:
print "________ "
print "| | "
print "| 0 "
print "| /|\ "
print "| / \ "
print "| "
choice = raw_input("Do you wish to guess the word? (Y/N): ").lower()
if choice == 'y':
word = raw_input("Please enter the word: ").lower()
if word == rand:
print "Well Done you Guessed Correctly, the word was: " + rand
# if the user has guessed correctly + 10 to the guesses tally to end the game
guesses += 10
else:
print "Incorrect, Game Over!! The word was: " + rand
guesses += 10
# if user chooses n continue with the game
if choice == 'n':
continue
# if the user has used up all their 10 guesses print Game Over!!
if guesses == 10:
print "End of Game you ran out of guesses!!!"
if __name__ == "__main__":
main()

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