'elif' not working inside 'while' loop [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
I am trying to create a program; however, even when 'y' or 'yes' is entered, the code still goes to the 'n'/'no' loop. Any suggestions?
no = input("How many messages?")
intNo = int(no)
msgno = input("2 different msgs? [y/n]:")
message = input("Message:")
message2 = input("Message 2:")
run = True
pyautogui.click(x=980, y=805, button='left')
while run == True:
if msgno.lower() == "n" or "no":
pyautogui.typewrite(message, interval=0.00001)
pyautogui.press('enter')
intNo = intNo - 1
if intNo <= 0:
run = False
elif msgno.lower() == "y" or "yes":
no = no / 2
pyautogui.typewrite(message, interval=0.00001)
pyautogui.press('enter')
pyautogui.typewrite(message2, interval=0.00001)
pyautogui.press('enter')
intNo = intNo - 1
if intNo <= 0:
run = False

You have to add two conditional statements to each If statement. Like this: if msgo.lower() == 'yes' or msgo.lower() == 'y' If you have just a variable that exists or a value, it will default to True, so where "no" was defaulted to True and went into the code-block.

Related

How to use a variable across multiple functions [duplicate]

This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 5 months ago.
I am trying to use two variables (i, and q) across three functions. I want to test whether i and q are valid after each input . If they are then they will be added to list and the while loop continues. If they are not valid Then the function will stop and all input will be taken and presented. I have tried to make both i and q global variables but it does not seem to work as it is saying that "i" is not defined. How do I check the i and q variables in separate functions?
Any help would be really appreciated as I am only new and thought this should work.
I didn't know what to add so I have put down the three functions in full below:
Updated:
def add_item():
code_inputed = []
quan_inputed = []
VC()
VQ()
vc_result = VC(I)
vq_result = VQ(q)
while True:
if i != "END":
if vc_result == True and vq_result == True:
code_inputed.append(int(i))
quan_inputed.append(int(q))
elif vc_result == True and vq_result == False:
print("Invalid Quanity")
break
elif vc_result == False and vq_result == True:
print ("Invalid code")
break
else:
print("Invalid inputs")
break
return code_inputed,quan_inputed
def VC():
i = input("enter code: ")
minimum = 0
maxiumum = 39
if i == "END":
return False
elif int(i) > minimum and int(i) <= maximum:
True
else:
False
def VQ():
q = input("enter quantity: ")
minimum = 0
maxiumum = 49
if int(q) > minimum and int(q):
True
else:
False
Thank you for any help
Please read this W3Schools - Python global variables for a better understanding of how global variables work.
I think the problem with your code is, you should initialize your variables i and q first, before the add_item() function, and then get them from the global scope using the global keyword in the add_item function too.
i = 0
def add_item():
global i
Plus, you want to recheck your add_item() conditions,
while True:
i = input("enter code: ")
return i
if i != "END":
q = input("enter quantity: ")
return q # your code stops at this return
VC()
VQ()
if VC == True and VQ == True:
code_inputed.append(int(i))
quan_inputed.append(int(q))
elif VC == True and VQ == False:
print("Invalid Quanity")
break
elif VC == False and VQ == True:
print ("Invalid code")
break
else:
print("Invalid inputs")
break
P.S. you actually don't have to use global variables in this context, you can just pass the values as functions arguments.
Looks like you need some help here. First of all the global keyword is for functions where you are setting the global variable. Also, forget about globals. Pass i and q to the functions directly. Then set those calls equal to variables and check those variables.
vc_result = VC(i)
vq_result = VQ(q)
if vc_result == True and vq_result == True:
...
Plus, return immediately exits the function so no processing will continue. Those should be removed. I recommend reviewing tutorials on python functions to fill in your knowledge.

How to start stopwatch in python [duplicate]

This question already has answers here:
Keyboard input with timeout?
(28 answers)
Closed 1 year ago.
I want to use a stopwatch to time my code, but I need help with it. This is my code:
import time
timer = 0
alreadyout = 'no'
eligable = 'no'
entered = 'no'
if alreadyout == 'no' and eligable == 'no':
answer = str(input("type to 100 letters as fast as you can"))
if len(answer) == 100:
eliable = 'yes'
entered = 'yes'
alreadyout = 'yes'
while entered == 'no':
time.sleep(1)
timer = timer + 1
print(timer)
You can use time.time() to time your code. Here is an example
import time
start = time.time()
# <code to time>
end = time.time()
print(f"Time taken to run the code was {end-start} seconds")

Loop doesn't stop after applying Break condition [duplicate]

This question already has answers here:
Breaking out of nested loops [duplicate]
(8 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
As I am a new learner in python, I was trying to do an exercise having while loop in it.
I have written a piece of code which will ask user to enter his details.
After getting all the details the program should stop, but In my case after entering Account Number, it again start asking Mobile number to enter.
Please have a look at the code and suggest where I am going wrong.
bnkName = ["SBI", "PNB", "CBI", "ICICI", "BOB"]
targetattmpt = 10
appliedattmpt = 1
while (appliedattmpt <= targetattmpt):
mobilenum = input("Please Enter your Mobile Number:\n")
if (len(mobilenum) == 10):
while (True):
Bankname = input("Please Enter your Bank Name\n").upper()
if Bankname in bnkName:
print("Valid Bank\n")
print("Please enter your Account Number\n")
accnum = input("Account Number:\n")
print(accnum)
break
else:
print("Invalid Bank")
else:
print(mobilenum, "IS NOT VALID!!!", "You have", targetattmpt - appliedattmpt, "attempts left\n")
appliedattm = appliedattm + 1
if (appliedattmpt > targetattmpt):
print("Account locked!!")
The break statement inside the inner loop will break the inner loop but not the outer. You should re-think the logic and maybe add bool variable to check if inner loop broke so you can break the outer loop. For/while loops have else statements which will check if the loop called finished successfully or was aborted with a break. In the case of a while loop, the else will be executed if the condition in the is no longer true.
Take a look at: https://book.pythontips.com/en/latest/for_-_else.html
To give you an example:
j = 0
bank = True
while(j < 2):
print('check_this')
i = 0
while(i < 2):
print('check that')
if bank:
break
else:
i += 1
else:
break
print('I checked both !')
j += 1
Output:
check_this
check that
I checked both !
check_this
check that
I checked both !
Now change the bank to False
j = 0
bank = False
while(j < 2):
print('check_this')
i = 0
while(i < 2):
print('check that')
if bank:
break
else:
i += 1
else:
break
print('I checked both !')
j += 1
Output:
check_this
check that
check that

While loop menu never ends [duplicate]

This question already has answers here:
Python, unable to convert input() to int()
(3 answers)
Closed 3 years ago.
I'm trying to do a menu, it's so easy but I don't understand why never ends my loop, I attach my code:
def main():
menu_bool = False
while(menu_bool == False):
print("Menu:\n\t1. Copiar")
x = input()
if x == 1:
print("You have selected option 1.")
menu_bool = True
# Ejecutamos la función main
if __name__ == '__main__':
main()
Why when I press "1" ask me again to choose an option? I have declared a boolean variable for stop it, menu_bool = True, but I don't know why my main function is in loop.
I try it doing a global variable but it don't works too. Then this means that my menu_bool = True is never done but I don't understand why.
menu_bool = False
def main():
global menu_bool
while(menu_bool == False):
print("Menu:\n\t1. Copiar")
x = input()
if x == 1:
print("You have selected option 1.")
menu_bool = True
# Ejecutamos la función main
if __name__ == '__main__':
main()
Thank you so much!
As others have said, basically you are comparing strings with ints. Also I'd suggest being a bit more pythony with bools, in this case using not instead of comparing explicitly via comparison operator.
def main():
menu_bool = False
while(not menu_bool):
print("Menu:\n\t1. Copiar")
x = input()
if x == '1':
print("You have selected option 1.")
menu_bool = True

Break out of double while loops? [duplicate]

This question already has answers here:
How can I break out of multiple loops?
(39 answers)
Python - `break` out of all loops [duplicate]
(4 answers)
Closed 8 years ago.
Hello i have this login that i am trying to make and when i get to the command screen if i want to exit out of the program i type "exit", but the problem is i have it in a double while loop and don't know how to break out of both. Here is an example of the code:
a = 0
b = 0
loginatt = 0
while a == 0:
if loginatt == 4:
print "Too many tires!"
break
password = raw_input("Password: ")
if password == "test":
b = 1
while b == 1:
command = raw_input("command: ")
if command == "exit":
break
else:
loginatt += 1
print "error, login failed!"
this part of the code won't break out of the double while loop:
command = raw_input("command: ")
if command == "exit":
break
break will only leave one level of looping. You could try resetting your outer loop variable:
if command == "exit":
a = 1
break
However, it might be better to break your code up a bit:
def access_control(correct_pass="test", attempts=4):
"""Control access to the supplied function func."""
for _ in range(attempts):
password = raw_input("Password: ")
if password == correct_pass:
get_commands()
break
else:
print "Incorrect password."
else:
print "Too many tries."
def get_commands():
"""Take user input until they enter 'exit'."""
while True:
command = raw_input("Command: ")
if command == "exit":
break
You can now call access_control to enter the password; if correct, you will be passed on to get_commands:
>>> access_control()
Password: test
Command: exit
>>>
or
>>> access_control()
Password: foo
Incorrect password.
Password: bar
Incorrect password.
Password: baz
Incorrect password.
Password: python
Incorrect password.
Too many tries.
>>>
There is no keyword to break from more than one loop. You can try the following:
wantToBreak = False
while b == 1:
command = raw_input("command: ")
if command == "exit":
wantToBreak = True
break
if wantToBreak:
break
It utilizes a boolean variable which indicates whether the flow should be interrupted (break more levels).
Generally variable names like a and b aren't very explicit. Also your login functionality is independent of your command functionality, hence why not seperate both?
#! /usr/bin/python2.7
def login(maxTries = 4):
while maxTries:
password = raw_input('Password: ')
if password == 'test':
return True
maxTries -= 1
print 'Too many tries.'
return False
def runCommand():
while True:
command = raw_input('Command: ')
if command == 'exit': break
print 'processing command', command
if login(): runCommand()
Instead of breaking when finding the command exit you can also use an iterator with a sentinel:
def runCommand():
for command in iter(lambda: raw_input('Command: '), 'exit'):
print 'processing command', command

Categories

Resources