As you can see i am trying to check if the entered input by the user is string or not. If not, I have to display invalid name.
student_name = input("Enter the name of the student")
x = type(student_name)
if x!=str:
print('invalid name')
else:
print(student_name)
student_name = input("Enter the name of the student")
try:
int(student_name)
print('invalid name')
except ValueError:
print(student_name)
or
import re
student_name = input("Enter the name of the student")
num_format = re.compile(r'^\-?[1-9][0-9]*$')
for c in student_name:
it_is = re.match(num_format,c)
if it_is: it_is = True
if it_is:
print('invalid name')
else:
print(student_name)
the difference is on the first one you can pass through numbers with characters (more like username) but second one you should enter only characters.
Related
always search function return bad search string
I'm trying to find if the searching matches the movie_list and print if true or false
movie_list = []
def menu():
data = input(' please type A to add S to seach')
while data != 'q':
if data == 'a':
additz()
elif data == 's':
searchit()
else:
print('unkown command')
data = input(' please type A to add S to seach')
print(movie_list)
def additz():
name = input('please enter movie name')
year = input('please enter the movie realsed year')
movie_list.append(
{
'name':name,
'year':year
}
)
return movie_list
print(movie_list)
def searchit():
seaching = input('what are you seaching for boy ??')
if seaching in movie_list:
print('okay')`enter code here`
else:print('bad seach')
menu()
Pls check this code for searching()
def searchit():
seaching = input('what are you seaching for boy ??')
for i in movie_list:
#print(i)
if i['name']==seaching or i['year']==seaching:
print('okay')
menu()
else:print('bad search')
menu()
i'm doing a small script that received name from user and then search for name, if found prints his/her name otherwise print "not found".
def std_record():
print("1. Enter data.")
print("2. Search student")
user_input = int(input("Enter Choice: "))
if user_input == 1:
name = input("Whats your name: ")
elif user_input == 2:
search = input("Enter keyword: ")
if search in name:
print("data found: " + name +".")
else:
print("not found")
while True:
std_record()
UnboundLocalError: local variable 'name' referenced before assignment
you need to initialize strings before using them, either as an empty string or none
so name = ""
or name = None
Try initializing the name variable:
name = None
def std_record():
print("1. Enter data.")
print("2. Search student")
user_input = int(input("Enter Choice: "))
if user_input == 1:
name = input("Whats your name: ")
elif user_input == 2:
search = input("Enter keyword: ")
if name:
print("data found: " + name +".")
else:
print("not found")
while True:
std_record()
I have been trying to resolve my script with no results. I can't get
the load data to display. It is saving in members.txt and can read
it manually if opened. If someone can give any other advice on the
script as a whole it would be greatly appreciated.
I have reasearced greatly changed script around still have no luck.
import os if 'file' in vars():
wk_dir = os.path.dirname(os.path.realpath('file')) else:
print('We are running the script interactively')
class playerCLass(object):
name = ""
phone = ""
number = 0
def __init__(self, name, phone, number):
self.name = name
self.phone = phone
self.number = number
def setname(self, name):
self.name = name
def setphone(self, phone):
self.phone = phone
def setnumber(self, number):
self.number = number
def getname(self):
return self.name
def getphone(self):
return self.phone
def getnumber(self):
return self.number
def display_data(self):
print("")
print("Member information: ")
print("Name:", self.name)
print("Phone number:", self.phone)
print("Jersey number:", self.number)
def displayMenu():
print("===========Menu Selections===========")
print("1. Display Team Roster.")
print("2. Add Member.")
print("3. Remove Member.")
print("4. Edit Member.")
print("5. Save Data.")
print("6. Load Data.")
print("9. Exit Program.")
print("")
return int(input("<<Selection>> "))
def printPlayer(players):
print("Current members: ")
if len(players) == 0:
print("No current members in memory.")
else:
x = 1
while x < len(players):
print(x)
x = x + 1
def addPlayer(players):
newName = input("Type in member's name to be added to the roster:")
newPhone = input("Type in the member's phone number:")
newNumber = int(input("Type in the member's jersey number:"))
players[newName] = playerCLass(newName, newPhone, newNumber)
return players
def removePlayer(players):
name = input("Enter member's name to be removed:")
if name in players:
del players[name]
else:
print("member's name not found in list: ")
return players
def editPlayer(players):
oldName = input("Enter the name you want to edit: ")
if oldName in players:
newName = input("Enter a new name: ")
newPhone = input("Enter new phone number: ")
newNumber = int(input("Enter new jersey number: "))
players[oldName] = playerCLass(newName, newPhone, newNumber)
else:
print("No such name in memory: ")
return players
def saveData():
filename = input("Filename to save: ")
print("Saving data...")
outFile = open(filename, "wt")
for x in players.keys():
name = players[int(x)].getname()
phone = players[int(x)].getphone()
number = str(players[x].getnumber())
outFile.write(name + "," + phone + "," + number + "\n")
print("Data saved.")
outFile.close()
def loadData():
players = {}
filename = input("Filename to load: ")
inFile = open(filename, "rt")
print("Loading data...")
while True:
inLine = inFile.readline()
if not inLine:
break
inLine = inLine[:-1]
name, phone, number = inLine.split(",")
players[name] = (name, phone, number)
print("Data Loaded Successfully.")
inFile.close()
return players
print("Welcome to the Team Manager")
players = {}
menuSelection = displayMenu()
print()
while menuSelection != 9:
if menuSelection == 1:
printPlayer(players)
elif menuSelection == 2:
players = addPlayer(players)
elif menuSelection == 3:
players = removePlayer(players)
elif menuSelection == 4:
players = editPlayer(players)
elif menuSelection == 5:
saveData()
elif menuSelection == 6:
loadData()
menuSelection = displayMenu()
print("Exiting Program...")
If your issue is specifically not getting printPlayer to work you can do
def printPlayer(players):
print("Current members: ")
if len(players) == 0:
print("No current members in memory.")
#Iterate through dictionary of player name and player object and call
#display data on each of them
else:
for name, player in players.items():
print(player.display_data())
If you then run the code and input according to the statements you wrote, you should get something like this.
Welcome to the Team Manager
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 1
Current members:
No current members in memory.
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 2
Type in member's name to be added to the roster:Joe
Type in the member's phone number:123
Type in the member's jersey number:456
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>> 1
Current members:
Member information:
Name: Joe
Phone number: 123
Jersey number: 456
None
===========Menu Selections===========
1. Display Team Roster.
2. Add Member.
3. Remove Member.
4. Edit Member.
5. Save Data.
6. Load Data.
9. Exit Program.
<<Selection>>
so i have this data validation program which validated the name, email and age but its giving me an error
def emailcheck():
if (email[0] == "#"):
print("email not valid try again")
email = input("enter email:")
if ("#" not in email):
print("your email is not valid")
email = input("enter email:")
if (email == ""):
print("email is empty")
email = input("enter email:")
def namecheck():
if (name == ""):
print("name is empty")
name = input("enter name:")
def agecheck():
if (age != int):
print("age must be a number")
age = input("enter your age:")
if (age != range(1,120)):
print("i dont even know what to say")
age = input("enter your age:")
while True:
email = input("enter email:")
emailcheck()
name = input("enter name:")
namecheck()
age = input("enter your age:")
agecheck()
heres the error:
Traceback (most recent call last):
File "python", line 29, in
File "python", line 2, in emailcheck
UnboundLocalError: local variable 'email' referenced before assignment
i need this solved please
Pass your variables as parameters in your functions because they will not be defined in that scope. e.g.
def emailcheck(email):
I am trying to write a quiz program that saves and reads from text files, storing the users details in a unique text file for each user. Each user file is saved in the format:
name, age, (line 1)
username (line 2)
password (line 3)
I currently am getting the error 'IndexError: list index out of range' whilst attempting to read a two lines from a file so the program can decide whether the user has entered the correct login details. I understand that the error is due to the program not seeing line three but I cannot understand why.
import sys
def signUp ():
name=input("Please enter your first name and last name. \n- ")
name = name.lower()
username=name[0:3]
age= input("Please input your age. \n- ")
username = username + age
password = input("Please input a password. \n- ")
print ("Your username is "+username+" and your password is " +password)
userfile = open(name+".txt", "r")
userfile.write(name+", "+age+"\n")
userfile.write(username+"\n")
userfile.write(password+"\n")
userfile.close()
return name, age, username, password
def login():
logname = input("Please enter your first name and last name. \n- ")
logname = logname.lower()
loginFile = open (logname+".txt", "r")
inputuname = input ("Enter your username. \n- ")
inputpword = input("Enter your password. \n- ")
username = loginFile.readlines(1)
password = loginFile.readlines(2)
print (username)
print (password)
loginFile.close()
if inputuname == username[1].strip("\n") and inputpword ==
password[2].strip("\n"):
print("success")
quiz()
else:
print("invalid")
def main():
valid = False
print ("1. Login")
print ("2. Create Account")
print ("3. Exit Program")
while valid != True:
choice =input("Enter an Option: ")
if choice == "1":
login()
elif choice == ("2"):
user = signUp()
elif choice== ("3"):
valid = True
else:
print("not a valid option")
def quiz():
score = 0
topic = input ("Please choose the topic for the quiz. The topics available
are: \n- Computer Science \n- History")
difficulty = input("Please choose the diffilculty. The difficulties
available are: \n- Easy \n- Medium \n- Hard")
questions = open(topic+"questions.txt", "r")
for i in range(0,4):
questions = open(topic+" "+difficulty+".txt", "r")
question = questions.readline(i)
print(question)
answers = open (topic+" "+difficulty+" answers.txt", "r")
answer = answers.readline(i)
print(answer)
userAns = input()
questions.close
answers.close
if userAns == answer:
score = score + 1
return score
main()
You should use with open(....) as name: for file operations.
When writing to a file you should use a for append / r+ for read+write, or w to recreate it - not 'r' that is for reading only.
As for your login():
def login():
logname = input("Please enter your first name and last name. \n- ")
logname = logname.lower()
inputuname = input("Enter your username. \n- ")
inputpword = input("Enter your password. \n- ")
with open(logname + ".txt", "r") as loginFile:
loginfile.readline() # skip name + age line
username = loginFile.readline() # read a single line
password = loginFile.readline() # read a single line
print(username)
print(password)
if inputuname == username.strip("\n") and inputpword == password.strip("\n"):
print("success")
quiz()
else:
print("invalid")
File-Doku: reading-and-writing-files
If the file does not exist your code will crash, see How do I check whether a file exists using Python?