Problem with while loop in Python, repeating string - python

a = input('Enter your username...')
while (a == 'SuperGiraffe007&'):
print('Welcome!')
else:
print("Try again...")
a = input('Enter your username...')
while (a == 'SuperGiraffe007&'):
print('Welcome!')
The code functions correctly but when I input the correct username the string 'Welcome!' repeats forever which crashes my browser. How do I stop it from repeating and only print once?

It looks like you have misunderstood what a while loop does. It checks the condition you give it and keeps on repeating the body of the loop for as long as the condition is true. The infinite loop you describe is exactly what you're asking for with your code.
What I think you want is a loop that stops when the user enters the correct username:
a = input('Enter your username...')
while a != 'SuperGiraffe007&': # stop looping when the name matches
print("Try again...")
a = input('Enter your username...') # ask for a new input on each loop
print('Welcome!')

I think you need to use if instead of while. Also, you don't need the parenthesis when using a conditional in python.
Use this:
a = input('Enter your username...')
if a == 'SuperGiraffe007&':
print('Welcome!')
else:
print("Try again...")
a = input('Enter your username...')
if (a == 'SuperGiraffe007&'):
print('Welcome!')

Related

Executing one line of code inside a while loop only once

How do I make a specific line of code execute only once inside a while loop?
I want the line:
"Hello %s, please enter your guess: " %p1" to run only once and not every time the player guesses wrong.
Is there are command or function I can use or do I have to structure the whole game differently? Is there a simple fix to the program in this form?
import random
number = random.randint(1,9)
p1 = input("Please enter your name: ")
count = 0
guess = 0
while guess != number and guess != "exit":
guess = input("Hello %s, please enter your guess: " % p1)
if guess == "exit":
break
guess = int(guess)
count += 1
if guess == number:
print("Correct! It Took you only", count, "tries. :)")
break
elif guess > number:
print("Too high. Try again.")
elif guess < number:
print("Too low. Try again.")
You can create a flag variable, e. g.
print_username = True
before the while loop. Inside the loop uncheck it after loop's first iteration:
if print_username:
guess = input("Hello %s, please enter your guess: " % p1)
print_username = False
else:
guess = input("Try a new guess:")
You have to ask for a new guess on every iteration - else the code will loop either endlessly (after first wrong guess) or finish immediately.
To change up the message you can use a ternary (aka: inline if statement) inside your print to make it conditional:
# [start identical]
while guess != number and guess != "exit":
guess = input("Hello {}, please enter your guess: ".format(p1) if count == 0
else "Try again: ")
# [rest identical]
See Does Python have a ternary conditional operator?
The ternary checks the count variable that you increment and prints one message if it is 0 and on consecutive runs the other text (because count is no longer 0).
You might want to switch to more modern forms of string formatting as well: str.format - works for 2.7 as well
A way to execute an instruction only x times in a while loop could be to implement a counter, and add an if condition that checks if the counter < x before executing the instruction.
You should ask for the username outside of the loop and request input at the beginning of the loop.
Inside the loop you create output at the end and request input on the next iteration. The same would work for the first iteration: create output (outside of the loop) and then request input (first thing inside the loop)

Loop in Python not working

I'm having trouble getting a while loop to work here. What I would like to do is have the program jump back to "please enter the word you with to translate" once it runs and provides the output.
When I have used while true and continue in what I believe are the proper places, it simply continues to print the output. of the word I'm translating. Hope that makes sense.
Listed below is the code I have working. The second chunk is where I add the while loop and run into issues.
def silly_alpha():
print("Looks like we're going with the Impossible alphabet.")
word_trans = input('Please enter the word you wish to translate: ')
if word_trans.isalpha():
for letter in word_trans:
print(impossible.get(letter.lower()), end=' ')
else:
print("There's no numbers in words. Try that again.")
This is the problematic code
def silly_alpha():
print("Looks like we're going with the Impossible alphabet.")
while True:
word_trans = input('Please enter the word you wish to translate: ')
if word_trans.isalpha():
for letter in word_trans:
print(impossible.get(letter.lower()), end=' ')
continue
else:
print("There's no numbers in words. Try that again.")
continue
To have it repeat the loop, and accept a new word to translate, you simply need to remove those continue statements. I tested this in IDLE and it works just fine.
def silly_alpha():
print("Looks like we're going with the Impossible alphabet.")
while True:
word_trans = input('Please enter the word you wish to translate: ')
if word_trans.isalpha():
for letter in word_trans:
print(impossible.get(letter.lower()), end=' ')
else:
print("There's no numbers in words. Try that again.")
However, you now have an infinite loop. You may want to consider some way of allowing the user to enter a command that will terminate the loop. Perhaps something like:
def silly_alpha():
print("Looks like we're going with the Impossible alphabet.")
while True:
word_trans = input('Please enter the word you wish to translate, "x" to cancel: ')
if word_trans == 'x':
print('Exiting translation...')
break
elif word_trans.isalpha():
for letter in word_trans:
print(impossible.get(letter.lower()), end=' ')
else:
print("There's no numbers in words. Try that again.")
continue applies to the closest loop and allow to skip next instructions in this loop.
So your first continue applies to for, as it s the last instruction of the loop, it as no effect.
You second continue applies to while True, as it s the last instruction of the loop, it as no effect.
What you are looking for is break which terminates the closest loop. In your case, the while True I suppose.
So remove the first continue and replace the second by a break.

