How to loop a program from the beginning - python

I am coding a mock sign up page for a game or something or other, at the end of the code I want to confirm that the user entered data is correct. I do this by typing.
#User sign up page.
#Getting the user's information.
username = input ("Plese enter your first name here: ")
userage = input ("Please enter your age here: ")
userphoneno = input ("Please enter your home or mobile number here: ")
#Showing the inforamtion.
print ("\nIs the following correct?\n")
print ("•Name:",username)
print ("•Age:",userage)
print ("•Phone Number:",userphoneno)
#Confirming the data.
print ("\nType Y for yes, and N for no. (Non-case sensitive.)")
answer = input ("• ")
if answer == 'Y'or'y':
print ("Okay, thank you for registering!")
break
else:
#Restart from #Getting the user's information.?
My problem arises in the last section of code. The program ends like normal when "Y or y" is entered, but I can't seem to work out how to let the user re enter their data if "N or n" is entered. I tried a While loop, which I'm guessing is the solution, but I couldn't seem to get it to work correctly.
Any help would be greatly appreciated. Thanks!

You should use a while loop! Wrap the part that deals with user input with a function and then keep on calling that function if the user responds with no. By the way, you should use raw_input instead of input. For example:
#User sign up page.
#Getting the user's information.
def get_user_info():
username = raw_input("Plese enter your first name here: ")
userage = raw_input("Please enter your age here: ")
userphoneno = raw_input("Please enter your home or mobile number here: ")
#Showing the inforamtion.
print ("\nIs the following correct?\n")
print ("Name:",username)
print ("Age:",userage)
print ("Phone Number:",userphoneno)
print ("\nType Y for yes, and N for no. (Non-case sensitive.)")
answer = raw_input("")
return answer
answer = get_user_info()
#Confirming the data.
while answer not in ['Y', 'y']:
answer = get_user_info()
print ("Okay, thank you for registering!")

Related

Python: How do I make it so that an input has to match the input entered previously

this is my first day of coding in python so I don't know how "clean" my code is. I am trying to make a fun piece of code, that makes you add your name, and correctly re-enter it right after
name = input ("Insert name:")
print ("re-enter your name")
answer = name
if answer == name
print ("excellent")
elif
print ("You have entered the wrong name")
exit()
since you create variable answer = name, the result will always be true because the answer variable and name variable will have the same contents in memory.
Oh yes, I ran your code and there was an error. After the code if some_condition must be added a colon after it in one line, elif is like that, in using elif you must have a conditional after elif and then a colon. If you only have one conditional for the if, then use else instead of elif.
Here's your code after fixing:
name = input("Insert name:")
answer = input("re-enter your name")
if answer == name:
print ("excellent")
else:
print ("You have entered the wrong name")
exit()
CMIWW
You need to take a second input to re-enter your name. answer=name is basically assigning answer name. So you will always end up with answer==name
Also, a colon missing after if.... The elif statement is completely useless. You might want to use else there because you only want answer==name else redirect them to You have entered the wrong name
name = input ("Insert name: ")
answer = input("re-enter your name: ")
if answer == name:
print ("excellent")
else:
print ("You have entered the wrong name")
Output 1:
Insert name: John
re-enter your name: jon
You have entered the wrong name
Output 2:
Insert name: Mike
re-enter your name: Mike
excellent
name = input("Insert your nme : ")
rename_name = input("Re-enter your name : ")
if name == rename_name:
print("excellent")
else:
print("You have entered the wrong name")
It's unclear whether objective is just to verify that second entry is same as first or make sure that they match. If latter then second input must be in loop ('while first answer is not equal to second print warning and ask again, if answers match print Excellent') :
first = input("Enter your name: ")
while first != input("Enter your name again: "):
print("Names entered don't match!")
else:
print('Excellent')
Here is one of the cleanest code you would like😊😊😊 You don't have to exit from condition using any exit function. And in second line, you were just printing "re-enter your name: " not receiving any inputs.
name = input ("Insert name: ")
answer = input("re-enter your name: ")
print ("excellent" if answer == name else "You have entered the wrong name")

Ending the program without the rest - need support

