So I've got this code, it guesses a number between 0 and 100.
It prompts a number and the user answers with 'h' 'l' or 'c'
now everything works fine except that I want this line to only show when the user input is not equal to 'h', 'l' or 'c' instead now it shows up even if I enter 'c' which would break the loop, right?
print "Sorry, I did not understand your input."
full code
start = 0
end = 100
guess = int((start+end)/2.0)
print "Please think of a number between 0 and 100!"
print
x= 'n'
while x != 'c':
print 'Is your secret number ' + str(guess) + '?'
x = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.").lower()
if x == 'h':
end = guess
elif x == 'l':
start = guess
else:
print "Sorry, I did not understand your input."
guess = int((start + end)/2)
print 'your answer is: ' + str(guess)
So to clarify this is the output even when I enter 'c'
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.c
Sorry, I did not understand your input.
your answer is: 50
You do not have an elif for the 'c' case, so it falls to the final else.
Add, the following to handle that case and break the while loop:
elif x == 'c':
break
In addition, you can just do while True: and loop until c breaks.
Your higher/lower logic is backward as well. for h, start = guess, for example.
The update to guess should be indented inside the while loop.
Related
I have ran into some problems while trying to combine while loop and ValueError.
Initially I wanted my program to add numbers together. When the sum of numbers has exceeded X, I would like my program to continue to else statement. At first I didn't focus on the fact that input could also be (for example) string.
number = 1
while number < 10:
add = int(raw_input("Enter a number to add: "))
number += add
print number
else:
print "Number is greater than 10"
I tried combining the first code with try/except and ValueError to accept integers as the only inputs. Second code will not continue to else statement when sum of numbers exceeds X. Could someone please explain why this is not working?
number = 1
while number < 10:
while True:
try:
add = int(raw_input("Enter a number: "))
number += add
print number
except ValueError:
print "Please enter a number"
else:
print "Number is greater than 10"
Thank You.
there's an extra while True: loop resulting in an infinte loop.
Remove it and your code will work fine.
Another example where while(condition) (with condition not True) leads to mistakes: you have to ensure that the loop will be entered once, sometimes by initalizing your condition artificially. I would write that instead
number = 1
while True:
try:
add = int(raw_input("Enter a number: "))
number += add
print number
if number>10:
break
except ValueError:
print "Please enter a number"
print "Number is greater than 10"
I am a beginner in Python and I was trying to write a small program that asks the user to enter an integer that is greater than 0. The function should keep on asking the user for the number until it is valid.
I tried something like below, however I am getting the wrong results. Can you please help me understand my error?
num = input('please enter a number: ' )
n = int(num)
while n < 0:
num = input('please enter a number: ' )
if n >= 0:
print('Valid number')
else:
print('Invalid number')
Is it possible to start the code without an input function? (like to start with num = int())
Thank You for Your Time
There's an error with the logic behind your code.
You firstly ask the user for a number and if he inputs a number which is greater than or equal to 0, the while-loop will never start (in your script: while n < 0:), which, I assume is fine, because the goal of your program is, as you said, to make "the user to enter an integer that is greater than 0".
If the user inputs a number that is smaller than or equal to 0, the while-loop will start, but will never break because inside of it, the value of variable n never changes, only does the value of num.
This is an appropriate script considering that you want to make the user input a number greater than 0, and that you want to give feedback regarding their input.
n = None
while n <= 0:
n = int(input('please enter a number: '))
if n <= 0:
print('Invalid number')
else:
pass # the loop will break at this point
# because n <= 0 is False
print('Valid number')
The code has the user stuck in a loop until they write a number that's greater than 0.
Another solution would be to, inside the loop, check whether int(num) is greater than 0 and if it is, print 'Valid number' and do break to stop the loop; if it's not, print 'Invalid number' (though then the loop doesn't need to be defined by while n < 0:; rather by while True:.
Also, what do you mean by this:
Is it possible to start the code without an input function? (like to start with num = int())
Please clarify this part.
If your problem is the code not terminating, writing Invalid number all the time it's because you are not updating the value of n. You assigned it just once. The solution to your problem is as follows:
n = -1
while n < 0:
n = int(input('please enter a number: '))
if n >= 0:
print('Valid number')
else:
print('Invalid number')
By the way you get rid of starting the code without an input function.
Edit:
As you just said - you want to keep the input reading despite passing an negative integer into the command line. This should help you accomplish this:
while True:
n = int(input('please enter a number: '))
if n >= 0:
print('Valid number')
else:
print('Invalid number')
This loop will go forever until you exit the program lets say with ctrl + C. while True: is as you see an forever ongoing loop, because the True argument will never be false.
I'm very new to python IDLE, I have been tasked with making a game that asks you to guess a random number, here is what I have but whatever I type in it returns "you were too high" a little help would be very appreciated thanks.
import random
i = random.randint(0,100)
print (i)
e = raw_input ("Guess what number I'm thinking of between 0 and 100!")
while e != i:
if i > e:
print "You were too low."
elif i < e:
print "You were too high."
e = raw_input ("Guess what number I'm thinking of between 0 and 100!")
if e == i:
print "yay"
You need to typecast your return call using raw_input, you're comparing ASCII values to integers, example 1 as an ascii character would be 0x31 (49), which compared to 1 is obviously higher. Every value you input is going to output as higher, simple do this to fix your issue.
e = (int(raw_input("Guess what number I'm thinking of between 0 and 100!")))
I tried to make a guess the number game in python but whenever I guess it repeats 4 times 'your guess is too low'
import random
number = random.randint(1, 20)
guessestaken = 0
print('I am thinking of a number between 1 and 20 ')
guess = raw_input('Take a guess and hit enter')
while guessestaken < 4:
guessestaken = guessestaken + 1
if guess > number:
print('your number is too low')
if guess < number:
print('your number is too high ')
if guess == number:
break
print('well done the number was ' + number + ' and you got it in ' + guessestaken + '')
You are asking for the user input before the while loop.
guess = int(raw_input('Take a guess and hit enter'))
This statement should come within the while block.
The function raw_input returns a string, you should convert it to an integer. You can read more about it in the Documentation.
You need to ask the user for input inside your loop, otherwise you are just comparing his first guess multiple times. Also, you should convert the input value to an integer, because raw_input returns a string.
>>> guess = raw_input('guess the number> ')
>>> type(guess)
<type 'str'>
>>> type(int(guess))
<type 'int'>
You are asking for the input from the user only once, right before you enter your loop. You will need to ask the user for a new input after every iteration of the loop, otherwise the guess will never change!
Additionally, when you read in some input from the user with raw_input it will be a string. You will need to cast it to an int.
Next, if you have a break in your loop, the statements after it will not get called. This means that you need to move the break statement to after the output when the user gets the right answer, or nothing will be printed.
Lastly, your logic in the if statements is backwards, if the guess is less than your generated number then the guess was too low, not too high! Altogether you get:
import random
number = random.randint(1, 20)
guessestaken = 0
print('I am thinking of a number between 1 and 20 ')
while guessestaken < 4:
guess = int(raw_input('Take a guess and hit enter'))
guessestaken = guessestaken + 1
if guess < number:
print('your number is too low')
if guess > number:
print('your number is too high ')
if guess == number:
print('well done the number was ' + number + ' and you got it in ' + guessestaken + '')
break
from random import randint
print("you wanna guess a number between A to B and time of guess:")
A = int(input("A:"))
B = int(input("B:"))
time = int(input("time:"))
x = randint(1, 10)
print(x)
while time != 0:
num = int(input("Enter: "))
time -= 1
if num == x:
print("BLA BLA BLA")
break
print("NOPE !")
if time == 0:
print("game over")
break
You just tried to make a loop in >4 so it is a normal error just to use while True: and change the raw_input to int(raw_input)
import random
number = random.randint(1, 20)
guessestaken = 0
print('I am thinking of a number between 1 and 20 ')
guess = int(raw_input('Take a guess and hit enter'))#make your input a int
while True:#change <4 for True
guessestaken = guessestaken + 1
if guess > number:
print('your number is too low')
if guess < number:
print('your number is too high ')
if guess == number:
break
print('well done the number was ' + number + ' and you got it in ' + guessestaken + '')
On an example I am working on, I have code to pick out the vowels between 'a' to 'z'. It is using a switch statement that instead of separate cases, the character values are sharing the same case. From what I know so far, the expression involved i.e
***(letter * (letter >= 'a' && letter <= 'z'))***
evaluates to true or false and is converted to an integer (1 and 0) in which it falls through to "case 0:" (0 obviously being false) to deal with the result should it be false. Can anyone explain the expression to conversion process involved with this statement? particularly the reasoning behind the multiplication of the logical expression. Here is my example code:
char letter(0);
cout << endl
<< "Enter a small letter: ";
cin >> letter;
switch(letter * (letter >= 'a' && letter <= 'z'))
{
case 'a': case 'e': case 'i': case 'o': case 'u':
cout << endl << "You entered a vowel.";
break;
case 0:
cout << endl << "That is not a small letter.";
break;
default: cout << endl << "You entered a consonant.";
}
EDIT: All great answers guys. Cleared a lot up. Thanks again for your input
letter * (letter >= 'a' && letter <= 'z')
The conditional expression multiplicand will evaluate to a true or false. The ASCII value of letter will be compared to the characters "a" and "z". True and false can be implicitly-converted to the numerals 1 and 0 respectively (and letter will be converted to its numeric ASCII value). So it will either be:
letter * (0)
or
letter * (1)
Anything times 0 is 0 which means without a corresponding case the control will go down to the default case (this one goes down to the case: 0 part). Otherwise, letter * (1) is letter, and therefore it will be compared by the other cases as if it were switch (letter).
(letter >= 'a' && letter <= 'z') is a boolean expression, which evaluates to true if the letter is between 'a' and 'z'; now, when you multiply it by letter, it first gets promoted to char, assuming the value 1 if it's true, 0 if false.
Thus, the whole expression will yield 0 if the condition in the parentheses evaluates to false, or letter if it evaluates to true, since any letter multiplied by zero yields zero, and multiplied by 1 yields itself.
(letter * (letter >= 'a' && letter <= 'z'))
Lets take it in 2 parts.
(letter >= 'a' && letter <= 'z')
This one is easy. Is the ascii code of letter greater than that of a and less than that of z. Since letters are sequencially increasing in ascii, this means that the letter is a small letter. However the result of this expression is a true/false, which translates to 1/0 in the next stage.
(letter * <1/0>)
At this stage, letter * 1 returns letter and letter * 0 returns 0. Which explains how the case statements work.
For the exact same reason that brought you here (lack of readability), I would split this off into a if first which checks for lower case letter, before passing on to the switch.