I began scripting today and don't know pretty much.
But how do I get it to end?
passwort = "Admin"
Logout = "Logout"
versuch = 0
while versuch != passwort:
versuch = str(input("Passwort: "))
while versuch !=Logout:
print ("Menu:Logout")
vesuch = str(input(">"))
if str(input) == "Logout":
print ("Do you really want to Logout?")
print("Y / N")
Main issue here is in second while loop:
while versuch !=Logout:
print ("Menu:Logout")
vesuch = str(input(">")) #Precisely here
You are not checking with the same variable in the while loop condition and in the assignment, may be mistyping mistake (in While loop condition it is: versuch, and in your assignment it is vesuch). so you should change it in your assignment to versuch
Another mistake here, is here:
if str(input) == "Logout":
you are not calling the input function here but just getting its reference, you need to add parenthesis to call the function: input()
Last thing, use raw_input() instead of input() to avoid explicitly adding the double quotations in the user input otherwise it will not match, so with your code, if I enter : Admin , it will not match, but if I enter "Admin" it will work,
You don't want to bother the user to each time add the double quotations to their input, right?
Also don't need the str() function if you use raw_input() because it already returns a string
If you're using Py3+ (which you are, judging by the print()) you don't have to explicitly convert the input to a string!
versuch = input("Passwort: ")
Doing the above is enough!
Coming to the if, you probably want to do something along the lines of:
while something:
fooo foooo
fooo foooo
if versuch == "Logout":
fooo
if input() == "Y":
break
Don't forget to indent it enough to put the if statement inside the while block!
PS: Welcome to Python!
Related
I'm a little new to Python so I apologise in advance if this is a really simple question but I have been trying to wrap my mind around this problem for a while now.
Simply put, my code is to prompt the user if they have written down a couple of values correctly, If they have I want the loop to continue so the values can be saved to a database. If they have not I would like the code to loop back to the top of the while loop so they can re-enter the values.
For some reason when I enter 'no' It goes through the loop regardless, how may I fix this?
Here's the code below:
while True:
clear()
print("\nPlease input the required data.\n")
in_name = input('Name: ')
in_email = input('Email: ')
in_address = input('Address: ')
clear()
print("\nDoes this look correct?\n")
print("#--START--#\n")
print("Name: " + in_name)
print("Email: " + in_email)
print("Address " + in_address)
print("\n#---END---#\n")
validate == input(">>> ")
if validate == "no":
continue
elif validate == "yes":
print("/nAttempting to copy to the database...")
cursor.execute("""
INSERT INTO contacts(name, email, address)
VALUES (?,?,?)
""", (in_name, in_email, in_address))
conn.commit ()
print ( 'Data entered successfully.\n' )
break
(I should note that this write program is part of a larger program, the loop is nested within another loop that acts as the main menu, perhaps that may help.)
the keyword continue will take you back to the next iteration without finishing the current one, example.
for i in range(5):
if i == 2:
continue
print(i * 5)
This means that when i is 2 it wont print(i=2 * 5), instead it will go up to start the next loop where i=3. The output will be
0
5
15
20
If you use break, it will just completely stop and exit out of the iteration once it reaches this keyword.
I think you're looking for the keyword pass.
'while True:' will always be True, meaning the loop will go on forever. I believe that you'll need to break out of the loop for it to stop. Based on Jorge Alvarez's answer, even changing 'continue' to 'pass' will allow the loop to go forever.
If I understand correctly, you'll need to change the initial 'while True:' statement to test whether validate equals 'no' or 'yes'.
I'm trying to figure out how to work with loops in Python and I need a little help. The code I wrote is just something I'm playing with. It's not an assignment or anything like that.
What I'm trying to figure out is how to loop the program so that it asks the user to input something to start the questions over. This is what I have so far:
def monkeys():
apes = "This is not a monkey!"
monkey_yes = "This is a monkey!"
is_it_a_monkey = apes + monkey_yes
monkey_question = input("Type in Gorilla, Chimp or Macaque and make sure they're capitalized: ")
for question in is_it_a_monkey:
if monkey_question == 'Gorilla' or monkey_question == "Chimp":
print(apes)
continue
else:
print(monkey_yes)
break
def main():
while True:
if again not in {"y","n"}:
print("Please enter valid input")
elif again == "n":
return "Good bye!"
elif again == "y":
return monkeys()
monkeys()
I'm trying to get main() to do most of the work since that's what my teacher wants on our assignments. Everything under main() is something I copied to see if that would work but it only returns this:
Type in Gorilla, Chimp or Macaque and make sure they're capitalized: Gorilla
This is not a monkey!
This is not a monkey!
This is not a monkey!
This is not a monkey!
It was a lot longer than just the 4 lines but this is not what I'm looking for.
I see a couple of problems here...
First of all, you're concatenating two strings...
apes = "This is not a monkey!"
monkey_yes = "This is a monkey!"
is_it_a_monkey = apes + monkey_yes
When you go into your for-loop, the interpreter is looking at each character of that concatenated string. This is why you output 38 lines of "This is not a monkey!" For what you're trying to do, you don't need a for-loop. Try this instead:
def monkeys():
apes = "This is not a monkey!"
monkey_yes = "This is a monkey!"
monkey_question = input("Type in Gorilla, Chimp or Macaque and make sure they're capitalized: ")
if monkey_question == 'Gorilla' or monkey_question == "Chimp":
print(apes)
else:
print(monkey_yes)
The next issue I see is that you don't call the main function at all. Instead of calling moneys() at the bottom of your code, call main().
Next issue is using "while True:". If you're going to use a boolean as a while condition, make sure you put logic in your code to change that condition. Changing it to "False" should be what exits your main, not a return statement. Your main() would be better off starting like this:
def main():
keep_going = True
while keep_going:
monkeys()
Notice you should call your monkeys() function first, otherwise nobody will know what to input when the program starts. You also need code asking if they want to continue running the program. Right after your monkey() call, do something like this:
monkeys()
again = input("Would you like to try again? (y/n) ")
The next issue is your use of return statements. Instead of doing this:
elif again == "n":
return "Good bye!"
do this...
elif again == "n":
print("Good bye!")
keep_going = False
Lastly, you have "if again not in {"y","n"}:". You have to assign a value to "again" or you'll get more errors. If you use the example above, it should meet your needs.
Keep plugging at it and don't lose hope. You're getting close to understanding it.
First of all, you call monkeys() but you should call main() instead since that's where the loop is. Second, return causes a function to halt execution and to continue where you called it. In order to continue looping, remove the returns in main().
To get a better understanding of how your code works read this article about debugging. It shows some tips that allow you to see step-by-step what your code is doing.
You should use this code instead, which (as many have pointed out including #Code-Apprentice above) calls the function main() as you intend. #Code-Apprentice 's answer also includes a good explanation of why this works. This code is almost exactly the same as yours above; only the last line is different:
def monkeys():
apes = "This is not a monkey!"
monkey_yes = "This is a monkey!"
is_it_a_monkey = apes + monkey_yes
monkey_question = input("Type in Gorilla, Chimp or Macaque and make sure they're capitalized: ")
for question in is_it_a_monkey:
if monkey_question == 'Gorilla' or monkey_question == "Chimp":
print(apes)
continue
else:
print(monkey_yes)
break
def main():
while True:
if again not in {"y","n"}:
print("Please enter valid input")
elif again == "n":
return "Good bye!"
elif again == "y":
return monkeys()
main()
The reason I am submitting this answer is to point out that, despite calling main(), you are going to encounter another problem right away. You refer to a variable again in main(), but you never assign a value to again in the first place (if you run this code, you can expect to see an error of the form, "NameError: global name 'again' is not defined."). Addressing this next error is beyond the scope of your question; there are lots of ways that you can re-write this code to accommodate again, if you choose.
I have a little piece of code in Python where I'm trying to compare a user input to a specific element in an array. Here is the code:
movies = ["movie 1", "movie2", "movie3"];
answer = raw_input("What is your guess: ")
if answer == movies[1]
then print ("yes that is correct")
else:
print ("no that is incorrect")
I know the indentation above looks wrong becasue I typed it out in the text box and I'm new to this site as well as python.
I also know that I probably need to use some sort of conditional loop, maybe a while loop, but I'm having trouble finding where I can compare user input string value to a string value in my array. Any ideas how I might accomplish this?
Have fun with Python! I guess you are trying to make a loop which keeps receiving inputs from user to compare with the desired input until user types the correct input. If so, one way, it can be implemented as following (but think of adding a break condition, like input == "Bored" , to avoid infinite loop and hard stopping your code):
movies = ["movie 1", "movie2", "movie3"]
correctAnswer = movies[1]
is_notCorrect = True
while(is_notCorrect):
answer = raw_input("What is your guess: ")
if answer == correctAnswer:
print("Yes, that is correct")
is_notCorrect = False
else:
print("No, that is incorrect")
In the code above, when is_notCorrect turns into False. At next condition checking, it will break condition, and done with the loop.
Your code has some issues
movies = ["movie 1", "movie2", "movie3"]; # No need the semi-colon in Python
answer = raw_input("What is your guess: ")
# Need a colon here after if condition, new line, and indent.
#If you don't like the colon, you need to write a different way with one line of code Eg: <Do A> if <Condition happens> else <Do B>
if answer == movies[1]
then print ("yes that is correct") # No then in if-else statement in Python
else:
print ("no that is incorrect")
Backstory: I have been trying to actually learn python instead of just snipping from others. I have created a simple script that uses webbrowser. It may be a dirty script and I would love input like "you should do this", "this can be simplified". The thing i cant figure out is using if statement to handle incorrect input, prompt, then recheck the if statement. I tried searching but nothing assisted in this.
import webbrowser
a = input ('Do you want to search?(y or n)')
if a == ('y' or 'yes' or 'Y' or 'Yes' or 'YES'):
b = input ('What do you want to search?')
ab = ('https://www.google.com//search?q='+b)
urlab = ab
webbrowser.open(urlab)
else:
x = input('Where do you want to go?: ')
new = 2 # open in a new tab, if possible
# open a public URL, in this case, the webbrowser docs
url = x
webbrowser.open(url)
The question is: How do i ether do a recurring that will handle incorrect answers. If they use something other then the listed yes, it will print please use ('y' or 'yes' or 'Y' or 'Yes' or 'YES'), then prompt again and allow for input. I know i will have to change it to a nested if statement to allow the same with no to move to next. Also as is, when i use the code and enter 'y' it will open with my default (firefox), but if i enter anything else, it only opens in IE without the google search but "searching" like http://fun/ instead of https://www.google.com//search?q=fun as it should.
What did leave out? Also if you could post information on in-depth the meaning behind the code to help further learning. Thank you all!
The following code should work:
import webbrowser
a = 'y'
while a != 'n':
a = input ('Do you want to search?(y or n)')
a = a[0].lower()
if a in "y":
b = input ('What do you want to search?')
ab = ('https://www.google.com//search?q='+b)
urlab = ab
webbrowser.open(urlab)
elif a not in "n":
print "Please only enter 'y' or 'n'."
The while loop tells python to loop as long as the answer is not "n".
The a = a[0] tells python to only use the first letter of the response. This is to make the comparison easier later on.
The .lower() code tells python to convert the result to lowercase. Again, this is to make the comparison easier later on.
Now our answer will always be lowercase, and the first letter entered. So y ,yes, Yes, YES and n, no, No, NO will be converted to y or n. Of course, any other text will be treated the same way (lowercase and first character), but we only care about y and n.
The rest should be pretty straightforward. Since we have limited the possibilities of what the answer can be, we can do a simple comparison.
Below are modifications to check for only yes and no:
import webbrowser
a = 'y'
while a != 'n':
a = input ('Do you want to search?(y or n)')
a = a.lower()
if a in ("y", "yes"):
b = input ('What do you want to search?')
ab = ('https://www.google.com//search?q='+b)
urlab = ab
webbrowser.open(urlab)
elif a in "no"
a = "n"
elif a not in ("n", "no"):
print "Please only enter 'y' or 'n'."
There's a different way to check if the value is one of the given values. You should make your if condition be like this:
if a in ('y', 'yes', 'Y', 'Yes', 'YES'):
It is fast and understandable.
Here's a reason why your condition does not work.
Let's say we entered 'no'. Let's see what happens in your if statement:
1. First, the ('y' or 'yes' or 'Y' or 'Yes' or 'YES') is evaluated. Since a non-empty string in Python converts to True, this part evaluates entirely to True
2. Then, the comparison takes place. It looks like this:
if a == True:
With a being a string 'no'. That's obviously not what you want. Use the method a described above and everything will be fine
To constantly re-ask until a correct input is received, try an endless loop with a break statement:
while True:
a = input()
if a in ...:
# process input
break
else:
print("please use 'y' or 'yes' or 'Y' or 'Yes' or 'YES'")
myName = input("Hey there, what's your name?")
print("Hello",myName,"!")
print("Here's a game called ''Guess my number'', in this game you will have to guess my number in 5 tips, I will think of a number between 1 and 20.")
ready = input("Are you readyyyy!?")
if ready = "yes" or "yeah" or "totally" or "hell yeah" or "yupp" or "yepp" or "uhumm" or "sure": <-- here's the problem it says, at "sure"'s 1st "-sign
print("Let's go!")
loop = "y"
else:
print("I'm sorry to hear that.")
loop "n"
Could please anyone help, beginner here. I tried to delete and add new word, I restared the program and the computer because there's something clearly wrong. If I delete a word like "sure" the pointer will still point to the same exact place but there's nothing there...
You're using a single = sign in your if statement. That's not allowed. If you want to check for equality, you'll need to use ==. The = operator is only for assignment statements.
While changing = to == will fix the syntax error, your code still won't work exactly right. That's because == will not be distributed over all the or options you show. The expression a == b or c gets interpreted as (a == b) or c, and if c is "truthy" (as any non-empty string will be), the expression will be considered true.
Instead, you probably want to use something like if ready in {"yes", "yeah", "totally"}. This creates a constant set object and tests if the value of the ready variable is in the set (which is a fast check).
You are using a = instead of a == in your if statement. However, I would recommend doing if ready.lower() in {"yes", "yeah", "totally", "hell yeah", "yupp", "yepp"} to account for them using all uppercase.
Also, you seem to be missing your actual loop statements. I noticed you had variables named loop that are 'y' and 'n' but don't actually use them. You should also do something like this:
myName = input("Hey there, what's your name?")
print("Hello",myName,"!")
print("Here's a game called ''Guess my number'', in this game you will have to guess my number in 5 tips, I will think of a number between 1 and 20.")
loop = True
while loop:
ready = input("Are you readyyyy!?")
if ready.lower() in {"yes", "yeah", "totally", "hell yeah", "yupp", "yepp", "uhumm", "sure"}:
print("Let's go!")
loop = False
#To break out of the while loop that will keep asking them when they are ready
else:
print("I'm sorry to hear that.")