Python - Passing input (prompt) into Function - python

I am trying to create a function that receives input from a user, re-prompts until one character is entered. Strip() is used to removed whitespace so only characters are counted.
Here is my current code:
def inputSomething(prompt, errorMessage = 'Atleast one character must be used'):
while True:
value = (prompt)
Response = value.strip()
if len(Response) >=1:
print ('Valid')
else:
print(errorMessage)
continue
inputSomething(input('Enter str: '))
The problem I'm having is with the loop. Right now it loops the result infinitely. Should I not be using if else?

The problem is that the input is outside the loop:
import sys
def inputSomething(prompt, errorMessage = 'Atleast one character must be used'):
while True:
value = input(prompt)
Response = value.strip()
if Response:
print ('Valid')
return Response
else:
print(errorMessage, file=sys.stderr)
something = inputSomething('Enter str: ')
Note that an empty string equates to False.
I was confused with recursion, because of the indentation used in your question.

Change:
inputSomething(input('Enter str: '))
To:
inputSomething(lambda : input('Enter str: '))
And:
value = (prompt)
To:
value = prompt()
This way you pass a function and then call it, instead of passing the result of a called function.

For future references, another way that also includes retries:
import sys
def inputSomething(prompt, retries = 2, errorMessage = 'Atleast one character must be used'):
while retries > 0:
value = input("Enter str: ")
Response = value.strip()
if Response:
print ('Valid')
retries -= 1
continue
#return Response
else:
print(errorMessage, file=sys.stderr)
retries -= 1
inputSomething('prompt')

Related

Python script not producing output

I have been tasked with reading values inputted by a user(using a while loop) to then store them in a list/array whilst using try: except: to determine if a given input is invalid. In continuation, if the user inputs "done" as a value it will break the loop and print() the total, sum, and average of all the imputed values.
I have gotten this snippet so far:
class Input:
def __init__(self, number_input_value, total_to_be_calculated, main_value):
self.number_input_value = 0
self.total_to_be_calculated = 0.0
self.main_value = input('Enter A Number: ')
self.number_input_value1 = float(self.main_value)
def loop_get_inputs(self):
while True:
self.main_value
if self.main_value == 'done':
break
try :
self.number_input_value1
except :
print('INVAL["VAL"]')
continue
self.number_input_value = self.number_input_value1
self.total_to_be_calculated = self.total_to_be_calculated + self.number_input_value1
print ("Finished successfully!")
print (
self.total_to_be_calculated,
self.number_input_value,
self.total_to_be_calculated/self.number_input_value
)
if __name__ in '__main__':
Input
I have no clue what's wrong, because when it runs it outputs nothing.
Output:
>>>
You need create an instance of the class 'Input' and call the method:
##(self, number_input_value, total_to_be_calculated, main_value)
inp = Input(100, 1000, 10)
#call the method
inp.loop_get_inputs()
Basically:
1 - You have to initialize your class/object before using it.
2 - Having code on the construct is not recommend. You should call a public method of the class to start the "process".
3 - That try-except wasn't doing much. You can, for example, surround the string (from input()) cast to float and print INVALID if the input can't be casted.
4 - You can use += to simplify a = a + b
5 - lower() will convert user input to lowercase, meaning that DONE, done and DoNe (etc) will be considered as "quit" input.
Does this make sense?
class Input:
def __init__(self):
self.number_inputs = 0
self.total = 0.0
def run(self):
self.__get_user_values()
print(f"total: '{self.total}'")
print(f"number_inputs: '{self.number_inputs}'")
print(f"average: '{self.total / self.number_inputs}'")
def __get_user_values(self):
while True:
value = input('Enter A Number: ')
if value.lower() == 'done':
break
if self.__is_valid_input(value):
self.total += float(value)
self.number_inputs += 1
def __is_valid_input(self, value) -> bool:
try:
float(value)
return True
except ValueError:
print('INVAL["VAL"]')
return False
if __name__ in '__main__':
input_wrapper = Input()
input_wrapper.run()

