How do I make my code loop properly in python? - python

My goal is to make sure when the user types in numbers in the userName input, then it should not accept it and make them try again.
Same thing with userNumber. When a user types in letters, they should be prompted with another line telling them to try again.
The problem is that when they do type in the correct input, the program will continue looping and listing the numbers indefinitely.
I'm new to coding, and I'm trying to figure out what I'm doing wrong. Thank you in advance!
userName = input('Hello there, civilian! What is your name? ')
while True:
if userName.isalpha() == True:
print('It is nice to meet you, ' + userName + "! ")
else:
print('Choose a valid name!')
userNumber = input('Please pick any number between 3-100. ')
while True:
if userNumber.isnumeric() == True:
for i in range(0,int(userNumber) + 1,2):
print(i)
else:
print('Choose a number please! ')
userNumber = input('Please pick any number between 3-100. ')

You never stop the loop. There's two ways to do this: either change the loop condition (while true loops forever), or break out from within.
In this case, it's easier with break:
while True:
# The input() call should be inside the loop:
userName = input('Hello there, civilian! What is your name? ')
if userName.isalpha(): # you don't need `== True`
print('It is nice to meet you, ' + userName + "! ")
break # this stops the loop
else:
print('Choose a valid name!')
The second loop has the same problem, with the same solution and additional corrections.

Alternative way: use a condition in your while loops.
userName = ''
userNumber = ''
while not userName.isalpha():
if userName: print('Choose a valid name!')
userName = input('Hello there, civilian! What is your name? ')
print('It is nice to meet you, ' + userName + "! ")
while not userNumber.isnumeric():
if userNumber: print('Choose a number please! ')
userNumber = input('Please pick any number between 3-100. ')
for i in range(0,int(userNumber) + 1,2):
print(i)

Related

Is there something wrong with the try and except statements that caused the error?

I'm trying to make a basic coin flipping simulator. And ask the user for their name and greet them. Then ask if they want to play the game. But when they enter something other than "Y", it gives this error message: UnboundLocalError: local variable 'time_flip' referenced before assignment how can I fix that and instead it prints a goodbye message. And ask them again if they want to keep playing.
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
userWantsToPlay = input("Do you want to play this game? (Y/N): ")
while userWantsToPlay in ("Y", "y"):
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
There is more code, but I shortened it to the part with errors
here's the full program: https://replit.com/#Blosssoom/coinpy?v=1#main.py
The assignment of time_flip may not complete if there is an error transforming the input to an integer.
To resolve, assign to time_flip before the try block:
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
userWantsToPlay = input("Do you want to play this game? (Y/N): ")
time_flip = None
while userWantsToPlay in ("Y", "y"):
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
If people don't type y or Y, the while loop will never run. This cause that every variables in the while loop will never ba created. You want to return time_flip, but because it supposes to be made in the while loop (), it won't be created -> local variable 'time_flip' referenced before assignment (self-explained).
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
userWantsToPlay = input("Do you want to play this game? (Y/N): ")
time_flip = 0 #None or anything
while userWantsToPlay in ("Y", "y"):
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
return time_flip

Loop an if statement if the else condition is met

