Python if statement not working as it should - python-3.x

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

Related

If condition is "None" the loop starts somewhere else than I want

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))

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()

limiting the number of character

i would like to know how to put limit on how many character can player put
thinking to limit it by one letter per answer.
it's a guessing game but the computer can only answer yes or no.
five chances to guess a letter.
then need to guess the right word after 5 tries.
import random
words = dict(
helium = "type of element",
korea="a country in asia",
peugeot="brand of a car",
bournemouth="a good place for holiday")
word=list(words)
choice=random.choice(word)
x=list(choice)
score=0
chance=5
print("\n\n\t\t\t WELCOME TO GUESSING GAME")
print("\t\t\tYOU HAVE 5 CHANCES TO GUESS THE WORD")
print("\nit has a", len(choice),"letters word")
print("and this is a clue", (words[choice]))
while word:
guess = input("is there a letter :")
if guess in choice:
print("yes")
else:
print("no")
score +=1
if score == chance:
print("time to guess the right word")
guess = input("and the word is :")
if guess == choice:
print("well done you guess the right word which is ", choice.upper())
break
else:
print("better luck next time the right word is ", choice.upper())
break
Hope this is what you want:
First you should make a new function:
def own_input(text=""):
user_input = ""
# While the length of the input string is not 1
while len(user_input) != 1:
# Ask user for input with message
user_input = input(text)
Now you can use it like this:
a = own_input("Character: ")

Returning to my if statement

This is my first time on this site and am new to programming. I need the user to be able to input another word if they say "y". As of now the program sends them back to the while statements. Any advice would be appreciated.
print('Welcome to Word Madness!!')
vowels = list('aeioyu')
consonants = list('bcdfghjklmnpqrstvwxz')
wordCount = 0
complete = False
while not complete:
mode = input('Would you like to type Vowels, Consonants, or Quit?: ').lower().strip()
print('You chose to enter: ',str(mode))
#When user chooses to quit program will system exit
if mode == 'quit':
print('Sorry to see you go! Come back to Word Madness soon!')
import sys
sys.exit(0)
#If vowels are selected then they will be counted
if mode == 'vowels':
word = input('Please enter your word!')
number_of_vowels = sum(word.count(i) for i in vowels)
print('Your word was : ',word,'Your Vowel count was: ',number_of_vowels)
wordCount = wordCount + 1
choice = input('Do you have another word? Y/N: ').lower().strip()
if choice == 'n':
averageV = int(number_of_vowels // wordCount)
print('Your average number of Vowels was: ',averageV)
print('Thank you for using Word Madness!')
complete = True
else:
mode = 'vowels'
#If consonants are selected then they will be counted
elif mode == 'consonants':
word = input('Please enter your word!')
number_of_consonants = sum(word.count(i) for i in consonants)
print('Your word was : ',word,'Your Consonant count was: ',number_of_consonants)
wordCount = wordCount + 1
choice = input('Do you have another word? Y/N: ').lower().strip()
if choice =='n':
averageC = int(number_of_consonants // wordCount)
print('Your average number of Consonants was: ',averageC)
print('Thank you for using Word Madness!')
complete = True
#If user has no more words to enter then they are given an average
else:
mode == 'consonants'
else:
print('ERROR! INVALID INPUT DETECTED!')
From your question and the comment, I assume that you want to ask
mode = input('Would you like to type Vowels, Consonants, or Quit?: ').lower().strip()
only once. If that is the case, you can move that statement just above the while loop.
Or also, you can give an option whether user really wants to specify the mode again.
Ok,for what I understood you don't know how to go back in the code. For this you should learn how to use functions in Python.
What is a function?
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. (Definition taken from internet)
So I would suggest you to find more about functions, because it's very useful.
After learning functions you should add that:
After every
if choice =='n':
averageC = int(number_of_consonants // wordCount)
print('Your average number of Consonants was: ',averageC)
print('Thank you for using Word Madness!')
complete = True
Add
elif choice == 'n':
function()
Function() --> Calling the main function.

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.")

Resources