here what I need to do:
Your program must raise an exception if the user chooses any item not on the menu
presented. Along with raising an exception, write the code to handle this exception.
Ask the user for a value to convert.Your program must raise and exception, and handle the exception, if an input
errors occurs
Perform the conversion and write the original value, the original unit, the
converted value, and the converted unit to an output file named
conversions.txt.
Repeat steps a and b 10 times (in a loop).
heres my code:
#imports
import os
# global variables
mile_choice = 1
gallon_choice = 2
pound_choice = 3
inch_choice = 4
fah_choice = 5
quit_choice = 6
mainfile = open('conversions.txt', 'w')
# intro and global name variable
name = input ('what is your name? ')
print()
print('hello',name,', today we will be doing\
some standard to metric conversions.')
#define main function
def main():
choice = 0
while choice != quit_choice:
display_menu()
print()
choice = int(input('Please enter a number 1 - 6 : '))\
if choice == mile_choice:
print()
miletokm()
elif choice == gallon_choice:
print()
galtolit()
elif choice == pound_choice:
print()
poundstokg()
elif choice == inch_choice:
print()
inchtocm()
elif choice == fah_choice:
print()
fahtocel()
elif choice == quit_choice:
print()
print('Exiting the program.')
#define functions
def display_menu():
print()
print(' Menu ')
print()
print('Press 1 for Miles to Kilometers')
print()
print('Press 2 for Gallons to Liters')
print()
print('Press 3 for Pounds to Kilograms')
print()
print('Press 4 for Inches to Centimeters')
print()
print('Press 5 for Fahrenhiet to Celisus')
print()
print('To exit please enter 6 ')
def miletokm():
invalid_attempts = 0
#while loop for invalid input limited to 3
while invalid_attempts < 3 and invalid_attempts >= 0:
print()
mile = float(input('how many miles would you\
like to convert to kilometers? '))
mainfile.write(str(mile) + '\n')
# if statement to determine weather to proceed with conversation
# valid input = conversion
# invalid input = return with + 1 to invalid_attempt count
if mile >= 0 :
print()
mile_conv = mile * 1.6
print('that would be:', format(mile_conv, '.2f'), 'kilometers.')
print()
mainfile.write(str(mile_conv) + '\n')
return mile
else:
print()
print ('invalid input')
print()
invalid_attempts += 1
I left out the other conversion def. to help keep it shorter.
I am having problems with the exception part first and for most.
I have tried various things but I cant figure out how to write out the code correctly
I know how to define a value error for a number entered outside of the menu range
I don't understand how to write the units along with the data entered to the file.
The way I Have it now, it is not writing any information to mainfile.
I also feel like my code is very sloppy written. I have no idea because my professor refuses to help me.
I know that's alot to run through but i really have no where else to turn. I don't understand how I should structure the code and how to effectively accomplish what I need done.
what I have read covers the basis of this but I have no examples to look at other than very simple simple examples that deal with strictly one thing.
You could try something like... (from http://docs.python.org/2/tutorial/errors.html#exceptions)
>>> while True:
... try:
... x = int(raw_input("Please enter a number: "))
... break
... except ValueError:
... print "Oops! That was no valid number. Try again..."
...
You're on the right track. First thing that you need to do is to handle better the value for choice that the user gives you. Check what happens if they give you 9 or 'foo'.
Next, you should do the same for every value received in your functions that convert units. For that, you use try/except as #bitfish showed you (except that you use input instead of raw_input).
close the files you open (mainfile.close())
doing this elif choice == quit_choice: inside of this while choice != quit_choice makes no sense
use '\n' to skip lines (print('\n') is the same than print() two times
there are many ways to solve such a problem, white the experience you'll acquire you'll find more elegant ones, but this one is already ok.
Related
I'd like to create a function that add 2 to an integer as much as we want. It would look like that:
>>> n = 3
>>> add_two(n)
Would you like to add a two to n ? Yes
The new n is 5
Would you like to add a two to n ? Yes
the new n is 7
Would you like to add a two to n ? No
Can anyone help me please ? I don't how I can print the sentence without recalling the function.
The idea is to use a while loop within your function that continues to add two each time you tell it to. Otherwise, it exits.
Given that knowledge, I'd suggest trying it yourself first but I'll provide a solution below that you can compare yours against.
That solution could be as simple as:
while input("Would you like to add a two to n ?") == "Yes":
n += 2
print(f"the new n is {n}")
But, since I rarely miss an opportunity to improve on code, I'll provide a more sophisticated solution as well, with the following differences:
It prints the starting number before anything else;
It allows an arbitrary number to be added, defaulting to two if none provided;
The output text is slightly more human-friendly;
It requires a yes or no answer (actually anything starting with upper or lower-case y or n will do, everything else is ignored and the question is re-asked).
def add_two(number, delta = 2):
print(f"The initial number is {number}")
# Loop forever, relying on break to finish adding.
while True:
# Ensure responses are yes or no only (first letter, any case).
response = ""
while response not in ["y", "n"]:
response = input(f"Would you like to add {delta} to the number? ")[:1].lower()
# Finish up if 'no' selected.
if response == "n":
break
# Otherwise, add value, print it, and continue.
number += delta
print(f"The new number is {number}")
# Incredibly basic/deficient test harness :-)
add_two(2)
You can use looping in your add_two() function. So, your function can print the sentence without recalling the function.
The above answer describes in detail what to do and why, if you're looking for very simple beginner-type code that covers your requirements, try this:
n = 3
while True:
inp = input("Would you like to add 2 to n? Enter 'yes'/'no'. To exit, type 'end' ")
if inp == "yes":
n = n + 2
elif inp == "no":
None
elif inp == "end": # if the user wants to exit the loop
break
else:
print("Error in input") # simple input error handling
print("The new n is: ", n)
You can wrap it in a function. The function breaks once the yes condition is not met
def addd(n):
while n:
inp = input('would like to add 2 to n:' )
if inp.lower() == 'yes':
n = n + 2
print(f'The new n is {n}')
else:
return
addd(10)
I'm trying to take user-input but I need the input to be an integer, AND be between 1 and 9. I tried putting "in range(1,10)" in a few places in the code but it didn't work. I need the program to keep asking the user for the right input until they give the correct input. So far I've only been able to make sure their input is an integer with he following code. I will be taking input by using int(input("...")), rather than using input("...").
while True:
try:
ui1 = int(input("Player 1, Your move. Select your move. "))
break
except ValueError:
print("You have to choose a number between 1 and 9")
continue
Add a check before the break and move the error message to the end of the loop.
while True:
try:
ui1 = int(input("Player 1, Your move. Select your move. "))
if 1 <= ui1 <= 9:
break
except ValueError:
pass
print("You have to choose a number between 1 and 9")
Why not just check isdigit() and in range ?
while True:
ui1 = input("Player 1, Your move. Select your move. ")
if ui1.isdigit() and int(ui1) in range(1,10):
break
print("You have to choose a number between 1 and 9")
# Continue code out of the loop
# beJeb
# Stack overflow -
# https://stackoverflow.com/questions/51202856/how-to-check-user-input-for-multiple-conditions-within-same-loop-or-function-in
# Our main function, only used to grab input and call our other function(s).
def main():
while True:
try:
userVar = int(input("Player 1, Your move. Select your move: "))
break
except ValueError:
print("Incorrect input type, please enter an integer: ")
# We can assume that our input is an int if we get here, so check for range
checkRange = isGoodRange(userVar)
# Checking to make sure our input is in range and reprompt, or print.
if(checkRange != False):
print("Player 1 chooses to make the move: %d" %(userVar))
else:
print("Your input is not in the range of 1-9, please enter a correct var.")
main()
# This function will check if our number is within our range.
def isGoodRange(whatNum):
if(whatNum < 10) & (whatNum > 0):
return True
else: return False
# Protecting the main function
if __name__ == "__main__":
main()
Note: I tested a couple inputs so I believe this should be enough to help you understand the process, if not please comment, message, etc. Also, if this answer helps you, please select it as answered to help others.
Let the number be the input you are taking from the user.
while(1): #To ensure that input is continuous
number = int(input())
if number>=1 and number<=10 and number.isdigit():
break #if the input is valid, you can proceed with the number
else:
print("Enter a valid Number")
The number can be used for further operations.
I am trying to create an average solver which can take a tuple and average the numbers. I want to use the except hook to give an error message and then continue from the beginning of the while loop. 'continue' does not work.
import sys
z = 1
x = []
y = 1
i = 1
print('Welcome to the Average Solver.')
while z==1 :
def my_except_hook(exctype, value, traceback):
print('Please only use integers.')
continue
sys.excepthook = my_except_hook
print("Enter your set with commas between numbers.")
x=input()
i=len(x)
print('The number of numbers is:',i)
y=float(float(sum(x))/i)
print('Your average is', float(y))
print(' ')
print("Would you like to quit? Press 0 to quit, press 1 to continue.")
z=input()
print('Thank you for your time.')
As #PatrickHaugh noted, the keyword continue means nothing to my_except_hook. It is only relevant inside a while loop. I know this is what you are trying to do by having continue being called in the flow of a loop, but it's not really in the context of a loop, so it doesn't work.
Also, i is how many numbers you are, yet you set it as the length of the user input. However, this will include commas! If you want the real amount of numbers, set i = len (x.split (",")). This will find out how many numbers are in between the commas.
Never mind, I solved the problem. I just used a try-except clause...
z = 1
x = []
y = 1
i = 1
print('Welcome to the Average Solver.')
while z == 1:
try:
print("Enter your set with commas between numbers.")
x = input()
i = len(x)
y = float(float(sum(x)) / i)
print('Your average is', float(y))
print(' ')
print("Would you like to quit? Press 0 to quit, press 1 to continue.")
z = input()
except:
print('Please use integers.')
x = []
continue
print('Thank you for your time.')
So I'm getting into coding and I was doing an exercise from the Automate the Boring Stuff book. I figured out how to write the original function, but then I wanted to try to add a little more to it and see if I could fit it all in one function.
So in Python 3.6.2, this code works fine if I enter strings, positive integers, nothing, or entering "quit". However, if I enter 1 at any point between the others then try "quitting", it doesn't quit until I enter "quit" as many times as I previously entered 1. (like I have to cancel them out).
If I enter 0 or any int < 0, I get a different problem where if I then try to "quit" it prints 0, then "Enter a POSITIVE integer!".
Can't post pics since I just joined, but heres a link: https://imgur.com/a/n4nI7
I couldn't find anything about this specific issue on similar posts and I'm not too worried about this working the way it is, but I'm really curious about what exactly the computer is doing.
Can someone explain this to me?
def collatz():
number = input('Enter a positive integer: ')
try:
while number != 1:
number = int(number) #If value is not int in next lines, execpt.
if number <= 0:
print('I said to enter a POSITIVE integer!')
collatz()
if number == 1:
print('How about another number?')
collatz()
elif number % 2 == 0: #Checks if even number
number = number // 2
print(number)
else: #For odd numbers
number = number * 3 + 1
print(number)
print('Cool, huh? Try another, or type "quit" to exit.')
collatz()
except:
if str(number) == 'quit':
quit
else:
print('Enter an INTEGER!')
collatz()
collatz()
I've made a simple program where the users adds as many numbers as they would like then type 'exit' to stop it and print the total but sometimes it says the converting the string to int fails, and sometimes it does convert but then it has the wrong out put e.g I type 1 + 1 but it prints 1
def addition():
x = 0
y = 1
total = 0
while x < y:
total += int(input())
if input() == "exit":
x += 1
print(total)
addition()
I have tryed converting it to a float then to an int but still has inconsistency, I did start learning python today and am finding the syntax hard coming from c++ / c# / Java so please go easy on the errors
Maybe this is what you are looking for:
def addition():
total = 0
while True:
value = input()
if value == "exit":
break
else:
try:
total += int(value)
except:
print('Please enter in a valid integer')
print(total)
EDIT
There are two reasons why the code isn't working properly:
First, the reason why it is failing is because you are trying to cast the word "exit" as an integer.
Second, as user2357112 pointed out, there are two input calls. The second input call was unintentionally skipping every other number being entered in. All you needed to do was one input call and set the entered value into a variable.
You can break the while loop, without using x and y.
def addition():
total = 0
while True:
total += int(input())
if input() == "exit":
break
print(total)
addition()
These are a few ways you can improve your code:
Run the loop forever and break out of it only if the user enters "exit"
To know when the user entered "exit" check if the input has alphabets with isalpha()
Making the above changes:
def addition():
total = 0
while True:
user_input = input()
if user_input.strip().isalpha() and user_input.strip() == 'exit':
break
total += int(user_input)
print(total)
addition()
def safe_float(val):
''' always return a float '''
try:
return float(val)
except ValueError:
return 0.0
def getIntOrQuit():
resp = input("Enter a number or (q)uit:")
if resp == "Q":
return None
return safe_float(resp)
print( sum(iter(getIntOrQuit,None)) )
is another way to do what you want :P