While/if loop giving me trouble (beginner) - python

I have been trying to make my first "solo" python program, its a calculator where you pick what kind of formula you want it to calculate and then input the variables needed. I got issues with my while/for loop, when i run the program i get the correct menu: menu(), and then when I choose my next menu by inputting 1 i correctly get the "v_menu" however if I input 2, which should get me the "m_menu", I instead just get the v_menu like I would if I typed in a 1.
I hope my explanation made sense, im still very new to all of this. Appreciate any help I can get, been breaking my head over this for atleast one hour or so..
Cheers, and heres my code:
# coding=utf-8
#Menues
def menu():
print "Choose which topic you want in the list below by typing the corresponding number\n"
print "\t1) virksomhedsøkonomi\n \t2) matematik\n"
return raw_input("type the topic you want to pick\n >>")
def v_menu():
print "Choose which topic you want in the list below by typing the corresponding number"
print "\t1) afkastningsgrad\n \t2) overskudsgrad\n \t3) aktivernes omsætningshastighed\n \t4) Egenkapitalens forrentning\n \t5) return to main menu\n"
return raw_input("Type the topic you want to pick\n >>")
def m_menu():
print "Choose which topic you want in the list below by typing the corresponding number"
print "\t1) omregn Celsius til Fahrenheit\n \t2) omregn Fahrenheit til Celsius\n"
return raw_input("Type the topic you want to pick\n >>")
# - Mat -
#Celsius to Fahrenheit
def c_to_f():
c_temp = float(raw_input("Enter a temperatur in Celsius"))
#Calculates what the temperatur is in Fahrenheit
f_temp = c_temp * 9 / 5 + 32
#Prints the temperatur in Fahrenheit
print (str(c_temp) + " Celsius is equal to " + str(f_temp) + " Fahrenheit")
#Fahrenheit to Celsius
def f_to_c():
f_temp = float(raw_input("Enter a temperatur in Fahrenheit"))
#Calculates what the temperatur is in celsius
c_temp = (f_temp - 32) * (float(100) / 180)
#Prints the temperatur in celsius
print (str(f_temp) + " Fahrenheit is equal to " + str(c_temp) + " Celsius")
#Program
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == "1" or "1)":
v_menu()
elif choice == "2" or "2)":
m_menu()
if choice == "1":
c_to_f()
elif choice == "2":
f_to_c()
loop = 0

Your problem is in your if statements: if choice == "1" or "1)":
What you really need is: if choice == "1" or choice == "1)":
Everything after the or gets evaluated as another expression. You're saying "if choice is equal to one or if one exists."
"1)" evaluates to "true" in this instance, so you'll always hit that branch.

The problem is here;
if choice == "1" or "1)":
v_menu()
elif choice == "2" or "2)":
You have to write them like;
if choice == "1" or choice == "1)":
v_menu()
elif choice == "2" or choice == "2)":
Otherwise, all the time your if statement is True. And if first if statement is True, then your elif statement is not going to work. That's why you can't call v_menu()

Related

Error handling assistance requested in Python temperature converter