Not getting any results

I am trying to write code to find the length of a string, and to return "invalid entry" when an integer is entered.
def length_of_string(mystring):
if type(mystring) == int:
return "invalid entry"
else:
mystring = input("enter the string ")
return len(mystring)
When I try to execute this function it doesn't give me an error, nor does it produce any solution.
You should move out mystring = input("enter the string ") from else and call the function from main or other place.
def length_of_string(mystring):
if type(mystring) is int:
return "invalid entry"
else:
return len(mystring)
mystring = input("enter the string ")
print(length_of_string(mystring))
If you want the string to be always requested from the user:
def length_of_string():
mystring = input("enter the string ")
try:
int(mystring)
return "invalid entry"
except ValueError:
return len(mystring)
print(length_of_string())
If you want to use the function with a parameter:
def length_of_string(mystring):
try:
int(mystring)
return "invalid entry"
except ValueError:
return len(mystring)
print(length_of_string("a string")) # prints 8
print(length_of_string(1)) # prints invalid entry
print(length_of_string(input("enter the string "))) # prints [input length]
The problem is that you have not called the function. Functions (similar to classes) do not run until you execute them.
Calling them is easy. You just have to call the function name. You also have to pass the necessary parameters to the function (here it is mystring).
length_of_string('Hello World')
To get what is returned you will need to pass it to a variable or print it/perform some other action.
print(length_of_string('Hello World'))
Also if type(mystring) == int: will not work input() is always a string. The thing to do is to test it and see if it can be made into an integer:
try:
int(mystring)
return "invalid entry"
except ValueError:
mystring = input("enter the string ")
return len(mystring)
Entire code:
def length_of_string(mystring):
try:
int(mystring)
return "invalid entry"
except ValueError:
mystring = input("enter the string ")
return len(mystring)
print(length_of_string('Hello World'))
If you pass a string by parameter, it does not make sense to overwrite it again.
I think the solution is:
def length_of_string(mystring):
if (isinstance(mystring, str)):
print "Length of the string: ", len(mystring)
else:
print "Type invalid"

Try-Except ErrorCatching

I'm trying to force the user to input a number using try-except in python however it seems to have no effect.
while count>0:
count=count - 1
while (length != 8):
GTIN=input("Please enter a product code ")
length= len(str(GTIN))
if length!= 8:
print("That is not an eight digit number")
count=count + 1
while valid == False:
try:
GTIN/5
valid = True
except ValueError:
print("That is an invalid number")
count=count + 1
Actually, if the user inputs for example a string, "hello"/5 yields a TypeError, not a ValueError, so catch that instead
You could try to make the input value an int int(value), which raises ValueError if it cannot be converted.
Here's a function that should do what you want with some comments:
def get_product_code():
value = ""
while True: # this will be escaped by the return
# get input from user and strip any extra whitespace: " input "
value = raw_input("Please enter a product code ").strip()
#if not value: # escape from input if nothing is entered
# return None
try:
int(value) # test if value is a number
except ValueError: # raised if cannot convert to an int
print("Input value is not a number")
value = ""
else: # an Exception was not raised
if len(value) == 8: # looks like a valid product code!
return value
else:
print("Input is not an eight digit number")
Once defined, call the function to get input from the user
product_code = get_product_code()
You should also be sure to except and handle KeyboardInterrupt anytime you're expecting user input, because they may put in ^C or something else to crash your program.
product code = None # prevent reference before assignment bugs
try:
product_code = get_product_code() # get code from the user
except KeyboardInterrupt: # catch user attempts to quit
print("^C\nInterrupted by user")
if product_code:
pass # do whatever you want with your product code
else:
print("no product code available!")
# perhaps exit here

How to temporarily ignore punctuation? python

