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.
Related
I have this, what do I need to implement to make it ask me which conversion I want?
def user_choice(Celsius to Fahrenheit, Fahrenheit to Celsius):
return input ('Which conversion do you want to do? ')
I've tried a lot of combinations but can't seem to fit it right
I need more info about the vars. But you first need to name to var,
to make it usable, and put something like:
Var1 = input('Which conversion do you want to do? (Press A for Cº or B for Fº)')
then some conditional like:
if Var1 == "A":
Then you do you calculations and when you finish, you do it again but with
elif Var1 == "B":
And you do your results
Once you have them to print you do:
Var2 = print(Put the variable where the results are without the "")
then you return it like this
return Var2
So you want to ask if the user wants to convert from Celsius to Fahrenheit or Fahrenheit to Celsius. This can be done by defining a variable which stores this decision. You could store it as a number, 1 or 2. 1 could be Celsius to Fahrenheit and 2 could be Fahrenheit to Celsius. This can be done with the following code.
user_choice = input("Which conversion? Celsius to Fahrenheit = 1, Fahrenheit to Celsius = 2\n")
if user_choice == 1: # Celsius to Fahrenheit
# conversion code
elif user_choice == 2: # Fahrenheit to Celsius
# conversion code
For the conversions, you would want to take an input of what the user wants converted and then use a method for converting. This might look like this.
user_choice = input("Which conversion? Celsius to Fahrenheit = 1, Fahrenheit to Celsius = 2\n")
if user_choice == 1: # Celsius to Fahrenheit
user_input = input("What temperature would you like converted to Fahrenheit?\n")
converted_temp = (user_input * 1.8) + 32
print(f"Your converted temperature is {converted_temp}")
elif user_choice == 2: # Fahrenheit to Celsius
user_input = input("What temperature would you like converted to Celsius?\n")
converted_temp = (user_input - 32) * 0.5556
print(f"Your converted temperature is {converted_temp}")
Here, I just used the conversion formula google gave me.
I hope this helps you!
EDIT:
Here is the fixed code.
user_choice = int(input("Which conversion? Celsius to Fahrenheit = 1, Fahrenheit to Celsius = 2\n"))
if user_choice == 1: # Celsius to Fahrenheit
user_input = int(input("What temperature would you like converted to Fahrenheit?\n"))
converted_temp = (user_input * 1.8) + 32
print(f"Your converted temperature is {converted_temp}")
elif user_choice == 2: # Fahrenheit to Celsius
user_input = int(input("What temperature would you like converted to Celsius?\n"))
converted_temp = (user_input - 32) * 0.5556
print(f"Your converted temperature is {converted_temp}")
else:
print("That is not a valid input.")
I have spent a lot of time creating this encryption program that is specific to an assignment. The encryption works perfectly, i thought i would be able to copy the code and do the opposite to decrypt the message, however i receive the error:
letter = encryptionCharacters[temp_k]
"TypeError: String indices must be integers"
Not sure if anyone can fix this issue to be able to decrypt a message, but hopefully someone can give me some help.
Steps to use the program:
Select option 1 by entering that number from the menu.
Enter 854417 as the number
Then press 2 and choose a message to encrypt / decrypt.
from itertools import cycle
listOfDigits = []
listOfIllegalCharacters = []
encryptionCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz .'
encryptedMessageLettersPosition = []
decryptedMessageLettersPosition =[]
encryptedMessageList = []
def main(): #This Function is the base of the main menu
print()
print("********* Welcome to the Encryption Program *********")
print()
while True: #Start of while loop to get the users choice.
try: #Start of try method.
choice = int(input("""
1: Set Person Number
2. Encrypt a Message
3. Decrypt a Message
4. Quit
Please Choose an Option (1 - 4): """)) #Interactive menu itself taking in the users option as an integer.
except ValueError: #End of try method, in order to catch the possible value error of entering a string instead of an integer.
print("!!!!!!ERROR!!!!!!")
print()
print("ERROR: Choice was not valid!")
print("Try Again")
print()
print("!!!!!!ERROR!!!!!!")
main() #Call to menu method (a.k.a restart).
if choice == 1:
personNumberInput() #Call to personNumberInput method, which allows the user to enter their personal ID number for the encryption.
elif choice == 2:
if len(listOfDigits) == 0:
print()
print("!!!!!!ERROR!!!!!!")
print()
print("You have not set a Person Number")
print("Please Select Option 1 and set a Person Number to begin Encryption / Decryption")
print()
print("!!!!!!ERROR!!!!!!")
else:
messageEncrypt()
elif choice == 3:
if len(listOfDigits) == 0:
print()
print("!!!!!!ERROR!!!!!!")
print()
print("You have not set a Person Number")
print("Please Select Option 1 and set a Person Number to begin Encryption / Decryption")
print()
print("!!!!!!ERROR!!!!!!")
else:
messageDecrypt()
elif choice == 4:
menuQuit()
else:
print()
print("!!!!!!ERROR!!!!!!") #If none of the options are chosen, restart and provide a suitable error message.
print()
print("You must only select 1, 2, 3 or 4.")
print("Please Try Again")
print()
print("!!!!!!ERROR!!!!!!")
main()
def menuQuit(): #This function is the 4th option on the menu.
print()
userOption = input("Are you sure you want to Quit / Exit the Program? (Y/N): ") #Taking the users input to get their decision.
if userOption == "y":
exit()
elif userOption == "Y":
exit() #Exit the program if the user confirms their choice with "y" or "Y".
else:
print()
print("You have been returned to the Main Menu")
main() #Returning the user to the menu for any other option including "n" or "N".
def personNumberInput():
while True:
try:
print()
personNumber = int(input("Please enter your Person Number: ")) #Checking the input from the user.
except ValueError: #Catching the value error of unexpected value (non integer).
print()
print("ERROR: Person Number contained a non integer, Try Again")
continue
else:
personNumberInt = len(str(abs(personNumber))) #Getting the length of the string as well as the absolute value of each digit entered.
break
while True:
if (personNumberInt) != 6: #If the length of the number entered is not 6, try again.
print()
print("ERROR: Person Number length not equal to 6, Try Again")
return personNumberInput()
else:
print()
print ("The Person Number you have entered is:", personNumber)
print ("Ready to Encrypt / Decrypt a Message")
personNumberDigits = [int(x) for x in str(personNumber)]
listOfDigits.extend(personNumberDigits)
break
def messageEncrypt():
print()
message = input("Please Enter a Message to Encrypt: ")
messageLetters = []
messageLettersPosition = []
for char in message:
messageLetters += char
for i in messageLetters:
position = encryptionCharacters.find(i)
position = position + 1
messageLettersPosition.append(position)
digits = messageLettersPosition
values = cycle(listOfDigits)
for j, (digit, value) in enumerate(zip(digits, values)):
if j % 2 == 0:
val = digit - value-1
encryptedMessageLettersPosition.append(val)
elif j % 3 == 1:
val = digit - value*3-1
encryptedMessageLettersPosition.append(val)
else:
val = digit + value-1
encryptedMessageLettersPosition.append(val)
for k in encryptedMessageLettersPosition:
temp_k = k % len(encryptionCharacters)
letter = encryptionCharacters[temp_k]
encryptedMessageList.append(letter)
print()
print ("Your message has been Encrypted!")
print ("Encrypted Message Output:",(''.join(encryptedMessageList)))
encryptedMessageLettersPosition.clear()
encryptedMessageList.clear()
def messageDecrypt():
print()
message = input("Please Enter a Message to Decrypt: ")
messageLetters = []
messageLettersPosition = []
for char in message:
messageLetters += char
for i in messageLetters:
position = encryptionCharacters.find(i)
position = position + 1
messageLettersPosition.append(position)
digits = messageLettersPosition
values = cycle(listOfDigits)
for j, (digit, value) in enumerate(zip(digits, values)):
if j % 2 == 0:
val = digit + value-1
encryptedMessageLettersPosition.append(val)
elif j % 3 == 1:
val = digit + value/3-1
encryptedMessageLettersPosition.append(val)
else:
val = digit - value-1
encryptedMessageLettersPosition.append(val)
for k in encryptedMessageLettersPosition:
temp_k = k % len(encryptionCharacters)
letter = encryptionCharacters[temp_k]
encryptedMessageList.append(letter)
main()
Try making temp_k an integer using int()
temp_k = int( k % len(encryptionCharacters) )
letter = encryptionCharacters[temp_k]
Some of the values in encryptedMessageLettersPosition are floats, not integers.
Therefore temp_k = k % len(encryptionCharacters) sometimes returns a float value, and you cannot use a float as a string index.
I'm trying to complete my assignment and have been struggling. The idea is that you select report type, A or T. From there you enter keep entering integers until you quit. Once you quit, it should print out the total of integers added together for report 'T'; or for report 'A', it should print the total, plus a list of integers entered.
The problem I'm encountering at the moment is from report 'T', once I'm entering integers nothing will make it error or quit. It just keeps constantly asking me to enter another integer. Then from report 'A', every integer I enter it just comes up with 'invalid input'. I'm sure there are probably plenty more issues with my code but can't get past these ones at the moment. Any pointers would really be appreciated. Thanks
def adding_report(report):
total = 0
items = []
while True:
user_number = input("Enter an ingteger to add to the total or \"Q\" to quit: ")
if report.upper == "A":
if user_number.isdigit():
total += int(user_number)
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
elif report.upper() == "T":
if user_number.isdigit():
total += int(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\": ")
while True:
if report.upper() in "A T":
adding_report(report)
else:
print ("Invalid input")
report = input("Please select report type \"A\" or \"T\": ")
The in operator needs a collection of possible values. Use
if report.upper() in ("A", "T")
or (closer to what you have)
if report.upper() in "A T".split()
Your first problem is in this line:
if report.upper == "A":
This always evaluates to False, because report.upper is a function object, not a value. You need
if report.upper() == "A":
to return the value. You would also do well to rename the input variable and replace its value to the internal one you want:
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\": ")
report = report.upper()
This saves you the mess and time of calling upper every time you access that letter.
Please look through your code for repeated items and typos; you'll save headaches in the long run -- I know from personal experience.
Try this
def adding_report(report):
total = 0
items = []
while True:
user_number = input("Enter an integer to add to the total or \"Q\" to quit: ")
#You used "report.upper" instead of "report.upper()"
if report.upper() == "A":
if user_number.isdigit():
total += int(user_number)
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
elif report.upper() == "T":
if user_number.isdigit():
total += int(user_number)
#You forgot ot add this : "items.append(user_number)"
items.append(user_number)
elif user_number.upper() == "Q":
break
else:
print("Invalid input\n")
break
#Add this for loop termination: "or 0 to quit: "
report = input("Report types include All Items (\"A\") or Total Only (\"T\")\nPlease select report type \"A\" or \"T\" Or 0 to quit: ")
while True:
#it should be this ""if report.upper() in "A" or "T":"" not this ""if report.upper() in "A T":""
if report.upper() in "A" or "T":
adding_report(report)
#The condition below terminates the program
elif report == '0':
break
else:
print("Invalid input")
report = input("Please select report type \"A\" or \"T\": ")
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()
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