Python: Loop not exiting with "break" - python

I have this while loop that is testing to make sure the user inputs either 1, 2, or 3. Once the user inputs 1, 2, or 3, the loop keeps going infinitely, i can't get out of it.
while True:
try:
filterselection = raw_input("Please select a filter (1, 2, or 3): ")
if filterselection == "1" or filterselection == "2" or filterselection == "3":
filterselection = int(filterselection)
break
else:
print "Not a valid number try again!"
except TypeError:
print "Lol, that's not a number try again!"

Don't mix tabs and spaces! Here is what I see when pasting your original code into an editor that displays whitespace characters:
The arrows are tabs and the dots are spaces, it is very important that you don't mix these because if you do the code that you see might not be what the Python interpreter sees.

Related

While loop keeps taking input even after condition is satisfied

By using the while loop get numbers as input from the user and add them to the list. If the user enters 'done' then the program output maximum and minimum number from the list.
This code also includes the error message using the 'try and except' block for wrong inputs.
nums = list()
while(True):
x = input("Enter a Number: ")
if x == "done":
break
try:
inp = float(x)
nums.append(inp)
except:
print("Enter only numbers or type 'done'")
continue
print("Maximum: ", max(nums))
print("Minimum: ", min(nums))
Input: 1, 2, 3, 4, er, done,...
Issue: 'er' input did not call except block, instead kept taking inputs. Somehow the Program was still running even after typing 'done' and kept taking input.
Tried: Added print(x) after line:3 but did not get any output for that either.

How to avoid my program stopping because of a invalid index number when calling a tuple

I'm trying to make a pokémon text based journey in python.
I listed the starter pokémon in a tuple to call the number that the user typed in the input to then store the chosen starter pokémon.
It all works but when the user would type a different integer then availabe in the tuple, for example: writing 5 while there are only 3 indexs in the tuple. The program just stops when this happens.
Is there a way for me to just tell the program to not go into debugging mode when this happens; and recalling the "ChoseStarter" function instead?
Here is the code:
if(ChosenPok == 1,ChosenPok == 2,ChosenPok == 3):
ChosenPokInt = int(ChosenPok)
StarterPok = Starter[ChosenPokInt-1] #Here is the problem
Sure = f"You chose {StarterPok} are you sure? (y/n)"
YORN = input(Sure)
if(YORN == "Y" or YORN == "y"):
Congrats = f"Congratulations!! You just got a {StarterPok}!!"
WriteFast(Congrats)
print(Starter[ChosenPokInt-1])
else:
WriteFast(ERROR)
ChoseStarter()
No idea what the question is about or what logic you want to implement. See if the below code helps though. Seems like the "if condition" is buggy in your case. The following code repeatedly asks for the correct input using a while loop. Replace the while loop with an if statement if you don't want that.
starter = ["x", "y", "z"]
chosen_pok = int(input("Select a pok: "))
while not (1 < chosen_pok < 4):
print("Invalid pok. try again...")
chosen_pok = int(input("Select a pok: "))
starter_pok = starter[chosen_pok - 1]
yorn = input(f"You chose {starter_pok} are you sure? (y/n)")
if (yorn in ["Y", "y"]):
print(starter[chosen_pok - 1])
else:
print("Error")
You should just check for the len and if ChosenPokInt is in it's boundaries:
pokemon_index = ChosenPokInt - 1
if 0 <= pokemon_index < len(Starter)-1:
# everything is fine
else:
# handle the problem case
Besides that I advice you to look into pep8 :). You can find an awesome guide here: https://pep8.org
You can add a while loop before the condition that checks first if the input is in the correct range:
ChosenPok = ChoseStarter()
pokRange = [1, 2, 3]
while not (ChosenPok in pokRange):
print("Wrong input, try again")
ChosenPok = ChoseStarter()

Using If Else statements in addition to sets using Python

