Python: Print just once in raw_function - python

result = raw_input("Enter results file: ")
while True:
try:
result = get_marks_from_file(result)
break
except IOError:
print 'Please supply correct file. '
Above is the raw_input function that I am using to bring a file. When I put correct file name, it works well. But when I put something else such as 'asdsada', the sentence 'please supply correct file. ' is printed and it doesn't stop. Is there any method for just one printing and return to the question?
Any advices or helps would be appreciated.

Move the raw_input inside your loop:
while True:
result = raw_input("Enter results file: ")
try:
result = get_marks_from_file(result)
break
except IOError:
print 'Please supply correct file. '

Related

Python Login and Register System using text files

Hey I am trying to create a system using text files where a user can sign up and log in. All the data will be stored in plain text in a text file called User_Data.txt. My code works but I would like to know if there is anything I missed or If I could improve it in any way. Sorry for the Bad code Formatting in advance.
def choices():
print("Please choose what you would like to do.")
choice = int(input("For Sigining Up Type 1 and For Signing in Type 2: "))
if choice == 1:
return getdetails()
elif choice == 2:
return checkdetails()
else:
raise TypeError
def getdetails():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
f = open("User_Data.txt",'r')
info = f.read()
if name in info:
return "Name Unavailable. Please Try Again"
f.close()
f = open("User_Data.txt",'w')
info = info + " " +name + " " + password
f.write(info)
def checkdetails():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
f = open("User_Data.txt",'r')
info = f.read()
info = info.split()
if name in info:
index = info.index(name) + 1
usr_password = info[index]
if usr_password == password:
return "Welcome Back, " + name
else:
return "Password entered is wrong"
else:
return "Name not found. Please Sign Up."
print(choices())
There is a lot of improvements You could do.
First of all, split functionality to smaller function.
PASSWORD_FNAME = "User_Data.txt"
def get_existing_users():
with open("r", PASSWORD_FNAME ) as fp:
for line in fp.readlines():
# This expects each line of a file to be (name, pass) seperated by whitespace
username, password = line.split()
yield username, password
def is_authorized(username, password):
return any((user == (username, password) for user in get_existing_users())
def user_exists(username):
return any((usr_name == username) for usr_name, _ in get_existing_users())
# above is equivalent of:
#
# for usr_name, _ in get_existing_users():
# if usr_name == username:
# return True
# return False
def ask_user_credentials():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
return name, password
def checkdetails():
name, password = ask_user_credentials()
if is_authorized(name, password):
return "Welcome Back, " + name
if user_exists(name):
return "Password entered is wrong"
return "Name not found. Please Sign Up."
def getdetails():
name, password = ask_user_credentials()
if not user_exists(name):
return "Name Unavailable. Please Try Again"
# Not sure tho what would You like to do here
It's always good to remember to always close your file if you read it.
So if you do something like:
f = open("r", "file.txt") remember to always call f.close() later.
If you use context manager and do it like:
with open("r", "file.txt") as fp:
print(fp.read())
it will automatically close the file for you at the end.
Firstly, fix the spelling error at int(input("For Sigining Up Type 1") Other than that I would add some kind of purpose, for example storing secret numbers or something.
For example you can extend your script with a simple password recovery system.
I think it could be useful to learn...
You can implement a sort of a simple hashing system in order to avoid saving the password as plain text.
If you want to add a GUI, please consider using Tkinter.
https://docs.python.org/3/library/tkinter.html
Let we know.
Good Luck and Keep Coding with <3

TypeError: 'str' object is not callable with input() [duplicate]

This question already has answers here:
Why does code like `str = str(...)` cause a TypeError, but only the second time?
(20 answers)
Closed 21 days ago.
I have the following code, which is supposed to ask the user 2 file names. I get an error with the input() in the second function but not in the first, I don't understand...
Here is the error :
output = getOutputFile()
File "splitRAW.py", line 22, in getOutputFile
fileName = input("\t=> ")
TypeError: 'str' object is not callable
# Loops until an existing file has been found
def getInputFile():
print("Which file do you want to split ?")
fileName = input("\t=> ")
while 1:
try:
file = open(fileName, "r")
print("Existing file, let's continue !")
return(fileName)
except IOError:
print("No such existing file...")
print("Which file do you want to split ?")
fileName = input("\t=> ")
# Gets an output file from user
def getOutputFile():
print("What name for the output file ?")
fileName = input("\t=> ")
And here is my main() :
if __name__ == "__main__":
input = getInputFile()
output = getOutputFile()
The problem is when you say input = getInputFile().
More specifically:
The program enters the getInputFile() function, and input hasn't been assigned yet. That means the Python interpreter will use the built-in input, as you intended.
You return filename and get out of getInputFile(). The interpreter now overwrites the name input to be that string.
getOutputFile() now tries to use input, but it's been replaced with your file name string. You can't call a string, so the interpreter tells you that and throws an error.
Try replacing input = getInputFile() with some other variable, like fileIn = getInputFile().
Also, your getOutputFile() is not returning anything, so your output variable will just have None in it.
Next time just "RESTART YOUR KERNEL" TypeError: 'str' object is not callable - restart kernel and its gone. You're good to go.
You may be overriding the input name with something else.
If you need to reinitialize the input function in a notebook:
from builtin import input
Depending on what version of python you're using:
Python 2:
var = raw_input("Please enter something: ")
print "you entered", var
Or for Python 3:
var = input("Please enter something: ")
print("You entered: " + var)

Downloading a webpage using urllib3

I'm trying to write a program for an assignment that uses urllib3 to download a webpage and store it in a dictionary. (I'm using spyder 3.6)
The program is giving me an 'AttributeError' and I have no idea what I'm doing wrong. here is my code with step by step notes I wrote for the assignment.
#Downloading a webpage
import urllib3
import sys
#these import statements allow us to use 'modules' aka 'libraries' ....
#code written by others that we can use
urlToRead = 'http://www.google.com'
#This value won't actually get used, because of the way the while loop
#below is set up. But while loops often need a dummy value like this to
#work right the first time
crawledWebLinks = {}
#Initialize an empty dictionary, in which (key, value) pairs will correspond to (short, url) eg
#("Goolge" , "http://www.google.com")
#Ok, there is a while loop coming up
#Here ends the set up
while urlToRead != ' ':
#This is a condition that dictates that the while loop will keep checking
#as long as this condition is true the loop will continue, if false it will stop
try:
urlToRead = input("Please enter the next URL to crawl")
#the "try" prevents the program from crashing if there is an error
#if there is an error the program will be sent to the except block
if urlToRead == '':
print ("OK, exiting loop")
break
#if the user leaves the input blank it will break out of the loop
shortName = input("Please enter a short name for the URL " + urlToRead)
webFile = urllib3.urlopen(urlToRead).read()
#This line above uses a ready a readymade function in the urllib3 module to
#do something super - cool:
#IT takes a url, goes to the website for the url, downloads the
#contents (which are in the form of HTML) and returns them to be
#stored in a string variable (here called webFile)
crawledWebLinks[shortName] = webFile
#this line above place a key value pair (shortname, HTML for that url)
#in the dictionary
except:
#this bit of code - the indented lines following 'except:' will be
#excecuted if the code in the try block (the indented following lines
#the 'try:' above) throw and error
#this is an example of something known as exeption-handling
print ("*************\nUnexpected Error*****", sys.exc_info()[0])
#The snip 'sys.exc_info()[0]' return information about the last
#error that occurred -
#this code is made available through the sys library that we imported above
#Quite Magical :)
stopOrProceed = input("Hmm..stop or proceed? Enter 1 to stop, enter anything else to continue")
if stopOrProceed ==1 :
print ('OK...Stopping\n')
break
#this break will break out of the nearest loop - in this case,
#the while loop
else:
print ("Cool! Let's continue\n")
continue
# this continue will skip out of the current iteration of this
#loop and move to the next i.e. the loop will reset to the start
print (crawledWebLinks.keys())
Your issue is that you are trying to call urllib3.urlopen(), and urllib3 does not have a member urlopen Here is a working snippet. All that I did was replace urllib3 with urllib.request:
import urllib.request
import sys
urlToRead = 'http://www.google.com'
crawledWebLinks = {}
while urlToRead != ' ':
try:
urlToRead = input("Please enter the next URL to crawl: ")
if urlToRead == '':
print ("OK, exiting loop")
break
#if the user leaves the input blank it will break out of the loop
shortName = input("Please enter a short name for the URL " + urlToRead + ": ")
webFile = urllib.request.urlopen(urlToRead).read()
crawledWebLinks[shortName] = webFile
except:
print ("*************\nUnexpected Error*****", sys.exc_info()[0])
stopOrProceed = input("Hmm..stop or proceed? Enter 1 to stop, enter anything else to continue")
if stopOrProceed ==1 :
print ('OK...Stopping\n')
break
else:
print ("Cool! Let's continue\n")
continue
print (crawledWebLinks)
Another note, simply printing out the type of error in your except block is not very useful. I was able to debug your code in 30 seconds once I removed that and viewed the actual traceback.

Can I use try except without an error

Hoping someone can help me with this.
I think I need to use the try and except function in order to do what I need but im not creating an error for an exception to occur.
When a user enters a1 it looks at the a1 dictionary and finds an x so it does not satisfy the while loop as true. so it moves to else. I need to reask the question again and start over from the top of the while loop. Is it possible to trigger an exception just because something is false?
here is what I am working with
board = {'a1':'x','a2':'_','a3':'_','b1':'_','b2':'_','b3':'_','c1':' ','c2':' ','c3':' '}
def o_move():
print 'im over at o now'
def x_move():
ans = raw_input('Player x please Enter a location: ') #ask user for location
f = board[ans] #current value of dictionary location selected
while f is '_' or f is ' ':
board[ans] == 'x' #writes the user location selected to the dictionary
o_move() #everything was good, move on
break #break the loop
else:
print 'space not available Try again'
ans = raw_input('Player x please Enter a location: ') #ask again
x_move()
A simpler way to do this is to have the function x_move() call itself if a valid move's not chosen the first time. That way, you don't have to write two raw_input() statements.
Here's one way your code might be simplified:
board = {'a1':'x','a2':'_','a3':'_','b1':'_','b2':'_','b3':'_','c1':' ','c2':' ','c3':' '}
def o_move():
print 'im over at o now'
def x_move():
ans = raw_input('Player x please Enter a location: ')
open_positions = ['_', ' ']
if board[ans] in open_positions:
board[ans] = 'x'
o_move()
else:
print 'space not available Try again'
x_move()
x_move()
Instead of having
ans = raw_input('...')
Again, you should just put:
else:
Print 'space not available, try again'
x_move()
And that should send it to the start of the while loop again

Having trouble parsing a txt file into a list full of zip codes in my zipcode lookup program

Hello everyone thanks for looking into my problem. What I am trying to do is write a "Structured" program in python that takes txt from a file and parses it into lists. Then after closing the file, I need to reference the user input (zipcode) in those lists and then print out the city and state according to the zipcode that they entered. My instructor is having us use structure by making several functions. I know there are probably lots of more efficient ways of doing this, but I must keep the structure thats in place.
EDIT
Here is my code(Current):
#-----------------------------------------------------------------------
# VARIABLE DEFINITIONS
eof = False
zipRecord = ""
zipFile = ""
zipCode = []
city = []
state = []
parsedList = []
#-----------------------------------------------------------------------
# CONSTANT DEFINITIONS
USERPROMPT = "\nEnter a zip code to find (Press Enter key alone to stop): "
#-----------------------------------------------------------------------
# FUNCTION DEFINITIONS
def startUp():
global zipFile
print "zipcode lookup program".upper()
zipFile = open("zipcodes.txt","r")
loadList()
def loadList():
while readRecord():
pass
processRecords()
def readRecord():
global eof, zipList, zipCode, city, state, parsedList
zipRecord = zipFile.readline()
if zipRecord == "":
eof = True
else:
parsedList = zipRecord.split(",")
zipCode.append(parsedList[0])
city.append(parsedList[1])
state.append(parsedList[2])
eof = False
return not eof
def processRecords():
userInput = raw_input(USERPROMPT)
if userInput:
print userInput
print zipCode
if userInput in zipCode:
index_ = zipcode.index(userInput)
print "The city is %s and the state is %s " % \
(city[index_], state[index_])
else:
print "\nThe zip code does not exist."
else:
print "Please enter a data"
def closeUp():
zipFile.close()
#-----------------------------------------------------------------------
# PROGRAM'S MAIN LOGIC
startUp()
closeUp()
raw_input("\nRun complete. Press the Enter key to exit.")
Here is a sample from the zipcode txt file:
00501,HOLTSVILLE,NY
I am definitely stuck at this point and would appreciate your help in this matter.
EDIT
Thanks for all the help everyone. I really do appreciate it. :)
why you fill the lists zipcode, city , state like that, i mean in each user entry we get the next line from the file
i think that you should do :
def loadList():
# Fill all the list first , make the readRecord() return eof (True or False).
while readRecord():
pass
# than process data (check for zip code) this will run it only one time
# but you can put it in a loop to repeat the action.
processRecords()
about your problem :
def processRecords():
userInput = raw_input(USERPROMPT)
# Check if a user has entered a text or not
if userInput:
# check the index from zipcode
if userInput in zipcode:
# the index of the zipcode in the zipcode list is the same
# to get related cities and states.
index_ = zipcode.index(userInput)
print "The city is %s and the state is %s " % \
(city[index_], state[index_])
else:
print "\nThe zip code does not exist."
else:
print "Please enter a data"
one of the beauties of Python is that it's interactive. if you take processRecords() out of loadList(), and then at the bottom of your program put:
if __name__ == '__main__':
processRecords()
Then, from the command prompt, type "python". You'll get the Python shell prompt, ">>>". There you type:
from zipcodes import * # this assumes your program is zipcodes.py
dir() # shows you what's defined
print zipCode # shows you what's in zipCode
that ought to help debugging.
Strings don't have an append method like lists do. What I think you're trying to do is append the strings zipCode, city, and state to parsedList. This is the code you'd use to do that:
parsedList.append(zipCode)
parsedList.append(city)
parsedList.append(state)
Or, even more compactly:
parsedList = [zipCode, city, state]
Let me know if you get another error message and I can offer more suggestions.

Categories