Seems while learning as I'm going with Python that I'm running into every little roadblock I can.
Even though this is a simply "if" I can't seem to get it to work, and i was wondering if its because my input (pgName) has full stops within the string. e.g com.android.driver.software.
In my example scenario, I will enter com.android.driver.software, what is listed within the Dict.value is com.android.driver.software.7 I thought using the comparison "in" would work in this instance, but it doesn't seem to be handling the logic at all.. What am i doing wrong?
pgName = raw_input("Please enter a package name e.g com.android.driver.software: ")
#while loop that checks user input from pgName to see if it matches any device
#listed in the JSON output and if so printing all the entires for that value.
while True:
try:
jdata = data["result"]["items"][y]["tagValues"]["IdDevicesMap"]["value"]
for device in jdata.values():
if pgName in device:
print jdata[device]
print " "
else:
print 'false'
When i run it everything is false.
Related
I am working on a program that updates/changes the element in a CSV folder. It first reads the CSV file list by list and checks if the serial number matches the one given by the user. If it does then it asks the user for the next element to change.
But in my program, the first IF loop is not running even though the conditions are satisfied. The serial number I tried entering was present in the list but it still wouldn't execute. Please look into this problem.
Here is my code.
def update():
f=open("daily.csv",'r')
r=csv.reader(f)
sno=int(input("WHICH RECORD DO YOU WANT TO UPDATE? (ENTER THE SERIAL NO.)"))
next(r)
for i in r:
if i[0]==sno:
ch=int(input("1.CHANGE CATEGORY (PRESS 1)2.CHANGE AMOUNT (PRESS 2)3.CHANGE DATE (PRESS 3)"))
if ch==1:
nc=input("PLEASE ENTER NEW CATEGORY")
i[1]=nc
print(i)
elif ch==2:
na=int(input("PLEASE ENTER THE NEW AMOUNT"))
i[2]=na
print(i)
elif ch==3:
nd=int(input("PLEASE ENTER THE NEW DATE"))
i[3]=nd
print(i)
else:
print("INVALID SERIAL NO")
f.close()
I believe the problem is that the values from the file are being read as string. Try converting the s[0] to int first then compare. Also, if you are using an IDE like pycharm, then use the inbuilt debugger to see the values and why they fail.
The problem may also be with the index of 's' that you are trying to access. If you don't have a debugger then try printing the value and the type of the values as that might help in the debugging process.
I'm trying to create a personnal password vault. Basically I want to create a program that asks me what I want to do and depending on my input (New, or Access "title of website here") the program either lets me add a website title with it's corresponding username and password. Then in I type "Access..." i should get the username and password returned relative to the website's tite I input after the Access input. OFC all of this data is to be stored in a text file.
PROBLEM:
The problem is that when I check the text file, it stays blank. I tried changing the access mode (a, r, etc) and it doesn't work. Not only that, but the program returns only the last data entered, and not whichever data in select.
Keep in mind I'm a beginner.
Below is the code used:
vault = open("Passvault.txt", "a")
total = True
while total == True:
creation = True
action = input("What do you want to do? ")
if action == "New" or action == "new":
title = input("Add website: ")
username = input("Create username: ")
password = input("Create password: ")
vault.write("Title:" + username)
vault.write("\n")
vault.write("Username:" + username)
vault.write("\n")
vault.write("Password:" + password)
elif action == "Access " + title:
print(title)
print("Username: " + username)
print("Password: " + password)
creation = False
elif action == "Close":
creation = False
total = False
vault.close()
First of all, you are not reading the file. Reading AND writing in 'append' ('a') mode is a bad idea (see potential cursor issues).
I tested the code on Google Colab and it works. Note that the writing occurs only if you close the file.
Suggestions:
It is a good time to learn about databases. Even a simple Excel file would fit your goal better (check package csv).
Use 'a+' as the mode of opening the file: if the file does not exist, create it.
Try to open and close the file a bit more frequently, say, each time when you want to write something. Also with clause may be useful (https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files)
First of all, where do you define the variable title used in the elif condition. Another that how you are reading the file for title. Third and most important that your problem clearly mentions is that you are not seeing results being saved and that is because you don't close the file instantly and close method actually writes all data and saves the file in the end. Another way to save data before closing the file is by using the flush method.
Try this code:
vault = open("Passvault.txt", "a")
total = True
while total == True:
creation = True
action = input("What do you want to do? ")
if action.lower() == "new":
title = input("Add website: ")
username = input("Create username: ")
password = input("Create password: ")
vault.write("Title:" + username)
vault.write("\n")
vault.write("Username:" + username)
vault.write("\n")
vault.write("Password:" + password)
elif action == "Access " + title:
print(title)
print("Username: " + username)
print("Password: " + password)
creation = False
elif action == "Close":
creation = False
total = False
vault.close()
You didn't close the file at the end.
First of all you seem to be a bit confused how everything is working here so lets me clarify and then I will point out all the problems.
You first create a variable vault and assign it to file opened via append(a) mode.
Now append mode is used generally to append data, here you want to both read and write
data so you need to use read and write permission(r+).
Second , you are trying to create a vault and don't encrypt it any way. the problem is
that anyone can see it as a plain text by opening that file.
Now you set total to True and then use it for infinite while loop.
The problem here is that you can directly do while True so that loop continues
forever and you don't need to assign total a value of True because it doesn't need to
be changed as you can use break keyword to break out of loop. You just wasted memory
by assigning variable to True
Now inside the while loop, you create creation variable but never use it for a purpose, so it is I think not needed or you might have another plan and might use it in the future so I won't say about it.
Now you get input from the user and set it's value to action variable. This step is OK but I wan't to clarify that there are several security problems here but since they are very complex so I won't tell them here but this should be OK.
Now's the time of conditions:
Now in first if condition, you check is action == 'New or action == 'new', here you don't need to includeor` , although that's okay and there is no problem with it, you can do better. .lower() is a string method and it lower cases all the letters of the alphabet.
Either you can do if action.lower() in ['new' , 'create' , 'n' ....all inputs you want ] , note here you dont have to include '.....all inputs you want' , Its just to tell you that you need to put there all inputs on which you want the condition to be true.
Or you can simply do if action.lower() == 'new'
Now only if the condition is true this code runs
You create title variable and set it to user input, now here's too security problem but due to complexity I won't go into much deep. Always remember , wherever you have user interaction with application , there's a chance of security problem there.
Then you get the password and same problem. But also notice that you don't encrypt anything here. That's a big issue.
Now you write everything to the file but be aware that .write() doesn't write directly. You either have to call .flush() or close the file via .close() . But notice the problem , you called .close() but in the very end and out of the infinite while loop. You can tell that that close command is out of while loop by telling that both while loop and close are at the same level. If you have to put it inside while loop, you need to indent it a bit just like other code which is inside while loop. But that is also not gonna work because you close the file and you can't reuse it withot reopening it so either you put both open and close parts inside while loop or you use the .flush() method. This is the biggest bug due to which you are facing such a problem.
Now's the time of elif conditon
Here you see that in the condition you do if action == 'Access ' + title: and there are several problems here.
First you see that you directly compare action to access and you can do it better by using that list trich used in above if condition and can use .lower() method
Second that you use the title variable which notice only get defined when the above if condition runs. What if the above if condition doesn't run and what is the user directly said 'Access Google" or anything accept the above if condition such as "#^%&GJ" . Then elif condition will run and your variable title will not be found by python and then your program will crash. So it is better that you first search that if the input contains Access and the break it into Access And The keyword after it. There are several functions you can use like .strip() or others. Visit this link fore more methods.
Third, you are using the file cursor without being aware of it. Just like cursor in any text editor, the file handler also has a cursor which move foreward as you read the file and in the end it will reach the end of the file and once again you read , it wont return anything since there's nothing ahead of it. To know more about it, visit this link.
And these were the main problems due to which your code is not working correctly
There are also many more problems such as
Your way of reading from file
Your way of writing to the file
No error handling
Your way of closing the file
Your way of handling file
No encryptions
Security problems
Etc.
But for now, that's gonna help you in your task.
Good Luck And Smart Work!
So I have been struggling with this issue for what seems like forever now (I'm pretty new to Python). I am using Python 3.7 (need it to be 3.7 due to variations in the versions of packages I am using for the project) to develop an AI chatbot system that can converse with you based on your text input. The program reads the contents of a series of .yml files when it starts. In one of the .yml files I am developing a syntax for when the first 5 characters match a ^###^ pattern, it will instead execute the code and return the result of that execution rather than just output text back to the user. For example:
Normal Conversation:
- - What is AI?
- Artificial Intelligence is the branch of engineering and science devoted to constructing machines that think.
Service/Code-based conversation:
- - Say hello to me
- ^###^print("HELLO")
The idea is that when you ask it to say hello to you, the ^##^print("HELLO") string will be retrieved from the .yml file, the first 5 characters of the response will be removed, the response will be sent to a separate function in the python code where it will run the code and store the result into a variable which will be returned from the function into a variable that will give the nice, clean result of HELLO to the user. I realize that this may be a bit hard to follow, but I will straighten up my code and condense everything once I have this whole error resolved. As a side note: Oracle is just what I am calling the project. I'm not trying to weave Java into this whole mess.
THE PROBLEM is that it does not store the result of the code being run/executed/evaluated into the variable like it should.
My code:
def executecode(input):
print("The code to be executed is: ",input)
#note: the input may occasionally have single quotes and/or double quotes in the input string
result = eval("{}".format(input))
print ("The result of the code eval: ", result)
test = eval("2+2")
test
print(test)
return result
#app.route("/get")
def get_bot_response():
userText = request.args.get('msg')
print("Oracle INTERPRETED input: ", userText)
ChatbotResponse = str(english_bot.get_response(userText))
print("CHATBOT RESPONSE VARIABLE: ", ChatbotResponse)
#The interpreted string was a request due to the ^###^ pattern in front of the response in the custom .yml file
if ChatbotResponse[:5] == '^###^':
print("---SERVICE REQUEST---")
print(executecode(ChatbotResponse[5:]))
interpreter_response = executecode(ChatbotResponse[5:])
print("Oracle RESPONDED with: ", interpreter_response)
else:
print("Oracle RESPONDED with: ", ChatbotResponse)
return ChatbotResponse
When I run this code, this is the output:
Oracle INTERPRETED input: How much RAM do you have?
CHATBOT RESPONSE VARIABLE: ^###^print("HELLO")
---SERVICE REQUEST---
The code to be executed is: print("HELLO")
HELLO
The result of the code eval: None
4
None
The code to be executed is: print("HELLO")
HELLO
The result of the code eval: None
4
Oracle RESPONDED with: None
Output on the website interface
Essentially, need it to say HELLO for the "The result of the code eval:" output. This should get it to where the chatbot responds with HELLO in the web interface, which is the end goal here. It seems as if it IS executing the code due to the HELLO's after the "The code to be executed is:" output text. It's just not storing it into a variable like I need it to.
I have tried eval, exec, ast.literal_eval(), converting the input to string with str(), changing up the single and double quotes, putting \ before pairs of quotes, and a few other things. Whenever I get it to where the program interprets "print("HELLO")" when it executes the code, it complains about the syntax. Also, from several days of looking online I have figured out that exec and eval aren't generally favored due to a bunch of issues, however I genuinely do not care about that at the moment because I am trying to make something that works before I make something that is good and works. I have a feeling the problem is something small and stupid like it always is, but I have no idea what it could be. :(
I used these 2 resources as the foundation for the whole chatbot project:
Text Guide
Youtube Guide
Also, I am sorry for the rather lengthy and descriptive question. It's rare that I have to ask a question of my own on stackoverflow because if I have a question, it usually already has a good answer. It feels like I've tried everything at this point. If you have a better suggestion of how to do this whole system or you think I should try approaching this another way, I'm open to ideas.
Thank you for any/all help. It is very much appreciated! :)
The issue is that python's print() doesn't have a return value, meaning it will always return None. eval simply evaluates some expression, and returns back the return value from that expression. Since print() returns None, an eval of some print statement will also return None.
>>> from_print = print('Hello')
Hello
>>> from_eval = eval("print('Hello')")
Hello
>>> from_print is from_eval is None
True
What you need is a io stream manager! Here is a possible solution that captures any io output and returns that if the expression evaluates to None.
from contextlib import redirect_stout, redirect_stderr
from io import StringIO
# NOTE: I use the arg name `code` since `input` is a python builtin
def executecodehelper(code):
# Capture all potential output from the code
stdout_io = StringIO()
stderr_io = StringIO()
with redirect_stdout(stdout_io), redirect_stderr(stderr_io):
# If `code` is already a string, this should work just fine without the need for formatting.
result = eval(code)
return result, stdout_io.getvalue(), stderr_io.getvalue()
def executecode(code):
result, std_out, std_err = executecodehelper(code)
if result is None:
# This code didn't return anything. Maybe it printed something?
if std_out:
return std_out.rstrip() # Deal with trailing whitespace
elif std_err:
return std_err.rstrip()
else:
# Nothing was printed AND the return value is None!
return None
else:
return result
As a final note, this approach is heavily linked to eval since eval can only evaluate a single statement. If you want to extend your bot to multiple line statements, you will need to use exec, which changes the logic. Here's a great resource detailing the differences between eval and exec: What's the difference between eval, exec, and compile?
It is easy just convert try to create a new list and add the the updated values of that variable to it, for example:
if you've a variable name myVar store the values or even the questions no matter.
1- First declare a new list in your code as below:
myList = []
2- If you've need to answer or display the value through myVar then you can do like below:
myList.append(myVar)
and this if you have like a generator for the values instead if you need the opposite which means the values are already stored then you will just update the second step to be like the following:
myList[0]='The first answer of the first question'
myList[1]='The second answer of the second question'
ans here all the values will be stored in your list and you can also do this in other way, for example using loops is will be much better if you have multiple values or answers.
I am a complete python novice, learning how to code using some training videos (which have me using Python 2). In working through one exercise, I generated the below code to create a url dictionary. The video dictated that with the below code, inputting a blank input would lead to the break and end the sequence, but instead, I am taken to the "an error has occurred" message within the except code. This happens regardless of whether I type in an incorrect url or blank. What have I done wrong in the code that has caused this?
Secondly, when I reach the stopproceed function in the code and type in anything other than 1, the loop returns an error message rather than continuing as I had intended.
Any help anyone can provide would be very helpful to a total newb who does not yet have the knowledge to troubleshoot for themselves! Thanks!
while urltoread != '':
try:
urltoread = input("Please enter the next url to crawl ")
if urltoread == "":
print "OK, good loop!"
break
shortname = input("Please input a short name for this url "+ urltoread)
webfile = urllib2.urlopen(urltoread).read()
crawlweblinks[shortname] = webfile
except:
print "An error has occured, dummy",sys.exc_info()[0]
stoporproceed = input("Enter 1 to Stop, or enter anything else to continue")
if stoporproceed ==1 :
print "You got it!\n"
break
else:
print "On we go!\n"
continue
print "This line is inside the while loop"
print "This line is outside the while loop"
print crawlweblinks.keys()
I've been working on a login and signup code that is not connected to the cloud. To login, you must enter a username and password, and it will return you with a simple; "Hello, "
I've tried converting the element to a string, but I couldn't find anything else online to help me. It could possibly be that the program I'm using doesn't display an output properly.
inorup=""
newuser=""
users=["jdoe,tractor5","carrey1,1997","admin,56f67dk2997m"]
firstnuser=["John","Carrey","Frederick"]
while inorup != "login" or inorup != "signup":
inorup=raw_input("Would you like to login or signup? ")
if inorup=="login":
userpass=raw_input("Enter <username,password>: ")
if userpass in users:
userpassfnamepos=int(users.index(userpass))-3
print("Hello",str(firstnuser[userpassfnamepos])+".")
#Returning:
Would you like to login or signup? login
Enter <username,password>: jdoe,tractor5
('Hello', 'John')
#Expected Return:
Would you like to login or signup? login
Enter <username,password>: jdoe,tractor5
Hello John.
You should split your string on the ',' and check username password against a dictionary like {username:password}, or use a database or something. Checking string as you do now is kind of limiting and unwieldy.
But to just fix your output, you can change your print to this
print("Hello {}.".format(firstnuser[userpassfnamepos]))
using string.format() also does all the casting and such so you could pass in numbers or whatever you want, not just name. More info Here
and you will get the expected output.
output =
Would you like to login or signup? login
Enter :
jdoe,tractor5
Hello John.
You are already using normal string concatenation to add the period. Why not just do that with the name as well? You also don't need the str in front, since the list is already a list of strings, and so the element in question is already a string.
print("Hello" + " " + firstnuser[userpassfnamepos] + ".")
>>>Would you like to login or signup? login
>>>Enter <username,password>: jdoe,tractor5
>>>Hello John.
Looks like you are mixing python 2 and 3. raw_input id python 2 and in Python 3 it's only input. also, you should use brake to break out of the loop at appropriate places. You have an infinite loop. Lately, the code is printing "Hello John" for me as it's supposed to. However, you don't have to convert the list element to string, it is already a string (therefore returns the same value with or without converting.
I think the reason it's giving you ('Hello', 'John') as output is because it's printing the parenthesis themselves (but that does not make logical sense because they are not included in the string. Anyways note that python 2 print statement is as follows: print "this is to be printed" . there is no parenthesis. Make use of the vertion of python you are using and that your code matches the version.
One additional note, if you are not using a database, maybe use a python dictionary instead of a python list. Not only it's faster and memory efficient, it also makes it easier to work with. it can be something like {username : ("name" , "password")} a combination of a dictionart and a tuple or more explicit {username : {name: "name" , password: "password"}}, which saves a sigle's user data in a dictionary inside a dectionary containing all the users.