Python not responding in loop - python

Here is my code:
from random import randint
doorNum = randint(1, 3)
doorInp = input("Please Enter A Door Number Between 1 and 3: ")
x = 1
while (x == 1) :
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
exit()
now, that works fine, if I happen to get the unlucky number.
else :
print("You entered a room.")
doorNum = randint(1, 3)
This is the part where it stops responding entirely. I am running it in a bash interactive shell (Terminal, on osx). It just ends up blank.
I am new to programming in Python, I spent most of my time as a web developer.
UPDATE:
Thanks #rawing, I can not yet upvote (newbie), so will put it here.

If you are using python3, then input returns a string and comparing a string to an int is always false, thus your exit() function can never run.

Your doorInp variable is a string type, which is causing the issue because you are comparing it to an integer in the if statement. You can easily check by adding something like print(type(doorInp)) after your input line.
To fix it, just enclose the input statement inside int() like:doorInp = int(input("...."))

In python3, the input function returns a string. You're comparing this string value to a random int value. This will always evaluate to False. Since you only ask for user input once, before the loop, the user never gets a chance to choose a new number and the loop keeps comparing a random number to a string forever.
I'm not sure what exactly your code is supposed to do, but you probably wanted to do something like this:
from random import randint
while True:
doorNum = randint(1, 3)
doorInp = int(input("Please Enter A Door Number Between 1 and 3: "))
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
break
print("You entered a room.")
See also: Asking the user for input until they give a valid response

Related

Program asks twice for number if wrong data is input first

I am very new to Python (started 2 days ago). I was trying to validate positive integers. The code does validate the numbers but it asks twice after a wrong input is entered. For example if I enter the word Python, it says: This is not an integer! like is supposed to but if I enter 20 afterwards, it also says it is not an integer and if I enter 20 again it reads it.
def is_positive_integer(input):
#error: when a non-integer is input and then an integer is input it takes two tries to read the integer
flag = 0
while flag != 1:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
input = raw_input("Enter the number again:")
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
if isinstance(input, int):
flag = 1
return input
number = raw_input("Enter the number to be expanded: ")
is_positive_integer(number)
number = int(is_positive_integer(number))
Any help is appreciated.
The main bug is that you call is_positive_integer(number) twice with the same input (the first thing you enter).
The first time you call is_positive_integer(number), you throw away the return value. Only the second time do you assign the result to number.
You can "fix" your program by removing the line with just is_positive_integer(number) on its own.
However, your code is a little messy, and the name is_positive_integer does not describe what the function actually does.
I would refactor a little like this:
def input_positive_integer(prompt):
input = raw_input(prompt)
while True:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
else:
return input
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
number = input_positive_integer("Enter the number to be expanded: ")
The problem stems from the fact that you're calling is_positive_integer twice. So, the first time it's called, you send it a string like 'hello', then it says it's not an integer and tells you to try again. Then you enter '20', which parses fine, and it's returned.
But then you don't save a reference to that, so it goes nowhere.
Then you call the function again, this time saving a reference to it, and it first tries the original bad string, which was still there in number. Then it complains that it's a bad input, asks you for a new one, and you provide it, terminating the program.

Using multiple try statements with strings

Hi so I am working on a game and my game at the start asks the user if they want the rules to the game (y/n). I'm using if statements and else for this, so if user puts in y print rules and if user puts in n start game etc...it works fine, until the user puts in an integer or a word or something python doesn't recognize and it just goes and uses the else statement. My game is a math game so I used try statements before that if the user punched in something that's not a number it tells the user "Invalid, try again". The problem I'm having now is how to tell python to try multiple things...
I tried using try x = 'y' or x = 'n' but it says you can't give try multiple operations or something
Please help,
Cheers
You might want to use the following:
if inp=="Option1":
...
elif inp=="Option2":
...
elif inp=="Option3":
...
else:
print "Not known command"
You need a while loop that will keep taking input until the user inputs either y or n
while True:
inp = raw_input("Add intruction here")
if inp == "y":
# code here
elif inp == "n":
# code here
else:
print "Invalid input"

Testing Valid Input Python

So I have a finished program that accepts an input file with bank account information and parses it up and allows for a few different utilities.
One such utility is adding a transaction to the "database" (just a log file).
The program prompts the user to enter 'w' or 'd' and then an amount (float). This represents a deposit or withdrawal of X amount of money.
I was wondering how to go about making sure that the user entered either 'w' or 'd' AND a correct amount (number).
So, I decided that a while loop with the above condition would work, however I am having trouble getting it work 100%
I initially had:
while input1 is not ("w" or "d")
where input1 would be the first input (w or d) the user enters
However, I also want to check that a number exists.
I had the idea of casting the string input to a float, then checking that but I wouldn't know how to checking if that is right since casting and checking the type wouldn't tell me much.
How would I also check that the user entered in some sort of number.
So to reiterate, I would like the program to re-prompt for input if the user did not enter either:
A) A w or d
B) A number (int/float)
Thanks
the expression ("w" or "d") will always evaluate to "w". Generally, here you want an in:
while input1 not in ("w", "d"):
...
As far as handling the case where the input is a number, this is a job for a helper function:
def string_is_number(s):
try:
float(s)
return True
except ValueError:
return False
Now you can use that with the above to put the whole thing together:
while (not string_is_number(input1)) and (input1 not in ("w", "d")): ...
Which can actually be simplified a little more:
while not (string_is_number(input1) or (input1 in ("w", "d"))): ...
And now a completely different approach, You can actually use a recursive function for this sort of thing. Combine that with python's exception handling and we could probably put together a pretty elegant solution in just a few lines:
def prog_loop():
# prompt for user's input here:
input1 = raw_input("Enter a number, or 'w' or 'd':")
# See if we got a number
try:
number = float(input1)
except ValueError:
# Nope, wasn't a number. Check to see if it was in our
# whitelisted strings. If so, break early.
if input1 in ('w', 'd'):
return function_handle_w_d(input1)
else:
# Yes, we got a number. Use the number and exit early
return function_handle_number(number)
# haven't exited yet, so we didn't get a whitelisted string or a number
# I guess we need to try again...
return prog_loop()
This will work as long as your user doesn't enter bad input 1000 times.
Try this:
while True:
if input1 == 'w':
withdraw()
elif input1 == 'd':
deposite()
else:
continue()

