Where should I insert my try, except, finally to capture errors?
This is a program to add/reject element in the list
myUniqueList = []
myLeftovers = []
print("Initial elements of UniqueList:", myUniqueList)
print("Initial elements of LeftOvers:", myLeftovers)
myUniqueList.append(2)
myUniqueList.append(10)
myUniqueList.append(25)
myUniqueList.append(61)
print("Current elements in the list:", myUniqueList)
Function to add element to UniqueList
def AddToList(x):
if x not in myUniqueList:
myUniqueList.append(x)
print("Added Value:")
print(myUniqueList)
return True
else:
AddToLeftOver(x)
return False
Function to add element to LeftOver
def AddToLeftOver(x):
myLeftovers.append(x)
print("LeftOver value:")
print(myLeftovers)
Add element to list
x = int(input("Enter value:"))
print(AddToList(x))
I managed to add try, except without problem, like this:
def AddToList(x):
if x not in myUniqueList:
myUniqueList.append(x)
print("Added Value:" + str(x))
return True
else:
AddToLeftOver(x)
return False
def AddToLeftOver(x):
myLeftovers.append(x)
print("LeftOver value:" + str(x))
myUniqueList = []
myLeftovers = []
print("Initial elements of UniqueList:", myUniqueList)
print("Initial elements of LeftOvers:", myLeftovers)
myUniqueList.append(2)
myUniqueList.append(10)
myUniqueList.append(25)
myUniqueList.append(61)
print("Current elements in the list:", myUniqueList)
x = int(input("Enter value:"))
try:
AddToList(x)
except:
AddToLeftOver(x)
print("myUniqueList: " + str(myUniqueList))
print("myLeftovers: " + str(myLeftovers))
I couldn't add finally because there are only 2 options True or False.
You have to look, at which places exceptions can occure.
In add_to_list and add_to_leftover the only methods used are in and append. Both don't raise exception, so no need for try-except:
def add_to_list(unique_list, leftover, element):
if element not in unique_list:
unique_list.append(element)
print("Added Value:")
print(unique_list)
return True
else:
add_to_leftover(leftover, element)
return False
def add_to_leftover(leftover, element):
leftover.append(element)
print("LeftOver value:")
print(leftover)
In the main program, you ask for user input and convert it to int:
x = int(input("Enter value:"))
At this place, the input is possibly not convertible to int, so a exception is raised:
unique_list = [2, 10, 25, 61]
leftover = []
try:
x = int(input("Enter value:"))
except ValueError:
do_what_ever_is_need_in_this_case()
finally:
print(add_to_list(unique_list, leftover, x)
Related
I have the following code:
def five_numbers():
my_list = []
for i in range(1, 6):
user_nr = check_if_number_is_1_to_25(input("Number " + str(i) + ": "))
my_list.append(user_nr)
return my_list
def check_if_number_is_1_to_25(number):
if number.isalpha():
print("Enter a number between 1 and 25.")
# Here I want to go back to five_numbers() and the number x (for example number 4)
Now I want to check if the input contains any letters. If it has, I want to print a message and then I want to go back to the number that the user was on earlier. I've tried to return five_numbers() but then the user will start from the beginning.
I appreciate all the help.
Add a keyword arg for num and default it to None:
def five_numbers(num=None):
my_list = []
if num is None:
for i in range(1, 6):
user_nr = check_if_number_is_1_to_25(input("Number " + str(i) + ": "))
my_list.append(user_nr)
else:
# do other stuff with num (4) here...
return my_list
def check_if_number_is_1_to_25(number):
if number.isalpha():
print("Enter a number between 1 and 25.")
five_numbers(4)
You can use a while loop to keep asking the user for a valid input until the user enters one. You should also make the check function raise an exception instead so the caller can catch the exception and retry the input:
def five_numbers():
my_list = []
for i in range(1, 6):
while True:
user_nr = input("Number " + str(i) + ": ")
try:
check_if_number_is_1_to_25(user_nr)
break
except ValueError as e:
print(str(e))
my_list.append(user_nr)
return my_list
def check_if_number_is_1_to_25(number):
if number.isalpha():
raise ValueError('Enter a number between 1 and 25.')
Don't use a for loop, use a while loop with the list length as its condition. Make the check function return a boolean and use it to decide whether to append to the list.
def five_numbers():
my_list = []
while len(my_list) < 5:
user_nr = input("Number {}: ".format(len(my_list)+1))
if check_if_number_is_1_to_25(user_nr):
my_list.append(user_nr)
else:
print("Enter a number between 1 and 25.")
return my_list
def check_if_number_is_1_to_25(number):
return number.isdigit() and (1 <= float(number) <= 25)
I have to get userinputs of ints and store them in a array, and print the max number in the list. But I had to create my own max function. Im not sure what steps to take to implement it into my code.
def getInt(prompt):
n = int
done = False
while not done:
try:
n = int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
if n == 0:
done = True
return n
def maxNum(l):
maxi = [0]
for num in l:
if maxi > num:
maxi = num
return maxi
def result():
print("The maxium value is: " + maxNum(i))
def main():
num = []
i = 0
done = False
while not done:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
done = True
results = maxNum(i)
The below code does exactly what you want.
def getInt(prompt):
try:
n = int(input(prompt))
return n
except ValueError:
print("I was expecting a number, please try again...")
getInt()
def maxNum(lst):
if not lst: # if list is empty
return None
max_elem = lst[0]
for x in lst:
if x > max_elem:
max_elem = x
return max_elem
def main():
nums = []
while True:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
break
nums.append(num)
result = maxNum(nums)
print("The maxium value is: " + str(result))
main()
python support built-in max function
max([1,2,3]) # return 3
and Your code is totally wrong.
if you want to input array of integers, getInt may be like this.
def getInt():
array = []
while True:
x = int(input('message'))
if x == 0: break
array.append(x)
return array
and main code will be
array = getInt()
max_value = max(array)
print (max_value)
if you want your own max function, it can be
def max_func(array):
max_val = array[0]
for val in array:
if val > max_val: max_val = val
return max_val
Here is a fixed version of your maxNum function:
def maxNum(l):
if not l:
return None # or return whatever you want if user did not input anything
maxi = l[0] # it expects 'l' to be an array!
for num in l[1:]:
if maxi > num:
maxi = num
return maxi
Let's also fix your getInt function:
def getInt(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
Finally, your "main" function needs the following fix:
def main():
num = []
n = 1
while n != 0:
n = getInt("Please enter an integer < 0 to finish >: ") # store user input into n - do not overwrite num!
num.append(n) # append each user value to the list num
results = maxNum(num) # pass the entire *list* to maxNum
I have some code here meant to allow me to keep creating floats until I input 0 to have it stop (the 0 is then deleted). These floats are supposed to be entered into a list. The issue I'm having is that each time the while loop is run, the float_list is overwritten.
again = True
float_count = 1
while (again):
float_list = [float(input("Float%d: " % i))for i in range(float_count, float_count + 1)]
last_float = float_list[-1]
if (last_float == 0):
again = False
del float_list[-1]
else:
float_count = float_count + 1
Is there any way to alter this code so all of the floats are entered into a list? Thanks!
This maybe a good option to use the alternative form of iter(fn, sentinel), e.g.:
float_list = [float(x) for x in iter(input, '0')]
If you need the prompt then you can create a helper function:
import itertools as it
fc = it.count(1)
float_list = [float(x) for x in iter(lambda: input('Float{}: '.format(next(fc))), '0')]
Or alternatively (most closely matches OP's attempt - would exit on 0, 0.0, 0.00, etc.):
fc = it.count(1)
float_list = list(iter(lambda: float(input('Float{}: '.format(next(fc)))), 0.0))
With error handling:
def get_float():
fc = it.count(1)
def _inner():
n = next(fc)
while True:
try:
return float(input("Float{}: ".format(n)))
except ValueError as e:
print(e)
return _inner
float_list = list(iter(get_float(), 0.0))
A list comprehension really isn't appropriate here. Much simpler:
float_count = 1
float_list = []
while True:
val = input("Float%d: " % float_count)
if val == '0':
break
float_list.append(float(val)) # call float(val) to convert from string to float
float_count += 1
it might be more user friendly to not crash if the user didn't type a float, e.g.:
def read_float(msg):
while 1:
val = input(msg)
if val == '0':
return val
try:
return float(val)
except ValueError:
print("%s is not a float, please try again.." % val)
def read_float_list():
float_count = 1
float_list = []
while True:
val = read_float("Float%d: " % float_count)
if val == '0':
break
float_list.append(val) # now val has been converted to float by read_float.
float_count += 1
I am using python 3 and need to print the final result from within the function(this is not optional). Instead it is printing every time it goes through the function.
def reverseDisplay(number):
#base case
#if number is only one digit, return number
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10)))
print(result)
return(result)
def main():
number = int(input("Enter a number: "))
reverseDisplay(number)
main()
If you enter 12345 it prints out
21
321
4321
54321
I want it to print out 54321
The following worked for me (after I found a Python 3 interpreter online):
def reverseDisplay(n):
tmp = n % 10 # Determine the rightmost digit,
print(tmp, end="") # and print it with no space or newline.
if n == tmp: # If the current n and the rightmost digit are the same...
print() # we can finally print the newline and stop recursing.
else: # Otherwise...
reverseDisplay(n // 10) # lop off the rightmost digit and recurse.
If you need to return the reversed value in addition to printing it:
def reverseDisplay(n):
tmp = n % 10
print(tmp, end="")
if n == tmp:
print()
return tmp
else:
return int(str(tmp) + str(reverseDisplay(n // 10)))
You just need to move your print statement out of the reverseDisplay and into main:
def reverseDisplay(number):
#base case
#if number is only one digit, return number
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10)))
return result
def main():
number = 12345
print reverseDisplay(number)
main()
If you really need to print it in the recursive function, you'll have to add a parameter (called first in this example) to make sure you only print the first time:
def reverseDisplay(number, first=True):
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10, False)))
if first:
print(result)
return result
Try this:
def reverseDisplayPrinter(number):
print reverseDisplay(number)
def reverseDisplay(number):
if number<10:
return number
else:
result = int(str(number%10) + str(reverseDisplay(number//10)))
return(result)
def main():
number = int(input("Enter a number: "))
reverseDisplayPrinter(number)
main()
Hello I am trying to write a program in python that asks the user to input a set of numbers of 1's and 0's and I want the program to tell me if I have and even number of zeros or an odd number of zeros or no zero's at all. Thanks for your help!!
forstate = "start"
curstate = "start"
trans = "none"
value = 0
print "Former state....:", forstate
print "Transition....:", trans
print "Current state....", curstate
while curstate != "You hav and even number of zeros":
trans = raw_input("Input a 1 or a 0: ")
if trans == "0" and value <2:
value = value + 1
forstate = curstate
elif trans == "1" and value < 2:
value = value + 0
forstate = curstate
curstate = str(value) + " zeros"
if value >= 2:
curstate = "You have and even number of zeros"
print "former state ...:", forstate
print "Transition .....:", trans
print "Current state....", curstate
Looks like you're trying to do a finite state machine?
try:
inp = raw_input
except NameError:
inp = input
def getInt(msg):
while True:
try:
return int(inp(msg))
except ValueError:
pass
START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']
state = START
while True:
num = getInt('Enter a number (-1 to exit)')
if num==-1:
break
elif num==0:
state = state_next[state]
print 'I have seen {0}.'.format(state_str[state])
Edit:
try:
inp = raw_input
except NameError:
inp = input
START, ODD, EVEN = range(3)
state_next = [ODD, EVEN, ODD]
state_str = ['no zeros yet', 'an odd number of zeros', 'an even number of zeros']
def reduce_fn(state, ch):
return state_next[state] if ch=='0' else state
state = reduce(reduce_fn, inp('Enter at own risk: '), START)
print "I have seen " + state_str[state]
It sounds like homework, or worse an interview questions, but this will get you started.
def homework(s):
counter = 0
if '0' in s:
for i in s:
if i == '0':
counter = counter + 1
return counter
don't forget this part over here
def odd_or_even_or_none(num):
if num == 0:
return 'This string contains no zeros'
if num % 2 == 0
return 'This string contains an even amount of zeros'
else:
return 'This string contains an odd amount of zeros'
if you call homework and give it a string of numbers it will give you back the number of 0
homework('101110101')
now that you know how many 0s you need to call odd_or_even_or_none with that number
odd_or_even_or_none(23)
so the solution looks like this
txt = input('Feed me numbers: ')
counter = str( homework(txt) )
print odd_or_even_or_none(counter)
try:
inp = raw_input
except NameError:
inp = input
zeros = sum(ch=='0' for ch in inp('Can I take your order? '))
if not zeros:
print "none"
elif zeros%2:
print "odd"
else:
print "even"
The simple solution to your problem is just to count the zeros, then print a suitable message. num_zeros = input_stream.count('0')
If you're going to build a finite state machine to learn how to write one, then you'll learn more writing a generic FSM and using it to solve your particular problem. Here's my attempt - note that all the logic for counting the zeros is encoded in the states and their transitions.
class FSMState(object):
def __init__(self, description):
self.transition = {}
self.description = description
def set_transitions(self, on_zero, on_one):
self.transition['0'] = on_zero
self.transition['1'] = on_one
def run_machine(state, input_stream):
"""Put the input_stream through the FSM given."""
for x in input_stream:
state = state.transition[x]
return state
# Create the states of the machine.
NO_ZEROS = FSMState('No zeros')
EVEN_ZEROS = FSMState('An even number of zeros')
ODD_ZEROS = FSMState('An odd number of zeros')
# Set up transitions for each state
NO_ZEROS.set_transitions(ODD_ZEROS, NO_ZEROS)
EVEN_ZEROS.set_transitions(ODD_ZEROS, EVEN_ZEROS)
ODD_ZEROS.set_transitions(EVEN_ZEROS, ODD_ZEROS)
result = run_machine(NO_ZEROS, '01011001010')
print result.description