hi i'm trying to write a function to decode a message the user entered
decypherbook = {'0000':8, '0001':1, '0010':0, '0011':9, '0100':5, '0101':3, '0110':7, '0111':2, '1110':4, '1111':6}
userdecode = raw_input("Enter the number you want to de-cypher: ")
def decode(cypher, msg):
length = len(msg)
decoded = ""
key_index = 0 ## starting position of a key in message
while key_index < length:
key = msg[key_index:key_index + 4]
decoded += str(cypher[key])
key_index += 4
return decoded
print "After de-cypher: ", decode(decypherbook, userdecode)
but if the user input a message like "0001,0001", which i would like the result be "1,1". How could i make my code temporarily ignore punctuation so it doesn't mess up with my indexing +4 in my code and still able to print out the punctuation later?
You can check if the next characeter is an integer. If not, just add it to the string and continue to the next character:
def decode(cypher, msg):
length = len(msg)
decoded = ""
key_index = 0 ## starting position of a key in message
while key_index < length:
key = msg[key_index:key_index + 4]
decoded += str(cypher[key])
key_index += 4
# Pass every non digit after
while key_index < length and not msg[key_index].isdigit():
decoded += msg[key_index]
key_index += 1
return decoded
Here is an example of execution:
>>> def decode(cypher, msg):
... # ...
>>> decode(decypherbook, '0001,0010')
'1,0'
Side note: You could also prefer to make a list as a buffer instead of recreating a string every time (string are immutable, every += creates a new object) and do ''.join(buffer) at the end. Just for performance purpose.
Use split method from string object
userdecode = raw_input("Enter the number you want to de-cypher: ")
userdecode_list = userdecode.split(",")
And than call your function like this with join method from string object
print "After de-cypher: ", decode(decypherbook, "".join(userdecode_list))
I feel like replace matches your need more.
def decode(cypher, msg):
for key, value in cypher.items():
msg = msg.replace(key, str(value))
return msg
A fun-one-liner (which assumes userdecode is guaranteed to be of the form r"(\d{4},)*")
def decode(cypher, msg):
return ",".join([str(cypher[x]), for x in userdecode.split(",")])

If else code help in try/ except block

SomeDict = {'Sarah':20, 'Mark': 'hello', 'Jackie': 'bye'}
try:
result = ""
theKey = raw_input("Enter some key: ")
val = someDict[theKey]
except keyErrorr:
result "hello"
else:
result = result + "" + "done"
print result
I understand the try block you can insert and code to try and see what error comes up, and the error then can be caught by the except block. I am trying to figure out the best way to insert a if / else in the try and except block for the same key error that is present in this code. I was thinking that i could just replace the try and except with If/else or is it possible to just add a if/else in the try and except. Any help on how to insert a if/else into this code for key error would be greatly appreciated. So basically i want to add a if/else code into the try and except block for the same key error.
SomeDict = {'Sarah':20, 'Mark': 'hello', 'Jackie': 'bye'}
try:
result = "" #could i insert something like if result == "" : #for this line?
theKey = raw_input("Enter some key: ")
val = someDict[theKey]
except keyErrorr:
result "hello"
else:
result = result + "" + "done"
print result
One reasonable option is to initialize result = None, then test if result is None:.
It's better to use None than the empty string, since someday you might want a dictionary value to be the empty string, plus None is probably clearer to the casual reader of your code.
You could also just skip the try-except, and use if theKey in someDict:.
you can add another except without a specification what exception it should handle.
try:
# do something
except KeyError:
# do something because of the Keyerror
except:
# do what you need to do if the exception is not a KeyError
someDict = {'Sarah':20, 'Mark': 'hello', 'Jackie': 'bye'} # corrected dict name
result = ""
theKey = raw_input("Enter some key: ")
try: # just try the code where the error could be
val = someDict[theKey]
except KeyError: # corrected exception name and indent level
result = "hello" # corrected syntax
else: # corrected indent level
result = result + "" + "done" # why add "" ?
print result
does this work for you?

Categories

Resources