Output Daffodils-Numbers with python

I want to write a python program, first it asks you to enter two numbers, and then output all daffodil numbers between the two numbers, and it will continue run, until I enter a "q". I write a program, but it is wrong:
#coding=utf-8
while 1:
try:
x1=int(raw_input("please enter a number x1="))
x2=int(raw_input("please enter a number x2="))
except:
print("please enter only numbers")
continue
if x1>x2:
x1,x2=x2,x1
pass
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print ("%-5d")%n
pass
Can somebody help? I think it should be simple, but I am not able to write it correctly.
I believe you've misunderstood the problem statement. Try this instead:
if i*100+j*10+k==i**3+j**3+k**3:
ref: http://en.wikipedia.org/wiki/Narcissistic_number
for n in xrange(x1,x2):
digits = map(int,str(n))
num_digits = len(digits)
if sum(map(lambda x:x**num_digits,digits)) == n:
print "%d is a magic number"%n
you will still have the issue of not being able to enter "q" since you force the input to be integers
I would like to address the quit event.
while True:
x1 = raw_input("please enter a number x1=")
x2 = raw_input("please enter a number x2=")
quit = ('q','Q')
if x1 in quit or x2 in quit:
break
else:
try:
x1, x2 = int(x1), int(x2)
except:
print("please enter only numbers")
continue
# The mathematical part... (for completeness) (not my code)
if x1>x2:
x1,x2=x2,x1
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print "%-5d"%n
The pass statement is used only when you don't have anything to be executed in certain block of code. It does nothing more, so don't use it if not needed. It is there for the sake of the code looking clean & with correct indentation.
if some_thing: # don't do anything
else:
some_thing = some_thing_else
Note how the above if statement is syntactically incorrect. This is where pass comes handy. Say, you decide to write the if part later, till then you must provide pass.
if some_thing: # don't do anything
pass
else:
some_thing = some_thing_else
It's a bit tricky to know what's going on without more hints, but some issues I see right off:
You need to be consistent with indentation in Python. Your last if statement is less indented than statements above it (like the previous if and the for loop). This will cause an error. You're also using different amounts of indentation in other places, but since it's not inconsistent that's allowed (if a bad idea). Its usually best to pick one indentation standard (like four spaces) and stick with it. Often you can set your text editor to help you with this (turn on "Expand tabs to spaces" or something in the settings).
You've got two pass statements where they're unneeded or harmful. The first, after the line that has if x1>x2: x1,x2=x2,x1 is going to cause an error. You can't have an indented "suite" of code if you've put a series of simple statements on the end of your compound statement like an if. Either put the assignment on its own line, indented, or get rid of the pass. The last pass at the end of the code is not an error, just unnecessary.
You're missing a colon at the end of your try statement. Every statement in Python that introduces an indented suite ends with a colon, so it should be easy to learn where they're needed.
while True:
x1 = raw_input("please enter a number x1=")
x2 = raw_input("please enter a number x2=")
quit = ('q','Q')
if x1 in quit or x2 in quit:
break
else:
try:
x1, x2 = int(x1), int(x2)
except:
print("please enter only numbers")
continue
if x1>x2:
x1,x2=x2,x1
pass
for n in xrange(x1,x2):
i=n/100
j=n/10%10
k=n%10
if i*100+j*10+k==i+j**2+k**3:
print ("%-5d")%n
pass
i have it! thx to Ashish! it is exactly what i want! and i will quit wenn i enter q! thx a lot!

Getting user input and making a decision

I start my python script asking the user what they want to do?
def askUser():
choice = input("Do you want to: \n(1) Go to stack overflow \n(2) Import from phone \n(3) Import from camcorder \n(4) Import from camcorder?");
print ("You entered: %s " % choice);
I would then like to:
Confirm the user has entered something valid - single digit from 1 - 4.
Jump to corresponding function based on import. Something like a switch case statement.
Any tips on how to do this in a pythonic way?
Firstly, semi-colons are not needed in python :) (yay).
Use a dictionary. Also, to get an input that will almost certainly be between 1-4, use a while loop to keep on asking for input until 1-4 is given:
def askUser():
while True:
try:
choice = int(input("Do you want to: \n(1) Go to stack overflow \n(2) Import from phone \n(3) Import from camcorder \n(4) Import from camcorder?"))
except ValueError:
print("Please input a number")
continue
if 0 < choice < 5:
break
else:
print("That is not between 1 and 4! Try again:")
print ("You entered: {} ".format(choice)) # Good to use format instead of string formatting with %
mydict = {1:go_to_stackoverflow, 2:import_from_phone, 3:import_from_camcorder, 4:import_from_camcorder}
mydict[choice]()
We use the try/except statements here to show if the input was not a number. If it wasn't, we use continue to start the while-loop from the beginning.
.get() gets the value from mydict with the input you give. As it returns a function, we put () afterwards to call the function.

Categories