Simple Python 3.4.3 - python-3.x

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

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

Issue with checking ranges in if statement

I'm new to python and doing a cyber sec. course, one of the modules is Python.
I am playing around trying to code a number guesser game without a tutorial. Can someone look at this code and tell me why the code doesn't seem to be following the if statements.
Thanks.
EDIT: ERROR: I am trying to create code that will judge which "difficulty" the player has selected by checking which of the ranges it fits into. The issue is, it is printing each of the "difficulty" options, not just the one it fits in to.
EDIT 2: Changed title to be more specific so it may help others.
print("Welcome to the number guesser game!")
tutorial = input("Would you like a tutorial? (Y/N): ")
while tutorial != "Y" or "y" or "N" or "n":
input("Input not recognised, would you like a tutorial? Y (for yes) or N (for no)")
if tutorial == "N" or "n":
print("Let's get right into it!")
if tutorial == "Y" or "y":
print("In this game you will pick a number, the number you pick will be added to a random number between 1 and 20 /nYou will then attempt to guess the number generated, with a hint given every guess")
break
difficulty = input("Please choose a random number \nGuide:\nEasy 1-10\nMedium 1-100\nHard 1-1,000\nExtreme Numbers above 1,000-10,000")
if difficulty >="1" <="10":
print("You have chosen easy! You must be a noob!")
if difficulty >"10" <="100":
print("You have chosen medium! Good choice!")
if difficulty >"100" <="1000":
print("You have chosen hard! Pfft, good luck")
if difficulty >"1000" <="10000":
print("You have chosen extreme! You must be nuts")
if difficulty <="0" >"10000":
difficulty = input("Nice try, pick again: ")
else:
difficulty = input("Input not recognised, please input a number greater than 0: ")```
Explanation
That's because first, if the input is not y, then it will say not recognized.
And it's because, if it's y, it checks the no statement, then it breaks.
That means, It will say both.
Then, it goes strange because you are doing >= with str and str. It will react strange. so you should compare int with int.
Solution
First, use and in the first statement. then, use elif. and use break in the if statement too. and do int(input()) to convert to int. then, you can use elif again. and remove the quotes.
Try this:
print("Welcome to the number guesser game!")
tutorial = input("Would you like a tutorial? (Y/N): ")
while True:
if tutorial != "Y" and tutorial !="y" and tutorial !="N" and tutorial !="n":
tutorial = input("Input not recognised, would you like a tutorial? Y (for yes) or N (for no)")
if tutorial == "N" or tutorial =="n":
print("Let's get right into it!")
break
elif tutorial == "Y" or tutorial == "y":
print("In this game you will pick a number, the number you pick will be added to a random number between 1 and 20 /nYou will then attempt to guess the number generated, with a hint given every guess")
break
difficulty = int(input("Please choose a random number \nGuide:\nEasy 1-10\nMedium 1-100\nHard 1-1,000\nExtreme Numbers above 1,000-10,000"))
if difficulty >=1 and difficulty <=10:
print("You have chosen easy! You must be a noob!")
elif difficulty >10 and difficulty<=100:
print("You have chosen medium! Good choice!")
elif difficulty >100 and difficulty<=1000:
print("You have chosen hard! Pfft, good luck")
elif difficulty >1000 and difficulty<=10000:
print("You have chosen extreme! You must be nuts")
elif difficulty <=0 and difficulty >10000:
difficulty = input("Nice try, pick again: ")
else:
difficulty = input("Input not recognised, please input a number greater than 0: ")
And for the while loop, turn it to while True: then check it with a if statement. then you can check y or n.
First off in the while loop to check if the variable tutorial is "Y" or "y" or "n" or "N" you're doing tutorial != "Y" or "y" or "N" or "n", which is incorrect because it's saying if (tutorial != "Y") or ("y") or ("n") or ("N") and the latter 3 conditions return true because it is a non empty string.
with the if conditions there are 3 problems, first one is the one I just described, second is you're not converting the input to integer before checking, third is that you're nesting the conditions unnecessarily.
Simplify your checking, and do it in a loop so they cannot progress if they enter invalid input:
difficulty = -1
while difficulty < 1 or difficulty > 10000
try
difficulty = int(input("Please choose a difficulty.\nGuide:\nEasy 1-10\nMedium 1-100\nHard 1-1000\nExtreme 1000-10000\n: "))
except ValueError:
print("not a number")
if difficulty > 0 and difficulty <=10:
print("You have chosen easy! You must be a noob!")
elif difficulty<=100:
print("You have chosen medium! Good choice!")
elif difficulty<=1000:
print("You have chosen hard! Pfft, good luck")
elif difficulty<=10000:
print("You have chosen extreme! You must be nuts")
You don't need each elif to make sure the number is greater than the end of the range of the check before; if it wasnt then that elif would have been true, not this one. In other words, if youre playing a guessing game with another human and you say "is the number less than or equal to 10" and they say no, you don't need to say "is it greater than 10 and less than.. " because the "greater than" is implied - it has to be greater than because it isn't less than or equal to

What is the proper way to allow a capitalized "Yes" input and a non-capitalized "yes" input or value in Python? [duplicate]

This question already has answers here:
How to make user input not case sensitive?
(4 answers)
Closed 2 years ago.
'''
I am trying to allow a user to type a capital "Yes" as input or a non-capitalized "yes" as input and still get a 'True' value for the variables, good and the same with 'phone' or 'Phone' for the variable, aid.
print ('Do you want to take the Carona Test in North Carolina: Type in
"Yes or No"')
good='Yes'
aid='phone'
good = input()
if good == 'Yes':
print ('The address is 1801 Glendale Dr SW, Wilson, NC 27893. ' +
'If you need the Helpline, type "phone" and if not type in "No".')
aid = input()
if aid=='phone':
print("NC CDC Help Line 1-866-462-3821. Don't forget to wash
your hands.")
else:
print('You have elected to do nothing silly human scum, good luck.')
'''
Try something like this:
x = input('...')
if(x == 'Yes' or x == 'yes'):
print('True')
else:
print('False')
For a completely case insensitive solution, cast the user input to lower or upper case.
if input('Do you want the Coronavirus test in NC?').lower() == 'yes':
print('Instructions here')
else:
print('Okay')

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