`choice == 1` is False even when user enters "1" - python

I am starting to learn python. I have gone through several tutorials and now I am trying to write my first script. It is a simple console menu. I am running Python 2.6.5 under cygwin.
Here is my script:
import sys
print "********************************************************************"
print "** 1) This is menu choice #1 **"
print "** **"
print "** **"
print "** **"
print "** **"
print "** **"
print "********************************************************************"
print
print "Choice ?"
choice = sys.stdin.readline()
print "You entered: " + choice
if choice == 1:
choice1 = sys.stdin.readline()
print "You entered:" + choice1
else:
quit()
print "Exiting"
When I run the script, I get to the Choice? prompt. I enter 1 and I get the "You entered:" message and then the script exits without displaying the "Exiting" message.
Seems like it should be so easy. Thanks in advance for any help.

You're comparing a string to an integer. Try converting the string into an integer:
if int(choice.strip()) == 1:

Use raw_input() instead of sys.stdin.readline()
Change choice == 1 to choice == '1'

The problem is that readline returns a string, but your if statement expects an int. To convert the string to an int, you could use int(choice.strip()) (be prepared for it to raise an exception if what you enter isn't a valid number).
In [8]: choice
Out[8]: '1\n'
In [9]: int(choice.strip())
Out[9]: 1

Not sure, but I think the user is entering a string, not a number. The number 1 and the string 1 are two completely different things.
Try choice == "1"

The readline function retains the newline at the end of the input. Your first if should be:
if choice == "1\n":
assuming you want the newline.

It's exiting by calling quit() since it takes the else branch. That's because '1' (a string) does not equal 1, an integer.

Related

Function with more choices

I created a simple key stroke counter code that prints number of entered letters. However I am trying to figure out how to make a function so it recognizes 1 letter from 2 letters (singular and plural). I would like to add also 'stroke' in my code, and when the keyboard key is entered only once Id like it to print "You entered 1 stroke" instead of "You entered 1 strokes.".
I tried something but cant really move forward:
print('Start typing: ')
count = raw_input()
print('You entered:'), len(count), ('strokes')
Just use normal conditionals, e.g. using a conditional expression:
print "You entered:", len(count), 'stroke' if len(count) == 1 else 'strokes'
Also, just for fun, the overly clever for the sake of brevity solution that you should not actually use:
print "You entered:", len(count), 'strokes'[:6+(len(count) != 1)]
or:
print "You entered:", len(count), 'stroke' + 's' * (len(count) != 1)
You can use if and else:
if len(count) == 1:
print 'you entered: 1 stroke'
else:
print 'you entered: {} strokes'.format(len(strokes))
Instead of using multiple arguments to print, you can also use string formatting:
print "You entered {} stroke{}".format(len(count), "s"*(len(count)!=1))
Admittedly, the last part is a bit exotic, but you can of course also do
print "You entered {} stroke{}".format(len(count), "s" if len(count) != 1 else "")

Python: Any ideas on how to check is an element in a string is a digit or not, without using .isdigit()?

I am supposed to write a code for a program that will ask a user to input an integer and if the input is not an integer it will print 'try again' and if it is an integer it just quits the program. The only issue is that we are not allowed to use the .isdigit() method. I need to come up with a method to check if each element in a strong is a digit or not without using .isdigit().
while True:
input_str = raw_input('input: ')
input_set = set(input_str)
digit_set = set([str(digit) for digit in range(0, 10)])
# print "isdigit: ", digit_set.issuperset(input_set)
if digit_set.issuperset(input_set) is True:
break
print 'try again'

Python program gives wrong output when use break statement inside while loop

I am using break statement inside while loop to exit from while loop. But it gives wrong output. I don't know why this occurs. Here is the code I have used:
def func():
print "You have entered yes"
t='yes' or 'Y' or 'y' or 'Yes' or 'YES'
while True:
r=raw_input("Enter any number:")
if t=='r':
func()
else:
break
print "Program End"
Update:
When I put Yes it should give :
You have entered yes , but control goes to break statement. Why?
You should not use t = 'y' or 'Y' ... in your code because when you use or it checks the validity. Try this code and I am pretty sure it will work.
def func():
print "You have entered yes"
t=('yes', 'Y', 'y', 'Yes', 'YES')
while True:
r=raw_input("Enter any number:")
if r in t:
func()
else:
break
print "Program End"
Change
if t=='r':
to
if t==r:
Is that what you want?
First, you're checking if t is equal to the string literal 'r' and not the variable r, so in theory what you want is if t==r
However, this won't work. What you're looking for is a list, like the following:
def func():
print "You have entered yes"
t= ['yes','Y','y','Yes','YES']
while True:
r=raw_input("Enter any number:")
if r in t:
func()
else:
break
print "Program End"
When executing
t=='r'
you are comparing variable to a string r (this exact one character only), not to r variable.

Python While loop won't exit when asked to

I don't understand why when the user enters "0" the loop won't exit.
def floatInput():
done = False
while not done:
integerIn = input("Please enter an integer < 0 to finish >: ")
try:
integerIn = int(integerIn)
except:
print("I was expecting an integer number, please try again...")
import sys
sys.exit()
if integerIn == "0":
done = True
else:
integers.append(integerIn)
return integers
def floatInput():
done = False
while not done:
integerIn = input("Please enter an integer < 0 to finish >: ")
try:
integerIn = int(integerIn)
except:
print("I was expecting an integer number, please try again...")
import sys
sys.exit()
Everything above here is fine, but as soon as you got to the comparison, you forgot that you've casted the input to an int.
if integerIn == "0":
Should be
if integerIn == 0:
The reason is because integerIn is an integer and you are treating it like a string in if integerIn=="0". Replace it with integerIN==0 will do the job.
You're converting to an integer and then checking for equality with the string "0".
EDIT: screw the advice about using input or raw_input. Just saw you python 3.x tag, but decided to leave it for future readers.
You have few problems there...
First, in this line:
integers.append(integerIn)
where is integers to begin with? unless it's a global name you must define it in your function.
Second, in this line:
if integerIn == "0":
you're comparing integer to string here, and here's a thing: in python (using python 2.7 here) a string will be bigger than any number if you're doing a comparison, so integerIn == "0" will evaluate to False, always.
Fix it with this:
if integerIn == 0:
Finally, I should tell you this... your code the way it looks like will throws NameError instead of executing what you've done in your except statement.
Try it with the following test cases and try to explain the behavior yourself :)
Please enter an integer < 0 to finish >: test
Please enter an integer < 0 to finish >: "test"
To avoid such problem next time, use raw_input instead of input. So this line:
integerIn = input("Please enter an integer < 0 to finish >: ")
should be like this:
integerIn = raw_input("Please enter an integer < 0 to finish >: ")
NOTICE: I'm not sure but I think raw_input doesn't exist in python 3.x, instead input there will do exactly the same. please correct if I'm wrong.
However, If you're using python 3 then I think you should have no problem.
Here's input vs raw_input() in python 2.x:
input will evaluate the user input then return it.
raw_input will return the user input as string.
so:
# python 2.x
foo = input("input something") # input 3 + 5
print foo # prints 8
bar = raw_input("input something") # input 3 + 5
print bar # prints "3 + 5"
Try this
if integerIn == 0:
should work now.

Python 2 - How to make the script go to a specific line?

This is kind of an extension to my last question, but I was wondering if it is possible to make the script go back to a specific line, if an event happens.
print "Type in 'Hello'"
typed = raw_input("> ")
if typed.lower() in ['hello', 'hi']:
print "Working"
else:
print "not working"
On the last line, if 'else' happens, can you make it so it restarts from line 2 again?
Any help will be very greatly appreciated, thanks a lot!
You could put your code in an endless loop that only exits if the right word is typed in:
print "Type in 'Hello'"
while True:
typed = raw_input("> ")
if typed.lower() in ['hello', 'hi']:
print "Working"
break
else:
print "not working"
You can let the program lie in a loop till the correct input is given
while True:
print "Type in 'Hello'"
typed = raw_input("> ")
if typed.lower() in ['hello', 'hi']:
break
there is 2 ways to do it , one with while loop , and one with recursion
the two answer before mine solved your problem with while loop , so i'd solve yours with recursion
def Inp():
print "Type in 'Hello'"
typed = raw_input("> ")
if typed.lower() in ['hello', 'hi']:
print "Working"
else:
print "not working"
Inp()
Inp()
at the end just call the function Inp and it will continue asking for entering the value you want

Categories

Resources