I'm a programming student working on a Python assignment to design an application that can convert Celsius to Fahrenheit or the other way around. My current code is working when it gets the expected values but running into some problems when the input doesn't meet the expected format:
temp = "" #set initial value for temp variable
celsfahr = "" #set initial value for Celsius or Fahrenheit
while temp != "exit":
temp, celsfahr = input("Enter a temperature in Celsius or Fahrenheit (examples: 32 Celsius, 500 Fahrenheit, -10 Celsius:) ").split()
if temp.isnumeric():
temp = int(temp)
if celsfahr == "Fahrenheit":
print(temp, "Fahrenheit equals", ((temp-32)*.556), "Celsius.")
else:
if celsfahr == "Celsius":
print(temp, "Celsius equals", ((temp*1.8)+32), "Fahrenheit.")
else:
if temp.lower() == "exit":
temp = temp.lower()
print("Goodbye.")
else:
print("I don't understand. Try again.\n")
A few problems I'm trying to solve:
How to add a check in the input/split so that the program doesn't crash if anything other than two space-separated values are entered
Related, how to accept "exit" as a value in the input field with the split in place
How to trigger the "I don't understand" error message earlier -- right now unexpected values other than Celsius or Fahrenheit return the program to the input but don't show an error
You are splitting too early and that's what giving you grief. Use the following approach instead. You'll check that your input, when split, contains 2 values exactly for the conversion or 1 or the exit message.
userInput = ""
while userInput != "exit":
userInput = input("Enter a temperature in Celsius or Fahrenheit (examples: 32 Celsius, 500 Fahrenheit, -10 Celsius:) ")
data = userInput.split();
if len(data)==2:
temp = data[0]
unit = data[1]
if temp.isnumeric():
temp = int(temp)
if unit.title() == "Fahrenheit":
print(temp, "Fahrenheit equals", ((temp-32)*5/9), "Celsius.")
elif unit.title() == "Celsius":
print(temp, "Celsius equals", ((temp*9/5)+32), "Fahrenheit.")
elif len(data)==1:
userInput = data[0].lower()
if userInput == "exit":
print("Goodbye.")
else:
print("I don't understand. Try again.\n")
I've also fixed a couple things for you. I used the actual fraction for the math (5/9) rather than the number you had in there. It's more accurate that way. I've also renamed your unit variable to just that, unit.

'while' loop not behaving as expected

Background:
I have made a program that takes a text input, applies encryption (a simple cipher) and saves the output to a list - if desired. Messages can also be decrypted.
The program is navigated through an options menu:
1. Encrypt a message
2. View encrypted messages
3. Decrypt a message
To allow all sections of the program to access the same list (variable) of saved messages, I have written it within a class. Within the class exist def's that call on this list.
Only the 'encrypt a message' bit has been written so far.
Problem:
The user decision flow is made with two Y/N choices.
However, the choices do not work - even if the user types in 'N' - my program thinks they have typed 'Y' in both cases.
def encrypt():
def save_cip():#This function allows the user to save the ciphered message to the ciphered_messages if they choose
choosing = True
while choosing:
save_choice = input("Would you like to save your Ciphered message? (Y/N)\n")
if save_choice == "Y" or "y":
print("You chose yes")
cct.ciphered_messages.append(' '.join(["Message", str(len(cct.ciphered_messages)), ":", cipher]))
choosing = False
elif save_choice == "N" or "n":
print("You chose no")
choosing = False
continue
else:
print("That was not a valid entry, please enter Y or N only")
continue
I think the problem lay within the scope, and that somehow the same variable is not being referenced when setting and reading Y or N. I have been going up and down the same code for about 3 hours and still nothing, declaring all variables in many different places with no luck, so any advice greatly appreciated.
Full executable code:
class cct:
print("Welcome to the CaeserCipher tool v1.0")
menu_state = "main" #This is used to record what state the program is in
unciphered_messages = [] #Decrypted messages are saved here
ciphered_messages = [] #Encrypted messages are saved here
def menu(): #This is the main menu interface
while cct.menu_state == "main": #This while
cct.menu_state = input("What would you like to do? \n 1: Encrypt a Message \n 2: View Encrypted Messages \n 3: Decrypt a message\n")
if cct.menu_state == "1":
cct.encrypt()
elif cct.menu_state == "2":
cct.view()
elif cct.menu_state == "3":
cct.decrypt()
elif cct.menu_state == "main":
print("\n\nWelcome back to the menu!\n\n")
else:
print("You did not enter a valid choice. Please enter a number between 1 and 3.\n")
cct.menu_state = "make_choice"
continue
def encrypt():
def save_cip():#This function allows the user to save the ciphered message to the ciphered_messages if they choose
choosing = True
while choosing:
save_choice = input("Would you like to save your Ciphered message? (Y/N)\n")
if save_choice == "Y" or "y":
print("You chose yes")
cct.ciphered_messages.append(' '.join(["Message", str(len(cct.ciphered_messages)), ":", cipher]))
choosing = False
elif save_choice == "N" or "n":
print("You chose no")
choosing = False
continue
else:
print("That was not a valid entry, please enter Y or N only")
continue
#This while loop continually takes messages, gives the option of saving, and asks if you want to cipher another
while cct.menu_state == "1":
text = input("Enter your message: ") #Enter the message you wish to cipher
cipher = '' #Create a string for the cipher
for char in text: #This for sub-loop will increment each character by 1. e.g. A -> B, T -> U, Z -> A
if not char.isalpha():
continue
char = char.upper()
code = ord(char) + 1
if code > ord('Z'):
code = ord('A')
cipher += chr(code)
print(' '.join(["Your ciphered message is:", cipher]))
save_cip()
print(cct.ciphered_messages)
#This sub-while loop is reponsible for checking if you want to cipher another message
#and making sure the user has made a valid choice
choosing_another = True
while choosing_another == True:
choice_variable = input(' '.join(["You have", str(len(cct.ciphered_messages)), "saved messages \n", "Would you like to Cipher another? (Y/N)\n"]))
if choice_variable == "Y" or "y":
print("You chose yes")
choosing_another = False
elif choice_variable == "N" or "n":
print("You chose no")
cct.menu_state = "main"
choosing_another = False
else:
choice_variable = input("That was not a valid entry, please enter Y or N only: \n")
continue
return
def view():
#TO BE CODED
return
def decrypt():
#TO BE CODED
return
cct.menu()
This is always true:
if save_choice == "Y" or "y":
bacause its interpreted as :
if (condition) or (condition):
the 1st condition is (save_choice == "Y")
the 2nd condition is just ( "y" ) which python interprets as 'True'
So the whole condition is always True.
U probably mean:
if save_choice == "Y" or save_choice == "y":
Or better :
if save_choice.lower() == "y":
Not a python programmer, but i don't think python allows a "implied" subject for the or operator
--> IF save_choice == "Y" OR save_choice == "y" :