I have to create a fortune teller for school. I want the user to input a number between 1-9. But i also want to give an error message if they put in a different number. I'm using a set containing my numbers, but I can't call it in my if statements.
fortune_num = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
user_num = input(f'Pick a number and find your fortune! Choose a number from 1 to 9 and hit enter: ')
print()
if user_num == fortune_num:
print(user_num)
else:
print('Error')
Use the keyword in to check set membership, also cast input into int:
fortune_num = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
user_num = input(f'Pick a number and find your fortune!
\nChoose a number from 1 to 9 and hit enter: ')
print()
if int(user_num) in fortune_num: #this would throw an error if input is not int
print(user_num)
else:
print('Error')
You can use this code,
fortune_num = list(range(1,10))
user_num = input(f'Pick a number and find your fortune!\nChoose a number from 1 to 9 and hit enter: ')
if int(user_num) in fortune_num:
print(user_num)
else:
raise ValueError("You entered a wrong input!")
This would raise an actual Python error if the input is wrong.
If you want to give the user another chances to enter a correct input use this,
fortune_num = list(range(1,10))
while True:
try:
user_num = int(input(f'Pick a number and find your fortune!\nChoose a number from 1 to 9 and hit enter: '))
if user_num in fortune_num:
print(user_num)
break
else:
raise ValueError
except:
print("\nYou entered a wrong input. Please enter a valid number!")
Change the code as per your needs but this would do work as the perfect foundation.
First of all, input takes user input as a string. So even if they enter 1, that won't match your set, because your set is of int, and their input is the string '1', not the integer 1. Also, there's no need to use a set. A range object is easier to generate, and since it contains multiple numbers, the variable name should be plural. You also don't have your indentation correct. I don't see what the f in the input function is doing, and if you want a multi-line string, you need triple quotes. Also, if you have a carriage return in your string, putting \n in the string gives you two line breaks; I'm not sure that's intended. So one way of doing this is:
fortune_nums = [str(num) for num in range(1,10)]
user_num = input('''Pick a number and find your fortune!
Choose a number from 1 to 9 and hit enter: \n''')
print()
if user_num in fortune_nums:
print(user_num)
else:
print('Error')
If you want to get fancier, you can keep your fortune_nums as int, then do a try-except on converting the input to int, catching the invalid literal error:
fortune_nums = range(1,10)
user_num = input('''Pick a number and find your fortune!
Choose a number from 1 to 9 and hit enter: \n''')
print()
try:
if(int(user_num) in fortune_nums):
print(user_num)
except ValueError:
print("That's not a valid integer!")
if user_num == fortune_num: // instead of this; you can use keyword in int(user_num) in fortune_num:,
Also your print statement must be indented, otherwise you might get indentation error.

Python is there a way to hide a programm

program, info = input ("->") .split ()
if program == 'search':
print (info)
elif program == 'hello':
print ("do")
else:
print ("Error")
In this example, the input is split.
E.g.
search youtube.com
Output:
youtube.com
But now I would also like to manage that you can only enter 1 word and it still works.
Such as.
elif program == 'hello':
that means I only type in hello and it works too.
then the output should be:
do
but only one word doesn't work at the moment, how do I get that?
You could add an asterisk to the info variable:
program, *info = input("->").split()
if program == 'search':
print(info[0])
elif program == 'hello':
print("do")
else:
print("Error")
This result in info being a list of everything after the first element of the split input. If you enter search youtube.com, the variable info will contain ['youtube.com']. If you enter hello, the variable info will contain nothing, i.e. [].
Note that I also added a list access to the info variable in line 4, where it is printed.
More information on how to solve this and/or why this works can be found here, where default values in unpacking are discussed.
Edit: As #Steve pointed out, this becomes problematic if only search is entered, because you'd try to access the first element of an empty list. To prevent this, you can add an extra check to your code:
program, *info = input("->").split()
if program == 'search':
if not info:
print("Error, nothing to search for")
else:
print(info[0])
elif program == 'hello':
print("do")
else:
print("Error")
Simply check the size of the input before assigning the variables:
data = input("->").split()
if len(data) == 2:
program = data[0]
info = data[1]
elif len(data) == 1:
program = data[0]
else:
print("invalid number of arguments")

Basic Python If Statements Using "or"

I am following a beginner program for learning python. I am struggling to find a better way to use an "if" statement with multiple possibilities. I am writing a basic text based game in which the user is able to choose three different difficulty levels: Easy, Medium, Hard. I am just trying to write code that takes in a 1, 2, or 3 to tell the program which level to run. I want to make sure the user input is one of those options, not "4" or "one".
Here is the relevant code I have written:
selected_level = 0
selected_level = raw_input("\n Please select a level by entering 1, 2, or 3 : ")
print selected_level
if selected_level == 1 or selected_level == 2 or selected_level == 3:
print "Pass"
else:
print "Fail"
break
All I am trying to do right now is test that the "if" statement works. However, no matter what input I enter it will print the input and then print "Fail" which tells me it is never entering the first part of the "if" statement.
I have tried testing this with inputs 1, 2, 3, 4, one, etc and it always skips to the "else" statement. Is there a better way to write an "if" statement with multiple or values?
Your issue is that raw_input returns a string, but the if-statement is comparing to ints.
"1" does not equal 1.
Try checking if selected_level == "1" ... "2"... etc. and it should work.
I would compare to strings instead of casting the input to an int, as that will crash the program if the user types something unexpected.
Also for a more succinct check:
if selected_level in ("1", "2", "3"):
print "Pass"
raw_input returns a string. Try int(raw_input(...))
The reason it keeps skipping down to the if statement is because it is comparing the string that you entered to the numbers 1, 2, etc and not to the string value of 1 and 2. If you want to take the numeric value of the input you could do something like:
selected_level = int(raw_input("\n Please select a level by entering 1, 2, or 3 : "))
This will take the integer value of whatever the user inputs.
raw_input (in Python 2.x) returns a str. so selected_level is a str, not int. You must parse it to int before compare it woth int values
selected_level = 0
selected_level = int(input("\n Please select a level by entering 1, 2, or 3 : "))
print selected_level
if selected_level == 1 or selected_level == 2 or selected_level == 3:
print "Pass"
else:
print "Fail"
break

Categories

Resources