I have wrote this simple login and registartion program:
import os
from os import path
def start():
startup = input ('are you an existing user? y/n : ')
if startup == "y":
print ("Lets login then")
login()
if startup == "n":
print ("Lets make you an account")
new_account()
else:
print ("That is an invalid input, please try again")
start()
def new_account():
new_username = input ('what do you want your username to be? ')
print ('okay...')
new_pass = input ('your new password... ')
checker_pass = input ('retype it... ')
if new_pass == checker_pass:
print ('you have entered correct passwords')
print ('Now please login ')
print (' ')
print ('..................................')
print (' ')
saveFile = open( new_username + '.txt','w')
saveFile.write(new_pass)
saveFile.close()
login()
else:
print ('you have done something wrong. Please start again')
new_account()
def login():
print (' ')
print ('..................................')
print ("")
user_name = input ('enter username: ')
file_check = path.exists(user_name + '.txt')
if file_check == False:
print ("That username dosent exist, please start again")
start()
if file_check == True:
Pass_check = open(user_name + '.txt' , 'r').read()
password = input ('enter your password: ')
if Pass_check != password:
print('That didnt quite match. Please start again')
start()
elif Pass_check == password:
print ('Welcome to your account.')
start()
once i have entered a valid username or password it then says:
That is an invalid input, please try again
are you an existing user? y/n :
this is part of the program but isnt supposed to occur once you have been welcomed to your account.
has anyone got a soulution so that once you recieve "welcome to your account" nothing else happens.
i would like it done so that the program dosent fully stop as im looking to put this code into another program.
thanks fin.
THE OUTPUT:
are you an existing user? y/n : y
Lets login then
..................................
enter username: finndude
enter your password: test
Welcome to your account.
That is an invalid input, please try again
are you an existing user? y/n :
i dont want the last two lines to appear
Add a boolean flag value to the start() function that says whether to display the line or not. When calling from login() pass True, when calling recursively from start() then pass False.

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!

local variable referenced before assignment python issue

So I'm coding a small project and I'm struggling with a certain aspect so far.
Here is the code:
import re
def clientDetails():
print("Welcome to the InHouse Solutions Room Painting Price Calculator")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = input(">>>")
print("Please enter your post code")
postCode = input(">>>")
print("Is your house a number, or a name?")
nameOrNumber = input(">>>")
if nameOrNumber == "number" or nameOrNumber == "Number":
print("Please enter your house number")
houseNumber = input(">>>")
elif nameOrNumber == "Name" or nameOrNumber == "name":
print("Please enter your house name")
houseName = input(">>>")
else:
print("Invalid")
house = (houseNumber) + (houseName)
address = (postCode) + ", " + (house)
print("Thank you for your information")
print (userName)
print (address)
print (" ")
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = input(">>>")
if clientDetailsCorrect == "no" or clientDetailsCorrect == "No":
clientDetails()
clientDetails()
Not sure what's going wrong as I haven't actually referenced the variable anywhere else. Someone help.
It would help if you posted the traceback.
That said, this line is the likely source of the problem:
house = (houseNumber) + (houseName)
The way your code is currently written, only one of houseNumber or houseName will be defined. So Python is likely complaining about the missing one.
Given how your code looks so far, it's probably better to just do:
print("Please enter your house name or number")
house = input(">>>")
And remove the house = (houseNumber) + (houseName) line.
Try this:
def clientDetails():
print("Welcome to the InHouse Solutions Room Painting Price Calculator\n")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = raw_input(">>>")
print("Please enter your post code")
postCode = raw_input(">>>")
print("Please enter your hose number or name")
house = raw_input(">>>")
address = "{}, {}".format(postCode, house)
print("Thank you for your information.\n")
print (userName)
print (address)
print (" ")
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = raw_input(">>>")
if clientDetailsCorrect.lower().startswith('n'):
clientDetails()
Using raw_input is better, it will input everything as a string. Also it will allow users to not type quotations to input text (I assume you will run this from CLI). If you later on need to separate houses that are numbers from names Python has very good string methods you can use to do so many wonderful things, I used a couple of them to simplify your code :)
N

Categories

Resources