How do you make consecutive if statements? - python-3.x

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

Related

Found error "not all arguments converted during string formatting" in Python

I found an error that says
File "", line 6, in
TypeError: not all arguments converted during string formatting"
while I'm trying to implement a while True loop in Python. I am trying to identify even and odd numbers with Python. Any suggestion for my problem?
Here's my code:
print("Identification Odd/Even number")
while True:
input = input ('Enter The Number ')
if input %2==0:
print("Even")
elif input %1==1:
print("Odd")
next_step = input ('Do you want indetify again? (Yes/No)')
if next_step == 'No' :
break
else:
print('You have input the wrong format')
The first thing you should not do is, that mixing variable names with function names. The line input = input('Enter number here: ') means that in the first pass the function input() will no longer be the function you want it to be, instead it will be string you got back from the first loop-pass.
Also you want to go on with some calculations. input (the function) will return a string, not an integer.
In order to get an integer from a string you should do a cast user_input = int(input('Enter number here: ')).
user_input is a integer and you can go on with you modulos operations.
So all in all I suggest based on your code:
change the variable name input to something else
do a cast after retrieving the user first user-input
for checking if a given number is odd or even there are only two cases to cover, which you can express with if-else-case.
input % 1 == 1 will always be False because there is no integer that is not divisible by 1.
If you want to continue to ask the user if he wants to go on, you probably want the user to give an answer you specified.
This will need another while-loop.
Why?
If the user gives an arbitrary answer, you want to continue to ask as long as the user gives an apropriate answer.
This is an answer you explicitly asked for.
To do that I have done something like this:
next_step = None
allowed_answers = ['No', 'Yes']
while next_step not in allowed_answer:
next_step = input('Want to go on? (Yes/No)')
If you want to give feedback to the user, something like this solved this riddle for me:
allowed_answers = ['No', 'Yes']
while True:
next_step = input('Want to go on? (Yes/No)')
if next_step not in allowed_ansers:
print('You have input the wrong format')
else:
break
All in all I would do something like this:
allowed_answers = ['No', 'Yes']
while True:
user_input = int(input('Enter The Number:'))
if user_input % 2 == 0:
print("Even")
else:
print("Odd")
next_step = None
while next_step not in allowed_answer:
next_step = input('Do you want indetify again? (Yes/No)')
if next_step == 'No' :
break

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

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 can I make the if statement contain more than one item?

I am extremely new to python and programming in general so please excuse my stupidity. But can I make if be able to search for more than one thing? so like..
choice = input()
if choice == "Yes" or "Sure" or "Yep":
print("You chose yes")
elif choice == "No" or "Nah" or "Nope":
print("You chose no")
And don't worry I know the or command isn't used correctly here because I've tried it and it obviously doesn't work, so how can i make it work?
Please explain how and why it works like this as you must remember I'm new to this stuff, so basically ELI5.
Cheers.
For starters you can go with
choice = input()
if choice == "Yes" or choice == "Sure" or choice == "Yep":
print("You chose yes")
elif choice == "No" or choice == "Nah" or choice == "Nope":
print("You chose no")
Why your code didn't work:
In the condition
if choice == "Yes" or "Sure" or "Yep":
each part separated by or will evaluate to a boolean value.
"Sure","Yep" will always evaluate to true
>>> bool("Sure")
True
You can try like this:
choice = input()
if choice in {"Yes", "Sure", "Yep"}:
print("You chose yes")
elif choice in {"No", "Nah", "Nope"}:
print("You chose no")

Resources