If condition is "None" the loop starts somewhere else than I want - python-3.x

I try to code my first little text based role play game.
The first step would be to enter your character name and then type "y" if you are fine with the name and "n" if you want to change the name.
So I want that the Program is asking you again to enter "y" or "n" if you fatfinger a "g" for example. And only let you reenter your name if you type "n"
Instead of these the program will let you reenter your name directly if you enter "g".
I already tried to do a "while True or False" loop around the _yesorno function.
Here is the code:
main.py
from Classes.character import character
from functions.yesorno import _yesorno
#character
char = character()
while True:
print("please enter a name for your character")
char.set_name(input())
print("Your name is: " + char.name + ". Are you happy with your choice? Type 'y' for yes, 'n' for no.")
if _yesorno(input()):
break
else:
continue
_yesorno.py
def _yesorno(input:str)->bool:
if input == "y":
return True
elif input == "n":
return False
else:
print("please use y for yes and n for no")
return None
As I am pretty new I would be happy, if you can explain your answer newbie friendly and not only with "your logic is wrong" :D
Thanks in advance!

if None is equal to while if False. Python have dynamic typing for types.
To check wrong input you can do things like:
def _yesorno(input_:str)->bool:
while input_ not in ['y', 'n']:
print("please use y for yes and n for no")
input_ = input()
return input_ == 'y'
That code check input directly instead itself. input_ not in ['y', 'n'] that part check if your input_ is one of array element.
After user enter 'y' or 'n' the function return proper result.

I would approach this with a pair of recursive functions. One that ran until the user gave a valid response, the other until a name was properly set.
Note that in many cases, recursive functions can be rewritten as loops and since python lacks tail call optimization, some people will prefer not using recursion. I think it is usually fine to do so though.
def get_input_restricted(prompt, allowed_responses):
choice = input(prompt)
if choice in allowed_responses:
return choice
print(f"\"{choice}\" must be one of {allowed_responses}")
return get_input_restricted(prompt, allowed_responses)
def set_character_name():
prospective_name = input("Enter a name for your character: ")
print(f"Your name will be: {prospective_name}.")
confirmation = get_input_restricted("Are you happy with your choice (y|n)? ", ["y", "n"])
if "y" == confirmation:
return prospective_name
return set_character_name()
character_name = set_character_name()
print(f"I am your character. Call me {character_name}.")

The reason why an input of 'g' is making the user reenter their name is because 'None' is treated as False therefore the loop will continue... you could try a simple if statement in a while loop and disregard your _yesorno function with
while(True):
print("please enter a name for your character")
charName = input()
while(True):
print("Your name is: " + charName + ". Are you happy with your choice? Type 'y' for yes, 'n' for no.")
yesorno = input()
if(yesorno == 'y' or yesorno == 'n'):
break
if(yesorno == 'y'):
break
char.set_name(charName)
print("and your name is {0}".format(char.name))

Related

If, elif and else - ask only for strings, continue the loop if the user enters a number

I have been wondering this for a longer time
If I check for user input, I know how to check for strings.
But what if I want to check if the user has entered just integers or floats. I tried it with an "if name == int or float: block but of course that didn't work. Can you help me out?
How do I check for that? Here is my code. Of course the input I always converted to a string so I don't know how to do that.
print("Enter a name: ")
while True:
name = input()
if name != "":
print("Thank you for entering a name: ")
break
else:
print("Please enter a name: ")
I also tried this:
print("Enter a name: ")
while True:
name = input()
if type(name) != int:
print("Thats not a name!")
print("Now please enter a name without numbers")
elif type(name) != float:
print("Thats also not a name!")
print("Now please enter a name without numbers")
elif type(name) != "":
print("Thank you for entering your name!")
break
else:
print("Please enter a name: ")
For int you can use the isnumeric() method
"1".isnumeric() #True
For float, you should try if casting to float is possible
def isFloat(num):
try:
float(num)
return True
except ValueError:
return False
Now use both these methods :
print("Enter a name: ")
while True:
name = input()
if name.isnumeric() or isFloat(name):
print("Thats not a name!")
print("Now please enter a name without numbers")
elif type(name) != "":
print("Thank you for entering your name!")
break
else:
print("Please enter a name: ")
Output :
Enter a name:
1
Thats not a name!
Now please enter a name without numbers
1.2
Thats not a name!
Now please enter a name without numbers
abc
Thank you for entering your name!
Edit: This might help.
def hello(userinput):
if userinput.isdigit():
print("You entered a number. That's not valid!")
else:
print("You entered a valid name.")
Old Solution
print("Enter a name: ")
while True:
name = input()
if type(name) != int:
print("Thank you for entering a name: ")
break
else:
print("Please enter a name: ")
Also I can understand why you did that.
The previous code you created meant that if the user typed the class int. This will be impossible to type a class because input() only takes a string from the user's input.
To check if a variable is of a type, simply use if type(VARIABLE) == TYPE: where "VARIABLE" is your variable and TYPE is your type (such as int, float, str, etc.).
In your code, however, you may want to use str.isnumeric() as it will return True when there are numerical values in the string. To check if ANY characters are numeric, do if all([not char.isnumeric() for char in list(STRING)]): where "STRING" is your user's input. This checks if every character in the string is not numeric and returns True when this is the case.