So I have an If-elif statement that I want to print some text and loop if the else condition is met. Here is the code:
print("Search Options:\n1. s - Search by keyword in general\n2. u - Search for specific user data\n3. kwin - Search a keyword in a specific user\n4. allin - Search for all data by and mentioning a user")
search_mode = input("How would you like to search?: ")
if "s" in search_mode:
kwsearch = input("What Keyword do you want to use?: ")
elif "u" in search_mode:
username = input("What is the username?: ")
elif "kwin" in search_mode:
kwinuser = input("What is the username?: ")
kwinword = input("What is the keyword?: ")
elif "allin" in search_mode:
allinuser = input("What is the username?: ")
else:
print("Error. Please check spelling and capitalization")
When people mess up and don't put one of the options properly, I want to loop back to the if statement so that when they put in the right one, the loop will end and the rest of the code will continue.
I tried a for loop and wrapped it all as a function but it would end up in an infinite loop of printing the error message. Is there a way to do it with a while loop? Do I need to block it ad a function to repeat it?
Thanks in advance!
In Python, the most idiomatic thing I see for this is while True:
while True:
search_mode = input("How would you like to search?: ")
if "s" in search_mode:
kwsearch = input("What Keyword do you want to use?: ")
elif "u" in search_mode:
username = input("What is the username?: ")
elif "kwin" in search_mode:
kwinuser = input("What is the username?: ")
kwinword = input("What is the keyword?: ")
elif "allin" in search_mode:
allinuser = input("What is the username?: ")
else:
print("Error. Please check spelling and capitalization")
continue
break
You can use a while loop and break statement. You can also reduce the elif statement as I see duplicate code.
Also, you can reduce the user error by converting the search_mode to lowercase.
print("Search Options:\n1. s - Search by keyword in general\n2. u - Search for
specific user data\n3. kwin - Search a keyword in a specific user\n4. allin -
Search for all data by and mentioning a user")
search_mode = input("How would you like to search?: ")
while True:
if "s" in search_mode.lower():
kwsearch = input("What Keyword do you want to use?: ")
break
elif search_mode.lower() in ('u','kwin','allin'):
username = input("What is the username?: ")
if "kwin" in search_mode.lower():
kwinword = input("What is the keyword?: ")
break
else:
print("Error. Please check spelling and capitalization")
search_mode = input("How would you like to search?: ")
The code enters the while loop after accepting value into variable search_mode.
If the value is 's', it asks for the keyword and breaks the loop.
if the value is not 's', then it checks if the value is 'u' or 'kwin' or 'allin'. If it is any of these, then it asks for the username. If the value is kwin, it also asks for keyword. Then it breaks the loop.
If the value is none of the above, it prints the error statement and asks the user the question again. It goes into the loop again with the new value from the user and checks the conditions again. It will exit only when the if or elif statement is true. Hope this helps.

How to detect a invalid input and put the user into a loop until an acceptable answer is typed?

I'm trying to figure out how to get the user to type on letters and return numbers as invalid inputs only.
This is my code, I'm still unclear about the ValueError as if I run the code and type in letters it'll come out as an invalid input but if I put in numbers it comes in as valid.
while True:
try:
name = int(input("What is your name? "))
except ValueError:
print("Invalid response. Letters only please.")
continue
else:
break
correctName = input("Your name is...'" + (name) + "', is this correct? \n Please use 'Y' as yes and 'N' as no.\n")
if correctName == "Y":
print("Thank you..!")
int(input()) will expect an integer as an input, so when you type your name (unless you're name wholly consists of numbers), you will get a ValueError like you're experiencing now. Instead, you can use str(input()) to get the user input, then use the str.isdigit() method to check if it's a number.
name = str(input("What is your name? "))
if name.isdigit():
print("Invalid response. Letters only please.")
continue
else:
break
you can also try regex to check if a string contains a number:
bool(re.search(r'\d', name))
\d will matches for digits [0-9].
it will return True if the string contains a number.
full code:
import re
while True:
name = input("What is your name? ")
if bool(re.search(r'\d', name)):
print("Invalid response. Letters only please.")
else:
correctName = input("Your name is...'" + (name) + "', is this correct? \n Please use 'Y' as yes and 'N' as no.\n")
if correctName == "Y":
print("Thank you..!")
break
For Python3
while True:
name = input()
if name.isalpha():
break
For Python2
while True:
name = str(input())
if name.isalpha():
break

Why is my password programme code not working?

The code will only let me guess once . Can someone please tell me what is wrong with my code?
Challenge:
Write a program that sets a password as ‘Gain Access ’ and asks the
user to enter the password and keeps asking until the correct password
is entered and then says ‘Accepted’. The program should count how many
attempts the user has taken and tell them after they have been
accepted.
enter code here
password = 'Gain access'
count = 0
input = input("Enter the password: \n")
while input != password:
print("Incorrect password! Please try again: \n")
count = count + 1
print("You have now got your password wrong " + str(count) + " times. \n")
if(count < 5):
print("Access denied, please contact security to reset your password.")
break
else:
print("Accepted, welcome back.")
print("You had " + str(count) + " attempts until you got your password right.")
You should always include the language you're programming in like simonwo mentioned already.
Looks like Python to me though. I suppose this line input = input("Enter the password: \n") needs to go after while input != password:, as well. Otherwise you can only enter the password once and then it directly executes all 5 loops. But you should NOT assign input because this is the function you want to obtain the input from.
Do something like user_input = input("Enter the password: \n"). So your code should look something like this:
...
user_input = input("Enter the password: \n")
while user_input != password:
print("Incorrect password! Please try again: \n")
user_input = input("Enter the password: \n")
... Your existing code here
But note that this way the user won't get notified if they entered the correct password with their first try. You could insert a check after the first reading of the user input and if it matches the desired password print your welcome phrase.

validate user input by length in Python

I have some code:
def GetPlayerName():
print()
PlayerName = input('Please enter your name: ')
print()
return PlayerName
How can I keep asking for the player's name until they enter a name that is more than one character long, and tell them they must enter a valid name if they leave the field blank?
I tried
def GetPlayerName():
print()
PlayerName = input('Please enter your name: ')
print()
return PlayerName
while len(PlayerName) < 1:
print("You must enter a name!")
but have been unsuccessful.
Use a while loop to get the input repetitively:
def get_player_name():
print()
player_name = ""
while len(player_name) <= 1:
player_name = input('Please enter your name: ')
print()
return player_name
The way you are currently using it, you use the while statement to only print the error message.
PS: I've converted your variable names etc to small_caps_format because that is what PEP recommends.
def GetPlayerName():
print()
while True:
PlayerName = input('Please enter your name: ')
if len(PlayerName) > 1:
break
print("Your name is too short! :c")
print()
return PlayerName
One solution amongst others, and doesn't require any variables outside of the while loop. As mentioned by #jme, the error message is rather easy to print with this solution. The issue with your code is that:
Your while loop is after the return statement is called, so it's affectively rendered mute.
Your while loop is infinite-- it doesn't give the user a chance to re-try!

Categories

Resources