"NameError: name is not defined" for user input [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am new to python and made a short script to try them out, while doing so I came across and error I've never had for the particular situation before, when I try to define uN as a str inputted by the user I get:
Traceback (most recent call last):
File "/home/pi/Desktop/Scripts/classTest/classTest1.py", line 14, in <module>
uN = input(str("Username"))
File "<string>", line 1, in <module>
NameError: name 'ben' is not defined
The code is as follows:
class user:
def __init__(self, usrName, pWord):
self.usrName = usrName
self.pWord = pWord
def createUsrPw(self):
f = open("usrName.txt", "a")
f.write(self.usrName)
f.write(" ")
f.write(self.pWord)
f.write("\n")
f.close()
uN = input(str("Username"))
pW = input(str("Password"))
usr1 = user(uN, pW)
usr1.createUsrPw()
I have used the x = input(str()) syntax a lot before and never had this error, and the error traces back to line 1, so is uN = input(str("Username")) still being considered a part of the class?
when I simplify the code to this it works perfectly:
class user:
def __init__(self, usrName, pWord):
self.usrName = usrName
self.pWord = pWord
def createUsrPw(self):
f = open("usrName.txt", "a")
f.write(usrName)
f.write(" ")
f.write(pWord)
f.write("\n")
f.close()
usr1 = user("Ben", "testPw")
usr1.createUsrPw()
with the file usrName.txt being appended to include "Ben testPw" as intended.

You should use raw_input instead of input as you are using Python 2.X. input works in Python 3.
This code would work:
class user:
def __init__(self, usrName, pWord):
self.usrName = usrName
self.pWord = pWord
def createUsrPw(self):
f = open("usrName.txt", "a")
f.write(self.usrName)
f.write(" ")
f.write(self.pWord)
f.write("\n")
f.close()
uN = raw_input("Username")
pW = raw_input("Password")
usr1 = user(uN, pW)
usr1.createUsrPw()

Use raw_input. This looks like a Python 2 error, I don't think you're using Python 3
You also don't need to call str on a string literal. str("asdf") == "asdf"

Related

how to print the exception from exce? My code is in string. It works fine on the correct code snippet. not on error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 days ago.
This post was edited and submitted for review 4 days ago and failed to reopen the post:
Not suitable for this site
Improve this question
import os
path = "C:\\Users\\Abdul Rafay\\Downloads\\Compressed\\day3_t1\\day3_t1"
file_name = os.listdir(path)
word1 = "email"
word2 = "return"
word3 = "def"
x = ""
y = "5"
for i in file_name:
path1 = os.path.join(path, I)
with open(path1, 'r') as fp:
lines = fp.readlines()
for line in lines:
if line.find(word1) != -1:
print("File: ",path1)
print("Email: ",line.strip("email= "))
elif line.find(word2) != -1 or line.find(word3) != -1:
x += line
if 'def' in x and 'return' in x:
print("Solution(5): ")
exec(x + """
try:
print(solution("""+str(y)+"""))
except Exception as err:
print(err)
""")
print("=========================")
x = ""
#The End---------------------------------------The End
Type 1 (with Error)
Type 2 (No Error)
I am reading the "solution" method from these files. and pass the parameter using exec and execute the function.
But the problem is when there is no error in the code it works fine but if there is a error it doesn't show the exception.
This is the output. when there is error it prints the particular function multiple times.

python sintaxError: invalid sintax , else: [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I get this invalid syntax error:
File "./data_3.0.1.py", line 148
else:
^
SyntaxError: invalid syntax
When I try to run this function:
def funzione_aggiornamento_prezzi(titolo):
pprint ("titolo " + titolo)
#parametri per scaricare lo storico dei prezzi
params = {'item': titolo,
'frequency': 'TBT',
'dataDa':x_giorni_fa()}
try:
r = requests.get(myurl, params=params)
except:
pprint("Si e' verificato un errore")
else:
pprint(r.status_code)
pprint(r.url)
new_list = crea_lista(r)
#codice per scrivere su di un csv da una lista
nomen = "%s.TBT.csv" % (titolo)
csvfile = open(nomen, 'a')
reportwriter = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL)
#codice per scrivere su di un csv
# controllo del numero di rows nel file
with open(nomen,"r") as f:
reader = csv.reader(f,delimiter = ",")
data = list(reader)
row_count = len(data)
if row_count == 0:
for i in new_list:
da_appendere = new_list[i+1]
reportwriter.writerow(da_appendere)
csvfile.close()
#here I get the error
else:
with open(nomen, 'rb') as f:
last_timestamp = f.readlines()[-1].split(",")[0]
#codice per aggiungere al csv solo i nuovi dati
found_it = 0
for i in new_list:
if i == last_timestamp:
found_it = 1
if found_it == 1:
da_appendere = new_list[i+1]
reportwriter.writerow(da_appendere)
csvfile.close()
for i in lista_indici:
funzione_aggiornamento_prezzi(i)
I don't understand what is the problem... Maybe is something very easy but.. I don't really see it!!
Basically what I want to do is say to python if the csv file you're opening is empty simply attach the new list otherwise attach only the elements from the new list that are not already in the csv file you just opened
Thanks
The line csvfile.close() is outdented to be level with the if above it so terminates that if - so you have an else: when you are not in an if. You also need to fix the indentation of the line after the with

while true loop in python can't be stopped [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a problem with this loop in python:
i = 1
while True:
with open('/tmp/file.txt', 'r+') as f:
for line in f:
work = 'word1' + line + 'word2' + line + 'counter=' + str(i) + 'test'
result = Function()
if "statement" in result:
out = open('/tmp/result.txt', 'a+')
out.write(result)
out.close()
i = i + 10
else:
return i
I want first read file.txt line by line and then for each line count i till statement exists in result but this loop is infinitive... So I removed break and used return i instead. but no result
How can I tell the while True loop to be stopped when all lines from file.txt is read and for each line counter is completed?
UPDATE
what I want to process:
word1line1word2line1counter=1test
word1line1word2line1counter=2test
word1line1word2line1counter=3test
.
.
.
#`till my if condition is true` then
word1line2word2line2counter=1test
word1line2word2line2counter=2test
word1line2word2line2counter=3test
.
.
.
and so on
Thanks
I think you need to switch your loops around:
i = 1
with open('/tmp/file.txt', 'r+') as f:
for line in f:
result = ...
while "statement" in result:
with open('/tmp/result.txt', 'a+') as out:
out.write(result)
i += 10
result = ...
Although it is not at all clear what this algorithm is supposed to be doing
I found the answer:
out = open('/tmp/result.txt', 'a+')
with open('/tmp/file.txt', 'r+') as f:
for line in f:
i = 1
line=line.strip('\r\n ')
while True:
work = 'word1' + line + 'word2' + line + 'counter=' + str(i) + 'test'
print work
result = Function()
if "statement" in result:
out.write(result)
i += 10
else:
break
out.close()

Python Code Error 3.3.2

I have recently been practicing my skills at figuring out my own problems but this one problem is persistent. This is the problematic code:
with open('login_names.txt', 'r') as f:
login_name = [line.rstrip('\n') for line in f]
k = input("name: ")
if k in login_name :
print("No errors")
else:
print("You have an error")
else:
print('fail')
#var = login_name.index[random]
check = login_pass[login_name.index[random]]
with open('login_passw.txt', 'r') as p:
login_pass = [line.rstrip('\n') for line in p]
s = input("pass: ")
if s == check :
print("Works")
else:
print("Doesn't work")
f.close()
p.close()
Basically when I run the code it says:
Traceback (most recent call last):
File "C:/Python33/Test.py", line 29, in <module>
check = login_pass[login_name.index[random]]
TypeError: 'builtin_function_or_method' object is not subscriptable
I have tried lots of different suggestions on different questions but none of them have worked for me...
If we assume that login_pass, login_name and random are defined in the namespace that line is in, the only problem you have is that you should write
check = login_pass[login_name.index(random)]
str.index is a function that returns the first index of the argument given in str, so you use () instead of [], which you would use for lists, tuples and dictionaries.

Getting user input [duplicate]

This question already has answers here:
How to read keyboard input?
(5 answers)
Closed 4 years ago.
I am running this:
import csv
import sys
reader = csv.reader(open(sys.argv[0], "rb"))
for row in reader:
print row
And I get this in response:
['import csv']
['import sys']
['reader = csv.reader(open(sys.argv[0]', ' "rb"))']
['for row in reader:']
[' print row']
>>>
For the sys.argv[0] I would like it to prompt me to enter a filename.
How do I get it to prompt me to enter a filename?
Use the raw_input() function to get input from users (2.x):
print "Enter a file name:",
filename = raw_input()
or just:
filename = raw_input('Enter a file name: ')
or if in Python 3.x:
filename = input('Enter a file name: ')
In python 3.x, use input() instead of raw_input()
sys.argv[0] is not the first argument but the filename of the python program you are currently executing. I think you want sys.argv[1]
To supplement the above answers into something a little more re-usable, I've come up with this, which continues to prompt the user if the input is considered invalid.
try:
input = raw_input
except NameError:
pass
def prompt(message, errormessage, isvalid):
"""Prompt for input given a message and return that value after verifying the input.
Keyword arguments:
message -- the message to display when asking the user for the value
errormessage -- the message to display when the value fails validation
isvalid -- a function that returns True if the value given by the user is valid
"""
res = None
while res is None:
res = input(str(message)+': ')
if not isvalid(res):
print str(errormessage)
res = None
return res
It can be used like this, with validation functions:
import re
import os.path
api_key = prompt(
message = "Enter the API key to use for uploading",
errormessage= "A valid API key must be provided. This key can be found in your user profile",
isvalid = lambda v : re.search(r"(([^-])+-){4}[^-]+", v))
filename = prompt(
message = "Enter the path of the file to upload",
errormessage= "The file path you provided does not exist",
isvalid = lambda v : os.path.isfile(v))
dataset_name = prompt(
message = "Enter the name of the dataset you want to create",
errormessage= "The dataset must be named",
isvalid = lambda v : len(v) > 0)
Use the following simple way to interactively
get user data by a prompt as Arguments on what you want.
Version : Python 3.X
name = input('Enter Your Name: ')
print('Hello ', name)

Categories