How to separate if statements and exit code to execute the program properly?

I was doing beginner python projects as I am a beginner still. I came upon this guessing game project and Wanted to do a Yes or No type of question on whether the user wants to take part in guessing or not.
If user enters Yes, they take part, if anything else ("No" or anything the program exits the code)
However I seem to be doing something wrong, when I enter Yes, the program exits the code anyway. What am I doing wrong? Thank you all,
Here is the code. I am only posting a part of it, where I most probably get the error.
import random
guess = 0
name = input("Hello what is your name?: ")
num = random.randint(1 , 50)
response = input("Well hello there " + name + " I have a number between 1-50, Want to play? You have 10 tries")
if response != "Yes" and response != "yes":
exit()
else:
while guess <= 10:
guess += 1
take = int(input("Guess a number!"))
if take == num:
print("You win! You guessed " + str(guess) + " times")
elif take > num:
print("Too high!")
elif take < num:
print("Thats too low!")
elif take >= guess:
print("You lose... The number was "+ num)
if response != "Yes" or "yes":
equates to this:
if response != "Yes" # which resolves to False when response is a 'no'
OR
"yes" # which is a non-empty string, which Python equates to True.
So basically, you code is equivalent to:
if False OR True:
and thus it always runs the exit() function.
In addition to the items noted above, the if statement should be checking both conditions and thus it should be using and instead of using or, as shown below (HT to #tomerikoo):
What you need is TWO separate tests in the if statement:
if response != "Yes" and response != "yes":
If you believe that you might have other versions of yes answers OR if you think that doing a comparison against a general sequence of terms might be easier to understand, you can also do this test instead:
if response in ['Yes', 'yes', 'y', 'Y', 'YES']:
Debugging:
For folks who are new to programming, in Python, it is sometimes fast and easy to use a simple print() function to rapidly evaluate the current state of a variable, to ensure that it really points at the value you believe it does. I added a print statement below with a comment. It would be beneficial to see what value is associated with response. (Caveat: there are professional tools built into Python and into code editors to help with watching variables and debugging, but this is fast and easy).
import random
guess = 0
name = input("Hello what is your name?: ")
num = random.randint(1 , 50)
response = input("Well hello there " + name + " I have a number between 1-50, Want to play? You have 10 tries")
print(response) # checking to see what was actually returned by the
# input() method
if response != "Yes" and response != "yes":
print(response) # check to see what the value of response is at
# the time of the if statement (i.e. confirm that
# it has not changed unexpectedly).
exit()
else:
while guess <= 10:
guess += 1
take = int(input("Guess a number!"))
if take == num:
print("You win! You guessed " + str(guess) + " times")
elif take > num:
print("Too high!")
elif take < num:
print("Thats too low!")
elif take >= guess:
print("You lose... The number was "+ num)
In python "non-empty random str" is True and empty string "" is False for conditional usages. So,
if "yes":
print("foo")
prints 'foo'
if "":
print("foo")
else:
print("bar")
prints 'bar'
In your case you want program to exit if response is not "Yes" or not "yes". You have two conditions evaluated in if statement:
response == "Yes" --> False
"yes" --> True
if 1 or 2 --> True --> so exit.
so it should be like that:
if response not in ["Yes", "yes"]:
exit()
else:
do_something()

Simple Python 3.4.3

I'm a beginner (only coding for 14 weeks) and I'm so confused as to what's happening here. All I want to do is ask a simple question and print back another print statement, but no matter what, it always answers "you said yes!". Someone please help me.
input("This Python program will ask you a series of questions. Are you Ready? ")
if input == "Yes" or "y":
print("You said yes!")
elif input == "No" or "n":
print("You said no!")
else:
print("You said neither.")
You have multiple issues in your code.
First, the string you get from the input method isn't store anywhere. Try printing the input"variable", and you will get :
<built-in function input>
Instead, store the output of the input method in a variable and use this variable instead of input.
Second issues, your tests. When you write if input == "Yes" or "y":, I guess you want to test if the string is equal to "Yes" or to "y". But in reality, the test happening can be written :
if (input == "Yes") or ("y"):
Your test is then composed of two parts : the first test is correct, but the second one is just test if "y", which is always true since the string "y" is not null.
You should replace it by :
if input == "Yes" or input == "y":
Or even simpler :
if input in ("Yes", "y"):
To conclude, the final code is simply :
str = input("This Python program will ask you a series of questions. Are you Ready? ")
if str in ("Yes","y"):
print("You said yes!")
elif str in ("No","n"):
print("You said no!")
else:
print("You said neither.")
First, you want to store the input in a variable:
string = input(...
Then, you have to repeat input == "y" for the second of or conditions:
if string == "Yes" or string == "y":
or
if string in ("Yes", "y"):

How do you make consecutive if statements?

I have been learning to code in python and I've come up with a good idea for a program. The basis is the following:
if input() == 'unnamed variable':
print('this')
if input() == 'another unnamed variable'
print('this other response')
I cannot type in another unnamed variable without first satisfying the first if statement
I want my program to print something different for the user to read based on the input
How do I used consecutive if statements? I've tried elif and else. Am I able to have say 80 if statements back to back?
Any help will be greatly appreciated, thanks in advance
If you want to do different things depending on the user input, then first of all, you should only ask the user to enter things once. So you should only call input() once and save the response to a variable:
response = input()
Then, you can use if, elif and else to check multiple different conditions and do different things each time:
if response == 'some input':
print('User entered some input')
elif response == 'some other input':
print('User entered some input')
elif response == 'some even more different input':
print('User entered some even more different input')
else:
print('User entered something I do not recognize')
So you only ask the user once and store the response, and then you compare the response against a number of different values: If one of the conditions is true, that part is executed and the remaining conditional checks are skipped.
You can replace nested if -elif-elif-else by 'or'
if cond1 or cond2 or cond3
You can replace nested if-if-if by 'and'
if cond1 and cond2 and cond3
it may help you in redesigning big if-else chain
You can define the input, and then check for equality.
userInput = input(" > ")
aNumber = 5
if userInput == 'y' or userInput == 'yes':
print("You said yes!")
elif userInput == 'no':
print("You said no.")
elif userInput == 'maybe' and aNumber == 5:
print("you said maybe, and aNumber is equal to 5!")
else:
print("I can't understand you.")

Python if statement not working as it should

Just to clarify, I have pasted my whole program as the problem can only be identified when it is with all the code in my program. My problem is, I have in-putted if else and elif statements in my program. When the user inputs "no" the program ends, and this runs fine and if the user inputs "yes" the program advances like it is supposed to do. The problem is when the user will input something invalid, something other than "yes" or "no" it should take them back to retyping their option but instead it carries on as if the user has inputted "yes".
while True:
print (" Position Finder")
choice = (input("Do you want to run the Position Finder program? Please enter yes or no!"))
# Lets the user input an answer to question I am asking it
if choice.lower() == "no":
# If the user input is "no"
print("The program will not run")
# This statement will be printed out and the program will not run
quit()
elif choice.lower() == "yes":
# If the user input is "yes"
print("The program will now run")
# This statement will be printed and the program will run
else:
# If an invalid statement is inputted
print("Invalid entry, please type again")
# This statement will be printed and the user will be given the option to input again
sentList = "ask not what your country can do for you ask what you can do for your country"
# Creates a list
sentList2 = sentList.split()
# This will split the list and give each word a position
print (sentList)
# This will print out the sentence in the program
word = (input("Enter Word: "))
# Lets the user input a word from the sentence
wordFound = False
# This boolean statement, "wordFound" will be set to true when the word has been found in the list
for (num, x) in enumerate(list(sentList2)):
# For every word in the users sentence
while word.lower() == x:
# While the users word is equal to the position in the sentence
print (ordinalSuffix())
# Print the ordinal suffix function
wordFound = True
# This boolean statement has been set to true as the word has been found in the list
break
# This will break the while loop from the boolean variable called "wordFound"
if wordFound == False:
# If the word has not been found in the list and the "wordFound" boolean variable has not been set to true
print ("Please enter a word from the sentence")
# This statement will print,meaning the user has to enter a word from the list
You may use continue keyword.
The continue statement, also borrowed from C, continues with the next
iteration of the loop:
while True:
print (" Position Finder")
choice = (input("Do you want to run the Position Finder program? Please enter yes or no!"))
if choice.lower() == "no":
print("The program will not run")
quit()
elif choice.lower() == "yes":
print("The program will now run")
else:
print("Invalid entry, please type again")
continue # move to next iteration
rest_of_your_code()
You only wrote a print statement in the else clause: print("Invalid entry, please type again"), but that does not make the program repeat the previous instructions. A possible solution:
choice = ""
while choice.lower() != "yes":
choice = (input("Do you want to run the Position Finder program? Please enter yes or no!"))
if choice.lower() == "no":
print("The program will not run")
quit()
elif choice.lower() == "yes":
print("The program will now run")
else:
print("Invalid entry, please type again")
You need to put one while loop more for that, returning the user in syntactically wrong answer and breaking loop in right answer. The question part should look like this:
while True: # Main loop
while True: # Question loop
choice = (input("Do you want to run the Position Finder program? Please enter yes or no!"))
if choice.lower() == "no":
print("The program will not run")
run = False
break
elif choice.lower() == "yes":
print("The program will now run")
run = True
break
else:
print("Invalid entry, please type again")
# In case of invalid entry Question loop will run again
# Outside Question loop
# Let's check if we should run the program
if not run:
break
# This will be executed if *run* is False, it will break the Main loop
# Your program

Resources