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.
Related
I am working on a hangman project and have run into a problem where the main function only runs for part of its entirety, then it stops. I made a smaller version of my original project to focus on the problem more.
import re
import time
import sys
#hangman shows the player how many incorrect guesses they did
hangman =['0','1','2','3','4','5','6','7']
print('\n')
w = input ('type what word you want to guess: ')
for i in range(50):
print('\n')
#blank_list creates a blank list from the word they choose above. It takes all letters and
#turns them into underscores, while special characters are exempt.
blank_list = []
blank_list = re.sub('A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z', '_', w)
blank_list = ' '.join(blank_list)
incorrect = 0
def guesscounter(w,blank_list,incorrect):
#main loop, lets player input their guess
while incorrect < 7:
print(hangman[incorrect])
print(blank_list)
guess = input('What letter would you like to guess? ').upper
#this is where it stops
return guess
for i in range(50):
print('\n')
#makes a player only guess one letter or get penalized
if guess > 0:
print("Ummmm, you can't guess more than one letter at a time. . . Have you played hangman before?")
incorrect = incorrect + 1
return incorrect
for i in range(50):
print('\n')
#determines whether guess is in word
if w.count(guess) == -1:
incorrect = incorrect+1
print("Sorry, {} isn't in the word. Try again!".format(guess))
time.sleep(3)
for i in range(50):
print('\n')
#replaces a blank with its letter when the player guesses correctly
else:
print('Good job! you got one!')
locate = w.find(guess)
blank_list.insert(guess,locate)
return blank_list
time.sleep(3)
for i in range(50):
print('\n')
#tells when the player guesses all of the letters
if blank_list.count('_') == -1:
print('Wow, you win! Nice job!')
sys.exit
#tells when the player runs out of chances
while incorrect == 7:
print('You lose! The word was {}! Better luck next time'.format(w))
guesscounter(w,blank_list,incorrect)
it currently only runs the first section guesscounter, from the top of the function to the guess input (when it ends, the shell says that guess is not defined). I will answer any questions that you have to the best of my abilities.
In your guesscounter function, after you ask the user/player "What letter would you like to guess?", in the next line you do return guess. That returns the value in the function, an explicit return statement immediately terminates a function execution and sends the return value back to the caller code. (you can read more here: https://realpython.com/python-return-statement/). So it doesn't look like you really need that return statement because the code below that is always unreachable, unless there is a reason you can comment on?
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)
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!')
I'm trying to complete a python Hangman miniproject to help me learn to code.
I've created a function that will hopefully ask the player for a letter, check the letter is only 1 letter and make sure it is not a number.
Here is the code I have so far:
def getLetter():
letter = raw_input('Please enter a letter...')
if letter.isdigit() == True:
print('That is a number!')
getLetter()
if len(str(letter)) >1:
print("Sorry, you have to enter exactly ONE letter")
getLetter()
else:
return letter
This works fine when the first input is correct, ie. one letter. However, when the input is incorrect, e.g 'ddddd', the program asks for another letter to be input but will either return the initial input ('ddddd') rather than the new input, or return nothing at all.
How can I make it return the new input? Do I need to clear the raw_input? If so, how?
You are not returning the result of your recursive calls; everywhere you call getLetter() you drop the return value.
Add return before those calls to pass on the result up the call chain:
return getLetter()
However, you should not be using recursion at all; use a loop instead:
def getLetter():
while True:
letter = raw_input('Please enter a letter...')
if letter.isdigit() == True:
print('That is a number!')
continue
if len(str(letter)) >1:
print("Sorry, you have to enter exactly ONE letter")
continue
return letter
Every recursive call adds onto the call stack, which is not unlimited in size; eventually a user always entering numbers will break your program! See Asking the user for input until they give a valid response for more information.
def get_valid_letter():
while True:
letter = raw_input('Please enter a letter...')
if letter.isdigit() == True:
print('That is a number!')
elif len(str(letter)) >1:
print("Sorry, you have to enter exactly ONE letter")
else:
return letter
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