Okay, so I have had some help with some fellow users on this website and I found you can't just ask someone for code. I am not. I want to know some of the variables and stuff needed to code.
1) Need to have a raw_input so the user can type in their number.
- I have seen you type:
raw_input("Please insert a number: ") #This allows you the user to type in a number.
2) Need to have if, elif and else statements in my code to stop the user from typing in Anything but numerical values
-I think you need this:
if raw_input == '£' or '$' or '%' ETC
but I think that might take too long :( Need help to make my if statements
3) Need to stop the user from entering a value below 1 and above 256.
I think you need this:
if raw_input > 256:
return("Enter a value below 256")
elif raw_input < 1: return("Enter a value above 1")
4) Need to have the binary number presented as an '8 bit'
Example "00000111" same as "111".
Thanks, all information will be useful and I will try to reply to all of yous! Thanks!!!
First of all, welcome to StackOverflow. It looks like you've been burned on questions in the past, and probably rightly so. This site is not typically well-suited for rank amateurs, who are better suited looking up a tutorial or reading documentation.
That said, you seem earnest in your efforts and have phrased the question in a meaningful way, so let me try to help:
1) Need to have a raw_input so the user can type in their number
That's correct, the way you store user input in Python2 is raw_input, as such:
variable_name = raw_input("Prompt")
2 and 3) Input validation
Basically both these points are the same -- how do I make sure my user entered data that's appropriate? There's lots of schools of thought on this, and you should read the difference between EAFP and LBYL coding, as well as concepts like duck-typing and etc. For now, let me just show you what I would do.
number = raw_input("prompt")
try:
number = int(number)
except ValueError:
# the user entered a value that can't be converted
# to an integer, e.g. letters or a decimal number
# so you'd handle that here, maybe with...
print("Invalid number")
if 1 <= number <= 255:
# user has entered a number below 1 or above 256
# handle it as above, probably ending with:
return
4) Conversion and return of value
Once you've done all the steps above, your number is GUARANTEED to either have thrown an error or be an integer between 1-256. From this point on, it's smooth sailing, just return the binary representation of that number (which is done with the built-in bin)
else:
# number is now an integer between 1-256
return bin(number) # bin(x) returns the number in base 2
Clarification
There are some terms here you've never seen before, so let me explain.
try:
do_a_thing()
except Exception:
handle_exception()
This is called a try/except block, and you use them when you're expecting the thing you're doing inside the block might throw an exception. For instance I might do:
try:
f = open("path/to/a/file.txt", "r") # open a file in read mode
except (IOError,FileNotFoundError,PermissionError):
print("Can't open that file because of an error")
I know when I try to open a file, it might fail if another application has it open, or if I'm not able to access the drive it's on, or even if the file doesn't exist! I then specify underneath how my code should handle each situation, and could even do
try:
f = open("path/to/a/file.txt","r")
except IOError:
handle_IOError()
except FileNotFoundError:
make_file("path/to/a/file.txt")
except PermissionError:
get_permission('path/to/a/file.txt')
To handle multiple errors in different ways.
Final Product
If this were my code, I would write it like this:
def get_binary(value):
try:
value = int(value)
assert 1 >= value >= 255
except ValueError:
raise TypeError("Value must be an integer")
except AssertionError:
raise ValueError("Value must be between 1-255")
return bin(value)
user_in = raw_input("Enter a number between 1-255: ")
print "The number in binary is {}".format(get_binary(user_in)[2:])
The basic strategy is to see if you can cast your number appropriately to a float (or int, if you prefer). If you can, it's a valid number. If you can't, ask the user for another input.
while (True):
input = raw_input("Please enter a number: ")
try:
number = float(input)
if number < 1 or number > 256:
print("The number must be between 1 and 256 inclusive.")
continue
break
except ValueError:
pass
# do whatever you want with your number here
print(number)
To answer your questions:
"try" means do something that we think might not work quite right, such as making a number out of something the user is entering that isn't a number. If you do that, it causes a ValueError.
So, we "except" or "catch" this ValueError. This is where we could do some sort of error handling code, like print("I said a number!").
continue brings us back to the start of the while loop
break stops the while look and goes to the next line of code.
Related
I want somebody to explain what is the difference between these two was of solving this problem and which one would be better.
Rewrite your pay program using try and except so that your
program handles non-numerical input gracefully by printing a message and
exiting the program. The following shows two executions of the program:
Enter Hours: 20
Enter Rate : nine
Error, please enter numeric input
Enter Hours: forty
Error, please enter numeric input
input_hours = input('Enter Hours: ')
try:
hours = float(input_hours)
except ValueError:
print('Error, please enter numeric input')
quit()
input_rate = input('Enter Rate: ')
try:
rate = float(input_rate)
except ValueError:
print('Error, please enter numeric input')
quit()
if hours < 40:
pay = rate * hours
else:
overtime = hours - 40
pay = (rate * 40.0) + (1.5 * rate * overtime)
print(pay)
or
try:
hrs = input('Enter Hours: ')
hr = float(hrs)
rate = input('Enter Rate: ')
rt = float(rate)
if float(hr) <= 40:
print(hr * rt)
else:
hrr = hr - 40
rr = hrr * 1.5 * rt
print(40 * rt + rr)
except:
print('Error, please enter numeric input')
Let's call them way1 and way2 respectively.
In way1, you are checking the value error after each input, but in way2, you are checking any error(in this case it is most likely to be a value error) after your code snippet.
Way1 checks error after every input, and way2 checks the error as a whole. In python, if it gets any error, the compiler will stop and throws an error.
Suppose, due to human error, you'll get an attribute error, way2 will print:
"Error, please enter numeric input"
But, way1 will give you an error and the code stops working, you'll have to re-run it.
Now let's talk about space and time complexity, both the code have the same complexity
IF someone else wants to understand your code, in a situation when you're not contactable, he/she will easily understand the way2 snippet because it is cleaner and easy to read.
The main difference between these approaches is whether you have a try-catch block around all of the code, or just one around the error-checking.
Firstly, the first one splits the error-checking into multiple try-except blocks, whereas the second one puts the whole code block into a single try-except block. Secondly, the first one skips the calculation part of the code with quit() functions, whereas the second one skips it by having it inside of the try block.
I would say that the second approach is cleaner and easier to read. Firstly, you have only one try-except block, which reduces the amount of redundant code that you have.
Secondly, it is easier to see what's happening when you skip the code by having it all in the try-except block rather than having the program quit.
Finally, the second piece of code is just shorter and less messy and feels more like standard practice to me.
There is repeated code in the first Try Statement. There are two Try and Excepts handling each user input for errors, whereas in the second block of code there is only one. Don't Repeat Yourself (DRY) principle states that duplication in logic should be eliminated via abstraction. Adding additional, unnecessary code to a codebase increases the amount of work required to extend and maintain the software in the future.
The second Try statement looks cleaner, easier to read, and is the preferred logical method.
What is the issue with:
try:
number = int((self.final_df_1[index1_name][i])[:first_space_a])
except TypeError or ValueError:
continue
For some background, that entry in the Dataframe is a string of an address. The argument of int() is simply the first "word," which in this case is the street number. The logic here is that I want to try to convert that street number into an integer, and if it happens to throw TypeError or ValueError, I want to skip to the next iteration of the for loop that this is nested within, ie, to the next row of the Dataframe. This is practical because the CSV's I'm parsing through contain thousands of addresses, and occasionally one will be formatted oddly (such as '74271/2,' which is one of the few entries that consistently throws this error in the test set).
I would expect this chunk of code to, during the attempt to convert to an integer, catch the error and, again, skip to the next iteration of the loop, but instead it does anything but what it's supposed to do.
Thanks in advance.
try doing
try:
number = int((self.final_df_1[index1_name][i])[:first_space_a])
except (TypeError,ValueError):
continue
instead of
try:
number = int((self.final_df_1[index1_name][i])[:first_space_a])
except TypeError or ValueError:
continue
This will check for both errors and the program won't crash. You can extend this to any amount of errors you want to check for.
Can anyone help me how to take input described in the problem below (link provided). I just want to know the implementation of the input part in Python 3.7 language. Please don't share your answer or logic of the main problem.
https://www.spoj.com/problems/COINS/
while True:
try:
value = int(input()) # Bytelandian coins can only have integer values.
except:
break
# your code to find and print the dollars you can make for a coin worth 'value' goes here
...
attempts = 0
guess = 5
name = input("what is your name?: ")
print("Hello",name,"i am thinking of a number")
print("it is between 1-20")
user_Guess = int(input("can you guess what it is?: "))
while user_Guess <5:
print("Too low!")
attempts += 1
while user_Guess >5:
print("too high!")
attempts += 1
im using the latest version of python and i don't know where i have went wrong. When i type in the correct answer "5" it prints that its too low!!!! what do i do?!please help if you can but don't over complicate or drastically change my answer.
Ok, so first things first, if you want a cleaner solved version I made one. Don't check it out before you try yourself though, but keep the link: https://repl.it/EQOg/2
Your current code doesn't do anything if you give it 5. No reason for a "Too Low" message.
However, if you try anything that isn't (including numbers beyond 20) you will get an infinite loop, because there's no opportunity for the user to fix anything. See the code runs one line after the other, so say if I guess 3, than this loop:
while user_Guess <5:
print("Too low!")
Will go on forever, since user_Guess will always be lower than 5. What you want to do is have only one while loop, that will break when the user guessed correctly. General tip, when you try to build something logical like this, it's helpful to write pseudo code describing what you're trying to achieve. In this case, you probably want something like this:
#take number input from user
while users guess is wrong:
if the number is higher:
# print something & count attempt
if the number is lower:
# print something & count attempt
if the number is invalid:
# print something
# take number input from user (again)
## this is the important part - it lets the user change his guess.
## If his guess is correct, it will break the loop.
## If not, he gets to try again and again until correct
# print some success message after breaking the loop
There are more clever designs but this is the simplest I think
P.S.: Note that my linked solution doesn't fix an invalid input (i.e. input that isn't a number). You should validate that yourself as well
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I am creating a function that appends a list with inputs. There needs to be exactly 24 items for hours in a day.I am using the range function to do this. I need to validate this input. However I can't seem to get it to validate properly every time or i've gotten proper validation but the code is prompting more than 24 inputs.
def get(list):
for i in range(24):
tem=float(input("Hourly tempature (00:00-23:00): "))
if tem < -50 or tem > 150:
print ("Enter tempatures between -50 and 130")
else:
tem=float(input("Hourly tempature (00:00-23:00)"))
list.append(tem)
Putting the input in the else block, not the if, means your code prompts for input again within the loop when the first input is correct, instead of incorrect.
In any case if they enter something wrong it won't check again. You need to use a while loop. See https://stackoverflow.com/a/23294659/2482744
Several points:
You might want to consider telling the user which hour they are setting the temperature for: e.g. input("Temperature at "+str(i)+":00 hours:")
You should clarify whether you want the temperature to be less than or equal to 150, or less than or equal to 130, since at the moment the text given to the user suggests that the temperature has to be less than or equal to 130, but your if statement suggests that it has to be less than or equal to 150.
You probably shouldn't be using the built-in list as a variable. Try using a variable that describes its purpose, like myTemperatureList
Your code currently prompts for input again when the input is within the temperature bounds, but prints an error message (not getting an extra input) when the temperature is out of bounds. This means that when the temperature input is within the bounds, the user will be prompted for input twice, and the second input will be added to your list. However, when the temperature input is outwith the bounds, although an error message will be printed, the user will not be prompted for a second input, and the temperature outwith the bounds will be added to your list.
Expanding on point 3 above, what you want the input validation code to do is prompt for a temperature, and check if that temperature is within the bounds. If it is, then the value should be added to your list, if it isn't, then the value should be discarded, and the user should be prompted for input again.
This can be done in several ways. For instance, using a while loop, a possible solution might be this:
def get(myTemperatureList):
for i in range(24):
while True:
#This is so that when an error message is printed,
#the user is prompted again for input, for as long as they
#are providing bad input
try:
#You'll want this try-except block in case the user doesn't enter a number
tem=float(input("Temperature at "+str(i)+":00 hours:"))
#This is basically the sames as in your code
if tem < -50 or tem > 150:
print ("Enter a temperature between -50 and 130")
#Same logic as in your code, prints an error message
#when the temperature is out of bounds
else:
#If the temperature is valid, break out of the while loop
break
except ValueError:
print("Enter a number")
myTemperatureList.append(tem)
You could also solve this problem in other ways, for instance, using recursion with a validation function.