a = input("enter your first name ")
for i in range(len(a)):
for space in range(len(a)-i):
print(end=' '*len(a))
for j in range(2*i+1):
print(a,end = '')
print()
print()
if a == 'Allahyar' or 'allahyar':
print(a+ ' is a boomer')
elif a != 'Allahyar' or 'allahyar':
print(a+' has been sent to the pyramid realm')
in this code the if statement executes no matter what and it completely ignores the elif statement. any idea why?
Correct syntax to combine two conditions using logical or operator.
if var == "str1" or var == "str2":
You can also do it like this
if var in ["str1","str2"]:
I'll expand on my comment. The reason you're getting the if condition always triggering is because you think that what you coded should equate to: "variable a is equal to either 'Allahyar' or 'allahyar'" but in reality it will get evaluated as two separate statements like so (brackets added for clarity):
(a == 'Allahyar') or (bool('allahyar'))
A non-empty string 'allahyar' will always evaluate to True so it's impossible for this combined expression to be False.
as #pavel stated the correct code is π == 'ππ₯π₯ππ‘π²ππ«' π¨π« π == 'ππ₯π₯ππ‘π²ππ«' I just got confused so I made an elif statement but the actual code was this a = input("enter your first name ")
for i in range(len(a)):
for space in range(len(a)-i):
print(end=' '*len(a))
for j in range(2*i+1):
print(a,end = '')
print()
print()
if a == 'Allahyar' or a == 'allahyar':
print(a+ ' is a boomer')
else:
print(a+' has been sent to the pyramid realm')
there is no reason for the elif statement its just extra code to write for no reason.
Related
So (as you will probably see from my code) I am a beginner at Python (version 3.8.3) and enjoying it very much so far, and I have challenged myself on several different beginner projects. I am currently making a random string generator (i.e. a password generator, hence the use of the secrets module).
# Password Generator
import secrets, string
print("Welcome to the generator. Please specify your requirements")
print("A. All Characters;\nB. No Numbers;\nC. No Punctuation\nPlease choose the appropriate letter for your needs.")
userInput = input()
def userWelcome():
if userInput.lower() == "a":
generatePass = string.ascii_letters + string.digits + string.punctuation
print("How long do you want your string to be?")
stringRange = int(input())
print( "".join(secrets.choice(generatePass) for _ in range(stringRange)) )
elif userInput.lower() == "b":
generatePass = string.ascii_letters + string.punctuation
print("How long do you want your string to be?")
stringRange = int(input())
print("".join(secrets.choice(generatePass) for _ in range(stringRange)))
elif userInput.lower() == "c":
generatePass = string.ascii_letters + string.digits
print("How long do you want your string to be?")
stringRange = int(input())
print("".join(secrets.choice(generatePass) for _ in range(stringRange)))
else:
print("Not an option! Let's try again.")
userWelcome()
userWelcome()
However, my problem is what to do if the user inputs an incorrect option. As you can see, with the else statement I assume what they filled in does not match any of the earlier options - and so I want to try to rerun the generator again (so I try to call userWelcome again in the else statement).
However, when I type in for example 12 as input, my shell starts to output my string (Not an option Let's try again) literally a thousand times like it is stuck in a loop. I am wondering what I am doing wrong exactly.
What I have tried:
(1) So I have tried to solve this input problem first with try and except, running the except when there is a ValueError but that only works for numbers and I did not manage to rerun userWelcome()
(2) I have tried to create a elif statement in which I check the input for integers, however that also gets stuck in a loop. Code:
elif userInput.isalpha() == False:
print("Not an option! Let's try again.")
userWelcome()
Anyway, I hope that explains it well. I have been busy with this for a few hours now and I thought I'd ask this. Maybe it's a very stupid question but for me it's hard :)
TL;DR: Want to check for proper user input by running my function again, get stuck in weird loop
Thank you for your time and effort!
The code calls userWelcome() recursively, without changing the global variable userInput. The same bad string is processed again, causing the same result, which again calls userWelcome() - for ever (at least until max call depth).
You should read a new string at the beginning of userWelcome, instead of using a global variable. Also, recursion here is an overkill that confuses you. Better use a simple while loop:
while True:
userInput = ....
if ....
do something
return
elif ...
do something else
return # exit the function - breaking out of the loop
else:
print(error message)
# No return here, means the loop will continue to loop
If you want to call the function instead of loop inside, you can instead make the function return success (True) vs. failure (False), and loop that in the caller:
while not userWelcome(inputString):
inputString = read the string
def userWelcome(inputString):
if inputString == ....:
something
return True # To mark OK
elif inputString == .....:
something else
return True # To mark OK
else:
print an error
return False # To mark failure
Just avoid global variables, it is a bad practice. Pass the value through parameters, as in the code above.
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 2 years ago.
I got to write a script which replaces certain things in a .txt file with a specific variables from input() and then it should create a new .txt with exact same content except the things replaced.
I have a few conditions:
Which compares line content from original .txt with a specific strings and if it's equal, it then replaces the string with replaced one and writes this new string to a new .txt file.
Basically, I must copy\paste original file with a few touches. But when it comes to the test stage, the whole config would be rewritten with only first condition stated in the build_config() function. And If you run my script, you would see that the LACP condition is not working at all, it writes the content in whichever way, when it should only write it if the LACP variable equals to "y".
What's going on? Here is my code:
def build_config():
base_config = open("MES2428B.txt", 'r')
for line in base_config:
complete_config = open(location + ".txt", 'a')
complete_config.write(line)
line.replace("location", "location"+location)
complete_config.close()
base_config.close()
if lacp == "y" or "Y" or "Π" or "Π½" :
base_config = open("MES2428B_lacp.txt", 'r')
for line in base_config:
complete_config = open(location + ".txt", 'a')
complete_config.write(line)
base_config.close()
complete_config.close()
print("LOCATION:")
location = input()
print("VLAN:")
vlan = input()
print("Adress:")
ip = input()
print("LACP NEEDED? y/n")
lacp = input()
print("COM SPEED:")
COMspeed = input()
print("LOCATION: " + location + "\nVLAN: " + vlan + "\nIP: " + ip)
print("IS EVERYTHING RIGHT? y/n")
while True:
check = input()
if check == "y" or "Y" or "Π" or "Π½":
build_config()
print("Done, check it!")
input()
break
elif check == "n" or "N" or "Ρ" or "Π’":
print("What would you like to change? /n 1 - ΠΠΎΠΊΠ°ΡΠΈΡ /n 2 - VLAN /n 3 - IP /n 4 - COM Π‘ΠΊΠΎΡΠΎΡΡΡ /n 5 - nothing")
check = input()
if check == 1:
location = input()
elif check == 2:
vlan = input()
elif check == 3:
ip = input()
elif check == 4:
COMspeed = input()
elif check == 5:
print('Then why you press it!?')
build_config()
print("Done! Check it!")
input()
break
elif True:
print("Your input is garbage, try again")
'''
Welcome to SO.
Where you have if check == "y" or "Y" or "Π" or "Π½":, you want if check.lower() in ('y', 'h'):
The or operator takes two boolean values and returns a boolean value.
This expression:
lacp == 'y' or 'Y'
would be evaluated as follows:
Evaluate lacp == 'y'.
If it is true, the whole expression returns true.
Otherwise, evaluate 'Y' as a boolean value and return that. Any non-zero, non-empty value is coerced to true. So your expression returns true.
The proper general way to incorporate multiple comparisons would be:
(lacp == 'y') or (lacp == 'Y')
The parentheses should not be necessary here, but I think it is a good habit to use them to make the order of evaluation clear.
For specific cases such as yours, there might be other reasonable ways to do your test, as shown in another answer.
I am writing Python code for the game Tic Tac Toe, however I have stumbled upon a hurdle already and can't seem to break out of a While loop:
print("Welcome to Tic Toe!")
Player1_Tag=input("Player 1: Choose between X and 0: ")
while Player1_Tag != "X" or Player1_Tag != "0":
print("Invalid input")
Player1_Tag=input("Player 1: Choose between X and 0: ")
else:
if Player1_Tag=="X":
Player2_Tag="0"
else:
Player2_Tag="X"
When I run this the program, it asks if I want to be "X" or "0" - if i choose '#' for example I get "Invalid input" and it asks me again in which case I choose "X" but it again gives me "Invalid input" and asks me again.. which is of course not what I want. I am confused as I don't understand why the loop keeps going even though I choose a valid input?
I have tried putting a "break" in the while loop but the loop breaks out if I choose an invalid input twice consecutively.. which is not what I want, I want it to ask me again for the third time, fourth time until I get it right.
Player1_Tag != "X" or Player1_Tag != "0" will always be true.
Consider 3 possibilities:
If Player1_Tag == "X", then Player1_Tag != "0"
If Player1_Tag == "0", then Player1_Tag != "X"
If Player1_Tag is anything else, it is neither "X" nor "0".
A clearer way to write this would be while Player1_Tag not in ("X","0"):
Your issue is caused by a logic error in the condition you're testing in your loop. You're currently testing Player1_Tag != "X" or Player1_Tag != "0", which is always True, regardless of what Player1_Tag is. If the variable is equal to one of the strings, it will be not-equal to the other. Since you're joining the two comparisons with or, you'll never exit the loop.
You need to either join the pieces of your test with and instead of or (Player1_Tag != "X" and Player1_Tag != "0"), or negate the comparisons (by changing != to ==) and do a negation of the whole expression: not (Player1_Tag == "X" or Player1_Tag == "0"). By De Morgan's laws, those are equivalent.
The problem is that you've used or when you should have used and
If Player1_Tag is equal to 0 It's at the same time not equal to X
And or checks if either is `True'
The assignment was to make a guessing game where the parameter is the answer. At the end if the person gets it right, it prints a congratulatory statement and returns the number of tries it took, if they type in quit, it displays the answer and tries == -1. other than that, it keeps looping until they get the answer correct.
def guessNumber(num):
tries = 1
while tries > 0:
guess = input("What is your guess? ")
if guess == num:
print ("Correct! It took you" + str(tries)+ "tries. ")
return tries
elif guess == "quit":
tries == -1
print ("The correct answer was " + str(num) + ".")
return tries
else:
tries += 1
When i run it, no matter what i put in it just keeps asking me for my guess.
Since you called your variable num so I'm guessing it's a integer, you were checking equality between an integer and a string so it's never True. Try changing the num to str(num) when comparing, so:
def guessNumber(num):
tries = 1
while tries > 0:
guess = input("What is your guess? ")
if guess == str(num):
print ("Correct! It took you {0} tries. ".format(tries))
return tries
elif guess == "quit":
tries = -1
print ("The correct answer was {0}.".format(num))
return tries
else:
tries += 1
Is the code properly indented?
The body of the function you are defining is determined by the level of indentation.
In the example you pastes, as the line right after the def has less indentation, the body of the function is 'empty'.
Indenting code is important in python
Additionally, for assigning one value to a variable you have to use a single '=', so the:
tries == -1
should be
tries = -1
if you want to assign the -1 value to that variable.
behavioural_level is defined as raw_input 1, 2 or 3.
What's going on here?
def summary_behaviour(x):
if behaviour_level == 1:
x = random.randint(0,1)
if x == 0:
return " "+str(first_name)+" has a rather "+str(shy[random.randint(0,(len(shy)-1))])+" personality. This has certain advantages. One is that "+str(he_she(gender))+" doesn't easily "+str(lose_focus[random.randint(0,(len(lose_focus)-1))])+": however, "+str(he_she(gender))+" can be a litte quiet at times."
else:
if x == 1:
return " Because of "+str(first_name)+"'s "+str(shy[random.randint(0,len(shy)-1)])+" character "+str(he_she(gender))+" can be a little quiet sometimes. On the plus side, however, "+str(he_she(gender))+" doesn't "+str(lose_focus[random.randint(0,len(lose_focus)-1)])+" very easily."
elif behaviour_level == 2:
x = random.randint(2,3)
if x == 2:
return str(first_name)+" is usually quite "+str(loud[random.randint(0,(len(loud)-1))])+" in class, and this has advantages and disadvantages. "+str(first_name)+" loves to involved and enjoys speaking, but sometimes "+str(hes_shes(gender))+" too "+str(loud[random.randint(0,(len(loud)-1))])+" to fully concentrate. This is common though. "
else:
if x == 3:
return " Because of "+str(first_name)+"'s "+str(loud[random.randint(0,len(loud)-1)])+" character "+str(he_she(gender))+" is "+str(adjective(int(science_level)))+" at speaking up and volunteering. Occasionally, "+str(his_her(gender))+" "+ str(loud[random.randint(0,len(loud)-1)])+ " nature can cuase "+str(him_her(gender))+ " to "+str(lose_focus[random.randint(0,len(lose_focus)-1)])+" but, that's fairly normal at "+str(his_her(gender))+" age."
else:
if behaviour_level == 3:
x = random.randint(4,5)
if x == 4:
return " I would descirbe "+str(fisrt_name)+" as a "+(str(well_mannered[random.randint(0,len(well-mannered)-1)]))+" child who is easy to teach. Rarely is "+str(he_she(gender))+" too "+str(loud[random.randint(0,(len(loud)-1))])+" to focus or too "+str(shy[random.randint(0,(len(shy)-1))])+" too speak up."
else:
if x == 5:
return str(first_name)+" a "+ (str(well_ma
Your nests are fine.
raw_input() returns a string. It doesn't look like you have converted it into an integer, so your function goes into the first else: bit of your if/else statement, because behaviour_level != 1 (but rather it equals "1")
Next, if behaviour_level == 3:. As the input is a string, not an integer, this is not True. And as there is no else, the function defaults to return None.
To fix this, you can use the int() function, which converts a string to an integer.
You can use
int(behaviour_level) == 1,2 or 3
to compare as 1 2 and 3 are integers and raw_input would return a string.
Also, Instead of doing
else:
if condition:
"""statements"""
You can simply use:
elif condition:
"""statements"""