Creating a "Flashcard" vocabulary program

I'd like to make a program in Python 3 that would be essentially vocabulary flashcards. I'd be able to list the terms, add a term, or display a random definition to try and accurately guess. Once guessed accurately, I would be given the option for another definition to guess. Alternatively, I'd like to just be able to display a random key:value pair, and to continue viewing pairs until I enter EXIT.
I have made most of the program using a dictionary, but am not sure how to go about with entering the proper command to enter the key for the definition displayed. If anyone could provide suggestions, I'd appreciate it! Also I got some sort of error message when entering this code in and had to do a bunch of indentations, not sure what I did wrong there.
import random
terms = {"1" : "def 1", #Dictionary of 'terms' and 'definitions'
"2" : "def 2",
"3" : "def 3"}
menu = None
while menu != "4":
print("""
DIGITAL FLASHCARDS!
1 - List Terms
2 - Add Term
3 - Guess Random Definition
4 - Exit
""")
menu = input("\t\t\tEnter Menu option: ")
if menu == "1": # List Terms
print("\n")
for term in terms:
print("\t\t\t", term)
input("\n\tPress 'Enter' to return to Main Menu.\n")
elif menu == "2": # Add Term
term = input("\n\tEnter the new term: ").upper()
if term not in terms:
definition = input("\tWhat is the definition? ")
terms[term] = definition
print("\n\t" + term, "has been added.")
else:
print("\n\tThat term already exists!")
input("\n\tPress 'Enter' to return to Main Menu.\n")
elif menu == "3": # Guess Random Definition. Once correct, choose new random definition
print("\n\t\t\tType 'Exit' to return to Menu\n")
choice = random.choice(list(terms.values()))
print("\n\t" + choice + "\n")
guess = None
while guess != "EXIT":
guess = str(input("\tWhat is the term? ")).upper()
display a random definition to try and accurately guess. Once guessed accurately, I would be given the option for another definition to guess
Use terms.items() to get key and value at the same time.
Define the process of generating a new definition question into a function generate_question() to avoid duplicity.
elif menu == "3": # Guess Random Definition. Once correct, choose new random definition
print("\n\t\t\tType 'Exit' to return to Menu\n")
def generate_question():
term, definition = random.choice(list(terms.items()))
print("\n\t" + definition + "\n")
return term
term = generate_question()
guess = None
while guess != "EXIT":
guess = input("\tWhat is the term? ").upper()
if guess == term:
print("Correct!")
if input("\tAnother definition?(y/n)").upper() in ["Y", "YES"]:
term = generate_question()
else:
break
Alternatively, I'd like to just be able to display a random key:value pair, and to continue viewing pairs until I enter EXIT.
elif menu == "4": # Random display a term-definition pair.
print("\n\t\t\tType 'Exit' to return to Menu\n")
exit = None
while exit != "EXIT":
term, definition = random.choice(list(terms.items()))
print(term + ":", definition)
exit = input("").upper() # Press enter to continue.
Remember to modify the beginning part:
while menu != "5":
print("""
DIGITAL FLASHCARDS!
1 - List Terms
2 - Add Term
3 - Guess Random Definition
4 - View term-definition pairs
5 - Exit
""")