I need to figure out how to make my program repeat. (Python coding class)

I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.

Python: How do I get my function to repeat until asked to cancel?

I just started learning Python. Basically I just want to repeat the loop once if answer is yes, or break out of the loop if answer is no. The return True/False doesn't go back to the while loop?
def userinfo():
while true:
first_name=input("Enter your name here:")
last_name=input("Enter your last name:")
phonenum=input("Enter your phone number here")
inputagain=rawinput("Wanna go again")
if inputagain == 'no':
return False
userinfo()
Instead of while true: use a variable instead.
Such as
while inputagain != 'no':
Instead of looping forever and terminating explicitly, you could have an actual condition in the loop. First assume that the user wants to go again by starting again as 'yes'
again = 'yes'
while again != 'no':
# ... request info ...
again = input("Wanna go again?: ")
though this while condition is a bit weak, if the user enters N, n, no or ever no with space around it, it will fail. Instead you could check if the first letter is an n after lowercasing the string
while not again.lower().startswith('n'):
You could stick to your original style and make sure the user always enters a yes-like or no-like answer with some extra logic at the end of your loop
while True:
# ... request info ...
while True:
again = input("Wanna go again?: ").lower()
if again.startswith('n'):
return # exit the whole function
elif again.startswith('y'):
break # exit just this inner loop

python checking user input for number in a while loop

I have a function below which is part of my big main function, what I want this function to do is that whenever called, I want the function to check if the user input is
a number or not. If it is a number it will return the number and break.
But if it is not a number I want it to loop again and again.when I try to
run it, it gives me unexpected an error:
unexpected eof while parsing
can any body help me what I am missing or how I should rearrange my code? thank you!
def getnumber():
keepgoing==True
while keepgoing:
number = input("input number: ")
result1 = number.isdigit()
if result1 == 1:
return number
break
elif keepgoing==True:
A neater and clearer what to do what you are already doing:
def getnumber():
while True:
number = input("Input number: ")
if number.isdigit():
return number
That's all you need, the extra variables are superfluous and the elif at the end makes no sense. You don't need to check booleans with == True or == 1, you just do if condition:. And nothing happens after return, your break will never be reached.
You don't need the last line:
elif keepgoing==True:
It's waiting for the rest of the file after the :.
Side note, it should be a single = in the first part, and can just be written simpler as well.
def getnumber():
while True:
number = input("input number: ")
result1 = number.isdigit()
if result1:
return number
Since you're inside the while loop, it'll keep executing. Using return will end the while loop, as will breaking and exiting the program. It will wait for input as well each time, though.
While assigning you have used keepgoing == True, I think it should be keepgoing=True
The following solution works on my machine, although I am running Python 2.7
def get_num():
while True: #Loop forever
number_str = raw_input("> Input a number: ") #Get the user input
if number_str.isdigit(): #They entered a number!
return int(number_str) #Cast the string to an integer and return it
I used raw_input rather than input, because raw_input gives you the exact string the user entered, rather than trying to evaluate the text, like input does. (If you pass the 12 to input, you'll get the number 12, but if you pass "12", you'll get the string '12'. And, if you pass my_var, you'll get whatever value was in my_var).
Anyway, you should also know that isdigit() returns whether or not the string has only digits in it and at least one character - that is not the same thing as isNumber(). For instance, "123".isdigit() is True, but "123.0".isdigit() is False. I also simplified your loop logic a bit.

Categories