Input validation while using range function [duplicate] - python

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.

Related

Which one of these would be better to calculate overtime pay?

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.

How can I get this python memory game to work

This is the code I have so far, my teacher wants the game to "flip the X's over" when you guess a number and when they match the numbers stay but when the numbers are different the numbers "flip back over" and become X's again. And he wants the game to say that "you win" when all the numbers have been exposed.
import random
visual=[['X','X','X','X','X'],['X','X','X','X','X'],['X','X','X','X','X'],['X','X','X','X','X'],['X','X','X','X','X']]
data=[[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
random.shuffle(data[0])
random.shuffle(data[1])
random.shuffle(data[2])
random.shuffle(data[3])
random.shuffle(data[4])
while True:
print(visual[0])
print(visual[1])
print(visual[2])
print(visual[3])
print(visual[4])
user_input_1 = int(input('enter a number 0 thru 4 to pick your first X position: '))
user_input_2 = int(input('enter a number 0 thru 4 to pick your first Y position: '))
user_input_3 = int(input('enter a number 0 thru 4 to pick your second X position: '))
user_input_4 = int(input('enter a number 0 thru 4 to pick your second Y position: '))
if data[user_input_1][user_input_2] == data[user_input_3][user_input_4]:
visual[user_input_1][user_input_2] = str(data[user_input_1][user_input_2])
visual[user_input_3][user_input_4] = str(data[user_input_3][user_input_4])
print(visual[0])
print(visual[1])
print(visual[2])
print(visual[3])
print(visual[4])
print('Congratulations you won the game!')
break
Here are the discrete steps in the game as I understand it:
Initialize the board and data.
Shuffle the data
Enter Loop
Print the board
Ask user for their first guess
Ask user for their second guess
Print the board with reveals
Cover them back up if user missed
Check win condition (everything revealed?)
Loop back or print win
Your code successfully initializes the board (step 1), shuffles the data (2), enter loop (3), prints board (4), and asks for the guesses (5)(6).
Here is some guidance on the pieces you are missing:
After you get the inputs, you always want to print the board with the reveals (7). To do this you need to update visuals first with the piece you have written:
visual[user_input_1][user_input_2] = str(data[user_input_1][user_input_2])
visual[user_input_3][user_input_4] = str(data[user_input_3][user_input_4])
and then print your visuals. This does not need to happen with an if statement, because you always want to do a print of the revealed board.
Afterwards, you want to do the swap back to X's if the user misses (8). You have this condition already basically written. You need to check if it's a miss in the data board and swap those visuals back to X's if true:
if data[user_input_1][user_input_2] != data[user_input_3][user_input_4]:
visual[user_input_1][user_input_2] = 'X'
visual[user_input_3][user_input_4] = 'X'
Side Note: Ideally, you want to clear the previous board print of the reveals to test memory. This part is kind of tricky. There are no simple ways to clear the print of the reveals without using operating system commands which are almost certainly beyond the scope of your class. I would check with your teacher about expectations around flipping back over.
If you are interested in how this is achievable using operating system command in Python here is a relevant StackOverflow post. You would need to import os and import time. After you print reveal, use time.sleep(number_of_seconds) to give the user however many seconds to try to memorize placements and then use os.system('clear') for linux/mac os or os.system('CLS') for windows to clear the screen. Again, it's very unlikely that this is what your teacher is looking for.
Now let's deal with the win condition (9). Currently you are using a "while True:" with a break. While this may be functional in this case, using "while True:" should be almost always avoided (there are many reasons why-- here is a post that addresses one reason). Loop structures like "while", "do-while", and "for" have built-in stopping conditions which will be checked each time you loop. In this program, your stopping condition is that the board is completely revealed (that is how you know the game is over and user no longer needs to guess). So, until this happens you want your while loop to keep going. This looks like this:
while #win condition is not met#:
#stuff you want to loop#
#congrats, you have met your win condition#
There are multiple ways to check your win condition is not yet met. One option is that you know you have not won yet if the visual board is still not the same as data board:
while visuals != data:
#stuff you want to loop#
print(congrats....)
In summary, TLDR:
import random
visuals = [...]
data = [...]
#shuffle
while visuals != data:
#print visuals
#get input
#update the inputted visuals with reveals
#print visuals with reveals
if #not a match:
#update the inputted visuals back to X's
print("Congratulations you won the game!")
There are a handful of smaller points that could improve your code as well if you're interested: be very vigilant about indents, a do-while loops is more appropriate here (can you think of why?), you can write functions and loops that reduce a lot of the repeating code (like when you print the visuals). But this should be enough for you to grapple with.
Some suggestions for your code:
Since you display the board so often, you may want to write a separate function that takes the variable visual as input and prints the content. Then you can just call the function instead of writing all of those print statements.
In your current code, you only display the cards when there's a match. One of the whole strategies for playing a memory game is that if you overturn two cards and see "5" and "2" for example, it's not a match, but if you overturn a new pair of cards and one of them is another "5", you might remember where that first "5" was you overturned in your previous turn and thus know how to make a match. So perhaps you should do this: update and display visual after selecting the first card, then do the same with the second card. If there's a match, then leave visual as is. If they don't match, then replace the two spots back with 'X' and go back to the top of the loop.
Your code seems to consider a single match a "win". Shouldn't it be considered won once all of the cards have been matched? In this case, you can follow up the previous step by checking to see if 'X' shows up anywhere in visual. If it doesn't, then that means all of the cards have been uncovered, thus the player has won.

in a while loop, where should you place a variable for counting?

enter image description here
Please excuse me that I'm posting my code as an image.
This is a simple guessing game expression.
When you look at the last line of the code,
there is 'tries += 1' code to count how many times it's looped.
So my question is,
the result is changing when I put 'tries += 1' right under
the code line 'guess = input("What is your lucky number?")'.
So what is the difference between
putting it at the last line of the code block and right under the start of while loop code.
Thanks for helping :)
Wouldn't it have been far easier to just copy in the text than to print-screen and crop the image? The number of tries is initialized to 1 which is misleading as at that point in the program there hasn't been any tries. Logically it makes more sense to initialize tries to 0 and place the increment immediately after the user input. But because the program hasn't been structured in this way, tries must be incremented after comparing the guess to the target; otherwise, in the case when the user's guess is correct, the output would show a number of tries one greater than the actual number of tries.
What you're misunderstanding is the order in which your code executes. There are three important events inside your loop:
You ask the user for their guess
You process their guess, and if they get it right you display the current value of the variable tries
You increment the variable tries, in the statement tries += 1
These execute in exactly that order. So, when the user guesses correctly, they're told the value of tries before it is incremented again. If you put the line tries += 1 right after the input statement, then that value is now being increased before it is printed. Thus, the displayed value is different.

What are the necessary requirements for coding decimal to binary [Python]?

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.

Transform game pseudo code into python

Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete
program is given below; your task is to turn it into a working python program.
The program should start by printing instructions to the screen, explaining that the user
should pick a number between 1 and 1000 and the computer will guess it in no more than
10 tries. It then starts making guesses, and after each guess it asks the user for feedback.
The user should be instructed to enter -1 if the guess needs to be lower, 0 if it was right,
and 1 if it needs to be higher.When the program guesses correctly, it should report how many guesses were required. If the user enters an invalid response, the instructions should be repeated and the user allowed to try again.
Pseudocode
- Print instructions to the user
-Start with high = 1000, low = 1, and tries = 1
- While high is greater than low
- Guess the average of high and low
- Ask the user to respond to the guess
- Handle the four possible outcomes:
- If the guess was right, print a message that tries guesses were required and quit the program
- If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries
- If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries
- If the user entered an incorrect value, print out the instructions again
- high and low must be equal, so print out the answer and the value of tries
I need some serious help! I don't understand any of this stuff at all!
This is all I have
def main(x, nums, low, high):
input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ")
for i in range (1, 1001):
main()
and I don't even know if it's right!
Before thinking about how to implement this in python (or any language) lets look at the pseudocode, which looks like a pretty good plan to solve the problem.
I would guess that one thing you might be getting stuck on is the way the pseudocode references variables, like high and low. The way to understand variables is to consider them slots that values can be stored. At any given time, a variable has some value, like the number 5, or a reference to an open file. That value can be summoned at any time by using its name, or it can be given a new value by assigning to it, and the old value will be forgotten with the new value taking its place.
The pseudocode references three variables, high, low and tries. It also tells you what their initial values should be. After the second line has executed, those values are set to 1000, 1 and 1, respectively, but they take on new values as the program progresses.
Another feature of the pseudocode is a conditional loop, and a case analysis of the user input. Your translation of the pseudocode's loop is incorrect. In your case, you have created a new variable, i and have instructed your program to run the loop body with every value of i between 1 and 1000. Obviously this doesn't have a whole lot to do with the pseudocode.
Instead what you want to do is loop forever, until some condition (which changes in the loop body) becomes false. In python, the while statement does this. If you're familiar with an if statement, while looks the same, but after the body is done, the condition is re-evaluated and the body is executed again if it is still true.
Finally, the case analysis in the body of the loop requires comparing something to expected values. Although some other languages have a number of ways of expressing this, in python we only have if-elif-else clauses.
Outside of transforming pseudocode to working code, it is probably useful to understand what the program is actually doing. The key here is on line 4, where the program guesses the average of two values. after that the program acts on how well the guess worked out.
In the first run through the loop, with high containing 1000 and low containing 1, the average is 500 (actually the average is 500.5, but since we're averaging whole numbers, python guesses that we want the result of the division to also be an integer). Obviously that guess has only a 0.1% chance of being right, but if it's wrong, the user is expected to tell us if it was too high, or too low. Either way, that answer completely eliminates 50% of the possible guesses.
If, for instance, the user was thinking of a low number, then when the program guessed 500, the user would tell the program that 500 was too high, and then the program wouldn't ever have to guess that the number was in the range of 501 thru 1000. That can save the computer a lot of work.
To put that information to use, the program keeps track of the range of possible values the goal number could be. When the number guessed is too high, the program adjusts its upper bound downward, just below the guess, and if the guess was too low, the program adjusts its lower bound upward to just above the guess.
When the program guesses again, the guess is right in the middle of the possible range, cutting the range in half again. The number of possible guesses went from the original 1000 to 500 in one guess, to 250 in two guesses. If the program has terrible luck, and can't get it two (which is actually pretty likely), then by the third, it has only 125 numbers left to worry about. After the fourth guess, only 62 numbers remain in range. This continues, and after eight guesses, only 3 numbers remain, and the program tries the middle number for its ninth guess. If that turns out to be wrong, only one number is left, and the program guesses it!
This technique of splitting a range in half and then continuing to the closer half is called bisection and appears in a wide range topics of interest to computer science.
How about some CODE! Since i don't want to deprive you of the learning experience, I'll just give you some snippets that might help you along. python is a language designed for interactive exploration, so fire up your interpreter and give this a shot. I'll be posting examples with the prompts shown, don't actually type that.
Here's an example using the while clause:
>>> x = 1000
>>> while x > 1:
... x = x/2
... print x
...
500
250
125
62
31
15
7
3
1
>>> x
1
Getting console input from the user should be done through the raw_input() function. It just returns whatever the user types. This is a little harder to show. To simplify things, after every line of python that requires input, I'll type "Hello World!" (without the quotes)
>>> raw_input()
Hello World!
'Hello World!'
>>> y = raw_input()
Hello World!
>>> print y
Hello World!
>>>
How about some combining of concepts!
>>> myvar = ''
>>> while myvar != 'exit':
... myvar = raw_input()
... if myvar == 'apples':
... print "I like apples"
... elif myvar == 'bananas':
... print "I don't like bananas"
... else:
... print "I've never eaten", myvar
...
apples
I like apples
mangoes
I've never eaten mangoes
bananas
I don't like bananas
exit
I've never eaten exit
>>>
Oops. little bit of a bug there. See if you can fix it!
I don't understand any of this stuff at all!
That's pretty problematic, but, fine, let's do one step at a time! Your homework assignment begins:
Print instructions to the user
So you don't understand ANY of the stuff, you say, so that means you don't understand this part either. Well: "the user" is the person who's running your program. "Instructions" are English sentences that tell him or her what to do to play the game, as per the following quote from this excellently clear and detailed assignment:
The program should start by printing instructions to the screen, explaining
that the user should pick a number between 1 and 1000 and the computer will
guess it in no more than 10 tries.
"print" is a Python instruction that emits information; for example, try a program containing only
print "some information"
to see how it works. OK, can you please edit your answer to show us that you've gotten this point, so we can move to the next one? Feel free to comment here with further questions if any words or concepts I'm using are still too advanced for you, and I'll try to clarify!
You're obviously very new to programming, and I guess that is one of the reasons for a delayed response from the community. It's tough to decide where to start and how to guide you through this whole exercise.
So, before you get a good answer here that includes making you understand what's happening there, and guiding you through building the solution yourself (ideally!) I would suggest you visit this page to try to get a grasp of the actual problem itself.
http://www.openbookproject.net/pybiblio/gasp/course/4-highlow.html
In the meantime, look at all the answers in this thread and keep editing your post so that we know you're getting it.
Doesn't match the psudocode exactly but it works. lol ;)
I know this is a wicked old post but this is the same assignment I got also. Here is what I ended up with:
high = 1000
low = 1
print "Pick a number between 1 and 1000."
print "I will guess your number in 10 tries or less."
print "Or at least i'll try to. ;)"
print "My first guess is 500."
guess = 500
tries = 0
answer = 1
print "Enter 1 if it's higher."
print "Enter -1 if it's lower."
print "Enter 0 if I guessed it!"
print ""
while (answer != 0):
answer = int(raw_input("Am I close?"))
if answer == 1:
tries = tries + 1
low = guess
guess = (high + low) / 2
print "My next guess is:"
print guess
elif answer == -1:
tries = tries + 1
high = guess
guess = (high + low) / 2
print "My next guess is:"
print guess
elif answer == 0:
tries = tries + 1
print "Your number is:"
print guess
print "Yay! I got it! Number of guesses:"
print tries
Okay, the nice part about using Python is that it's almost pseudocode anyway.
Now, let's think about the individual steps:
How do you get the average between high and low?
How do you ask the user if the answerr is correct
What do "if" statements look like in Python, and how would you write the pseudocode out as if statements?
Here's another hint -- you can run python as an interpreter and try individual statements along, so, for example, you could do
high=23
low=7
then compute what you think should be the average or midpoint between them (hint: 15)
Welcome to Stack Overflow!
The trick here is to realize that your Python program should look almost like the pseudocode.
First let's try to understand exactly what the pseudocode is doing. If we had to interact with the program described by the pseudocode, it would look something like this:
Think of a number between 1 and 1000 and press Enter.
>>>
Is it 500? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.
>>> 1
Is it 750? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.
>>> -1
Is it 625? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.
etc.
When we first think of our number, the program knows only that it is between 1 and 1000. It represents this knowledge by setting the variable 'low' to 1 and the variable 'high' to 1000. Its first guess is the average of these numbers, which is 500.
After we tell the program that our number is greater than 500, it updates the value of 'low' to 501. In other words the program then knows that our number is between 501 and 1000. It then guesses the average of 501 and 1000, which is 750. We tell it that our number is lower, so the program updates the value of 'high' to 749 and guesses the average of 501 and 749 next, and so on until it guesses right, or it has narrowed the possible range down to a single number (meaning its next guess will be right).
So back to writing the program in Python: We basically just translate the pseudocode line for line. For example our program loop should look just like it does in the pseucode:
while high > low:
# Guess (high + low) / 2 and ask user to respond
# Handle user response
There is no need for a for-loop as you have in your code.
To take input we can do something like this:
guess = (high + low) / 2
response = input('Is it ' + str(guess) + '? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.')
Now the user input is stored in the variable 'response', and we can handle the possibilities with if statements like 'if response == -1:' for example.
Just remember to print the instructions and set 'high' and 'low' to their initial values before entering the while loop and you should be all set.
Good luck!
Here's a few hints to get you started:
Average = Value + Value + Value [...] / Number of Values; (for instance, ((2 + 5 + 3) / (3))
Many programming languages use different operator precedence. When I am programming, I always use parentheses when I am unsure about operator precedence. In my example above, if you only did 2 + 5 + 3 / 3, the program would do division operations before addition - so it would evaulate to 2 + 5 + (3 / 3), or 2 + 5 + 1 == 7.
Skip this for python users
/*
Secondly: your earliest programs can benefit from const correctness (here is a good explanation of what it is and why it is EXTREMELY good practice). Please read through that and understand why you should use constants (or whatever the python equivalent is). Also look up "magic numbers," which is a big area where constants are used.
*/
Google "Please Excuse My Dear Aunt Sally" (NOTE: this only deals with mathematical operators, and mostly holds true for programming languages; for a more comprehensive study of operator precedence, look up your chosen language's documentation for precedence - also note that most programs don't have built in power operators, but most standard libraries have pow functions).
Speaking of standard library: Get acquainted with standard library functions (I have never used Python, I don't know how it implements a SL, but I would be extremely surprised if a language that popular didn't have a well developed SL). If you don't know what that is, and your book/tutorial doesn't have it, get a new one. Any resource that doesn't reference a standard library is not worth the time.
Lastly: while this post may look like I know what I'm talking about, I really am still in the early phases of learning, just like you. A few things you might want to get used to early on (when I skipped these parts, it slowed my learning a lot): The use of references and pointers (Q for comments: does Python have pointers?), the difference between the data IN a memory location and the actual memory location (often times, the location of the value in memory will be more useful than the value itself, at least when writing data structures). Especially get used to the standard library; look for copy, find, etc. type functions useful in string manipulation.
Actually, rereading your original post, I did not realize this was a homework type assignment. If you aren't doing this for fun, you will probably never take my advice. Just remember that programming can be extremely fun, if you don't make it a chore - and don't get frustrated when your code doesn't compile (or...interpret), or you get unexpected results, etc.

Categories

Resources