(Basic?) File compiles fine, doesn't execute as intended

I'm running this on cygwin using atom as my editor. Python3.
Hi,
Basic Python question that really baffles me. I've looked around on SO and found a lot of questions regarding similiar issues, but can't find one that covers the issue I'm facing.
Before I go into details; this is an assignment that I'm working on so if you don't want to spill "all the beans", then just give me some sort of guidance.
I've been tasked with splitting a chat-bot into two files, one that handles the main() function and one that handles all the possible functions that the input-choices from main() uses.
For some reason both files compile fine, but when I call main.py
(either by >python main.py // // // // or by > ./main.py)
I get no prompt at all. Neither do I get a prompt while trying the same with marvin.py.
Both files are in the same directory.
This is main():
#!/usr/bin/env python3
import marvin
def main():
"""
This is the main method, I call it main by convention.
Its an eternal loop, until q is pressed.
It should check the choice done by the user and call a appropriate
function.
"""
while True:
menu()
choice = input("--> ")
if choice == "q":
print("Bye, bye - and welcome back anytime!")
return
elif choice == "1":
myNameIs()
elif choice == "2":
yearsToSec()
elif choice == "3":
weightOnMoon()
elif choice == "4":
minsToHours()
elif choice == "5":
celToFahr()
elif choice == "6":
multiplyWord()
elif choice == "7":
randNumber()
elif choice == "8":
sumAndAverage()
elif choice == "9":
gradeFromPoints()
elif choice == "10":
areaFromRadius()
elif choice == "11":
calcHypotenuse()
elif choice == "12":
checkNumber()
else:
print("That is not a valid choice. You can only choose from the menu.")
input("\nPress enter to continue...")
if __name__ == "__main__":
main()
As you can see I do import marvin after the environment-variables have been loaded.
There are no indentation errors or anything else when compiling either files (as mentioned above).
Disclaimer: I don't think you need to read marvin, tbh...
And this is marvin.py:
#!/usr/bin/env python3
from random import randint
import math
def meImage():
"""
Store my ascii image in a separat variabel as a raw string
"""
return r"""
_______
_/ \_
/ | | \
/ |__ __| \
|__/((o| |o))\__|
| | | |
|\ |_| /|
| \ / |
\| / ___ \ |/
\ | / _ \ | /
\_________/
_|_____|_
____|_________|____
/ \
"""
def menu():
"""
Display the menu with the options that Marvin can do.
"""
print(chr(27) + "[2J" + chr(27) + "[;H")
print(meImage())
print("Welcome.\nMy name is Ragnar.\nWhat can I do for you?\n")
print("1) Present yourself to Ragnar.")
print("2) Have Ragnar calculate your minimum age (in seconds).")
print("3) Have Ragnar calculate weight on the moon.")
print("4) Try Ragnar's abilities by having him calculate minutes to hour(s).")
print("5) Have Ragnar calculate Fahrenheit from Celcius.")
print("6) See if Ragnar can multiply a word of your liking by a factor of your choice.")
print("7) Have Ragnar print 10 numbers within a range of your choice.")
print("8) Keep entering numbers and have Ragnar print their sum and average.")
print("9) Let Ragnar calculate your grade by entering your score!.")
print("10) Let Ragnar calculate the area of a circle with the radius of your choice.")
print("11) Let Ragnar calculate the hypotenuse of a triangle with the sides of your choice.")
print("12) Have Ragnar compare a given number to your previous number.")
print("q) Quit.")
def myNameIs():
"""
Read the users name and say hello to Marvin.
"""
name = input("What is your name? ")
print("\nMarvin says:\n")
print("Hello %s - your awesomeness!" % name)
print("What can I do you for?!")
def yearsToSec():
"""
Calculate your age (years) to seconds
"""
years = input("How many years are you?\n")
seconds = int(years) * (365 * 24 * 60 * 60)
print(str(years) + " would give you " + str(seconds) + " seconds.")
return
def weightOnMoon():
"""
Calculate your weight on the moon
"""
weight = input("What is your weight (in kiloes)?\n")
moonGrav = float(weight) * .2
print(str(weight) + " kiloes would weigh be the same as " + str(moonGrav) + " kiloes on the moon.")
def minsToHours():
"""
Calculate hours from minutes
"""
minutes = input("How many minutes would you want to converted to hour(s)?\n")
hours = float(format(float(minutes) / 60, '.2f'))
print(str(minutes) + " hours is " + str(hours) + " hours")
def celToFahr():
"""
Calculate celcius to Fahrenheit
"""
cel = input("Please insert Celcius to be calculated to Fahrenheit.\n")
fah = float(format(float(cel) * 1.8 + 32, '.2f'))
print(str(cel) + " is " + str(fah) + " in Fahrenheit units.")
def multiplyWord():
"""
Multiply word n-times
"""
word = input("Please enter the word.\n")
factor = input("And please give me the product to multiply it by!")
word *= int(factor)
print("The word is:\n" + str(word))
def randNumber():
"""
Adds 10 random numbers (depending on user range)
to a string.
"""
rangeMin = input("What is the lower number in your range?\n")
rangeMax = input("What is the higher number in your range?\n")
sequence = ""
for num in range(0, 10):
sequence += str(randint(int(rangeMin), int(rangeMax))) + ", "
num = num
print("The random sequence is:\n" + sequence[:-2])
def sumAndAverage():
"""
Adds numbers to the sum and calculate the average value of the input(s)
"""
summa = 0
count = 0
temp = input("Please enter a number to be added to the sum. \nEnter 'q' if you wish to finish!\n")
while True:
if temp == "q":
print("The sum of your numbers are: " + str(summa) + "\nAnd the average is: " + str(summa/count))
return
else:
try:
summa += int(temp)
count += 1
temp = input("Please enter a number to be added to the sum. \nEnter 'q' if you wish to finish!\n")
except ValueError:
print("That's not an int! \nPlease try again!")
def gradeFromPoints():
"""
Shows the user's grade based on his / her points
"""
points = input("How many points did you score?\n")
if(float(points) >= 1 and float(points) <= 100):
points = float(points) / 100
if float(points) >= 0.9:
print("You got an A!")
elif float(points) >= 0.8 and float(points) < 0.9:
print("You got a B!")
elif float(points) >= 0.7 and float(points) < 0.8:
print("You got a C!")
elif float(points) >= 0.6 and float(points) < 0.7:
print("You got a D!")
else:
print("You failed the class")
def areaFromRadius():
"""
Calculates a circles area based on it's radius
"""
radius = input("What is the circle's radius?\n")
area = (float(radius) * float(radius)) * 3.1416
print("The area of the circle is: " + str(format(area, '.2f')))
print("This was calculated with this formula: (radius^2) * 3.1416")
def calcHypotenuse():
"""
Calculates a triangle's hypotenuse based on it's sides
"""
side1 = input("How long is the first side?\n")
side2 = input("How long is the second side?\n")
hypotenuse = math.sqrt((float(side1) * float(side1)) + (float(side2) * float(side2)))
print("The hypotenuse is: " + str(hypotenuse))
def compareNumbers(a, b):
"""
Compares two numbers
"""
if (a > b):
print("Your previous number was larger!")
return a
elif (a < b):
print("Your new number was larger!")
return b
else:
print("They were equal!")
return a
def validateInt(a):
"""
Validates that an input is an integer
"""
if a == 'q':
return a
else:
flag = False
while (flag == False):
try:
a = int(a)
flag = True
except ValueError:
print("That's not an int! \nPlease try again!")
a = input("Try again!\n")
return a
def checkNumber(prev="first"):
"""
Checks the number
"""
print("\n=================\n")
if prev == "first":
prev = validateInt(input("Please input a number. Press 'q' if you wish to end\n"))
print("\n=================\n")
new = validateInt(input("Please input a number. Press 'q' if you wish to end\n"))
if new == 'q' or prev == 'q':
print("You have exited the loop\n")
return
else:
compareNumbers(int(prev), int(new))
checkNumber(str(new))
else:
new = validateInt(input("Please input a number. Press 'q' if you wish to end\n"))
if new == 'q':
print("You have exited the loop!\n")
return
else:
compareNumbers(int(prev), int(new))
checkNumber(str(new))
FULL DISCLAIMER: I'm sure there are bunches of improvments I can do,
but I'm only interested in understanding why the files won't execute
even though they compile fine...
if __name__ == "__main__":
main()
should not be indented.
In your current code, the main() method is run in the else block, but you never get there because the program won't start because you just define the main() method but never execute it.
Unindent it and it will be executed as it won't be in a function definition anymore.
The functions defined in marvin.py are not globals in main.py; they are members of the marvin module object. So, this:
elif choice == "1": myNameIs()
should be changed to this:
elif choice == "1": marvin.myNameIs()
The same goes for the rest of the places where main.py is using functions from marvin.py.

Python Calculator Divide by Zero/Sqrting a Neg. Int. crashing program

Alright, I'm doing this for a project and whenever I attempt to have it divide by zero or square root a negative number that program closes out. I've attempted to find something I can insert into the code to make it display a message and then prompt for the value again, but everything that I've tried inserting causes the program to close out instantly when I start it up.
Here's the calculator without anything inserted to fix the crashes.
import math
def convertString(str):
try:
returnValue = int(str)
except ValueError:
returnValue = float(str)
return returnValue
def addition(a, B):
return convertString(a) + convertString(B)
def subtraction(a, B):
return convertString(a) - convertString(B)
def multiplication(a, B):
return convertString(a) * convertString(B)
def division(a, B):
return convertString(a) / convertString(B)
def sqrt(a):
return math.sqrt(convertString(a))
keepProgramRunning = True
print "Welcome to [Removed]'s 2011 4-H Project! This is a simple calculator coded in Python, which is a high-level programming language. Java, C, C++, and Perl are other high-level programming languages that you may have heard of."
while keepProgramRunning:
print ""
print "Please choose what you would like to do:"
print ""
print "1) Addition"
print "2) Subtraction"
print "3) Multiplication"
print "4) Division"
print "5) Square Root"
print "6) Quit Program"
choice = raw_input()
if choice == "1":
numberA = raw_input("Enter your first addend: ")
numberB = raw_input("Enter your second addend: ")
print "The sum of those numbers is:"
print addition(numberA, numberB)
elif choice == "2":
numberA = raw_input("Enter your first term: ")
numberB = raw_input("Enter your second term: ")
print "The difference of those numbers is:"
print subtraction(numberA, numberB)
elif choice == "3":
numberA = raw_input("Enter your first factor: ")
numberB = raw_input("Enter your second factor: ")
print "The product of those numbers is:"
print multiplication(numberA, numberB)
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
print division(numberA, numberB)
elif choice == "5":
numberA = raw_input("Enter the number you wish to find the square root of: ")
print "Your result is:"
print sqrt(numberA)
elif choice == "6":
print "Goodbye! Thank you for your time spent both judging my project and those of everyone else! Have a nice day! (。◕‿◕。)"
keepProgramRunning = False
else:
print "Please choose a valid option."
print "\n"
I'm not real sure what to insert and where to solve the crashes, but I think the problem lies with my placement.
I've been attempting to insert something like this:
except ValueError:
print "You cannot divide by zero. Please choose another divisor."
numberB = raw_input("Enter your divisor: ")
Would that work? Where would I insert it? If it wouldn't work, what would and where would it go?
I've been attempting to put it after
numberB = raw_input("Enter your divisor: ")
So that section would read
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
except ValueError:
print "You cannot divide by zero. Please choose another divisor."
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
print division(numberA, numberB)
But as I said, the program will close as soon as it opens when I do try that. Also, I know that if they inputted 0 again the program would crash. Is there any way to make it return to the line that it's under?
Also, for closing the program, the message it is supposed to display can't be read as the program is closing immediately after it's displayed, or the commands are being executed at the same time. Either way, the message can't be read. Is there any way to make the message appear in a separate dialog window that will cause the program to close when the window is closed? Or at least a way to make it delay before closing?
Please correct me if I got any terminology wrong. I'm still somewhat new to this.
And, as always, (constructive) feedback for any part of the program is always appreciated.
The problem is that you are trying to catch an exception before it is thrown. Instead, try this:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
while float(numberB) == 0:
print "You cannot divide by zero. Please choose another divisor."
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
print division(numberA, numberB)
Here's your answer without exception handling.
Essentially you just make this questionable input at the beginning of an infinite loop, but break out when you find that the input is all good.
For your square root:
elif choice == "5":
while True:
numberA = raw_input("Enter the number you wish to find the square root of: ")
if float(numberA) >= 0:
break
print "Cannot take the square root of a negative number."
print "Your result is:", sqrt(numberA)
and for division:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
while True:
numberB = raw_input("Enter your divisor: ")
if numberB != "0":
break
print "You cannot divide by zero. Please choose another divisor."
print "The quotient of those numbers is:", division(numberA, numberB)
And to make your program stall before it closes:
elif choice == "6":
print "Goodbye! Thank you for your time spent both judging my project and those of everyone else! Have a nice day! (。◕‿◕。)"
raw_input('')
keepProgramRunning = False
Cheers!
You should use exceptions, like you're already doing in convertString.
try:
result = division(numberA, numberB)
print "The quotient of those numbers is:"
print result
except ZeroDivisionError:
print "You cannot divide by zero. Please choose another divisor."
Your format of the try:...except: statement is wrong. Try this:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
try:
print division(numberA, numberB)
except ZeroDivisionError:
print "You cannot divide by zero. Please choose another divisor."
This does not answer your coding question, but I think it is worth to comment.
sqrt: The square root of a negative number is an imaginary number. Python supports complex numbers with complex(real_part, imaginary_part).
so your sqrt calculation could be written as:
elif choice == "5":
numberA = raw_input("Enter the number you wish to find the square root of: ")
numberA = float(numberA)
if numberA < 0:
sqrt_numberA = complex(0, sqrt(abs(numberA)))
else:
sqrt_numberA = sqrt(numberA)
print "Your result is:", sqrt_numberA
division: A division by 0 is infinite. Python indicates infinite with 'inf'. In fact, it returns 'inf' with numbers higher than 1E309:
>>> 1E309
inf
and the division of two of these numbers produces 'nan'
>>> 1E309/1E309
nan
so that you could write:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
try:
div = division(numberA, numberB)
except ZeroDivisionError:
div = 'inf'
print "The quotient of those numbers is:", div
this code should be additionally extended to return -inf, when numberA is negative, and to take into account situations such as 0/0

Categories