i know there are a lot of people asking a similar question and i also understand what the answers are trying to say but no matter what i try,it just doesnt work.
someone help!
here is my code (well a shorter version)
import random
##opening all the files and reading them line by line.
file_1 = open("devices.txt","r")
read_1 = file_1.readlines()
file_2 = open("phones.txt","r")
read_2 = file_2.readlines()
def choose_device():##creating function
device = input(read_1[0]).lower()##asking the user by printing a question from file_1
if device == "phone" or device == "phones" or device == "smartphone" or device == "smartphones" or device == "1":
brand = input(read_2[0])
if brand == "samsung":
version = input(read_2[1])
raw_memory = input(read_2[4])
solution_for_phones()
elif brand == "iphone":
version = input(read_2[2])
raw_memory = input(read_2[4])
solution_for_phones()
elif brand == "sony":
version = input(read_2[3])
raw_memory = input(read_2[4])
solution_for_phones()
else:
print(read_2[5])
do_again()##restart
def solution_for_phones():
datadict = {} ##creating a dictionary
with open('phonesolution.txt') as file: ##opening file
for rec in file: ##looping through every line
rec = rec.split(':') ##delimiter is :
problem = rec[0] ##first values before the delimiter are saved as problems
answer = rec[1] ##second values after the delimiter are saved as answers
problem = problem.split(" ") ##problems is further split by the delimiter "space"
for item in problem: ##every word in the problem section is assigned to an answer
datadict[item] = answer
user_problem = input('What is the problem?: ')##asking the user where the problem is
split_answer = user_problem.split(" ")##splitting the users answer into separate words
for option in datadict.keys():
if option in split_answer:##mathcing the users answer to keywords in the problem
print(datadict[option])
else:
CaseNo = (random.randrange(100000,999999))
print (CaseNo)
ReportFile = open('not_found.txt', 'a')
ReportFile.write ("\n"+"-------------------------------------------")
ReportFile.write ("\n"+"Case No is : "+str(CaseNo))
ReportFile.write ("\n"+"Case No is : "+(device))
ReportFile.close
do_again()
and here is the error message. anybody knows how to fix it?
welcome to our trouble shooting system
what device do you have a problem with? (these are the options:1.smartphones, 2.laptops, 3.game consoles)
smartphones
what brand is your phone? (eg: samsung, iphone)
samsung
what version is your samsung? (eg:J3, S7 edge)
J3
what is the memory size? (eg:8g, 16gb)
8
What is the problem?: vZrfvSZ
109451
Traceback (most recent call last):
File "C:\Users\hp\Downloads\A453\task 3\mine\task 3 just for practice.py", line 156, in <module>
choose_device()##calling the function
File "C:\Users\hp\Downloads\A453\task 3\mine\task 3 just for practice.py", line 110, in choose_device
solution_for_phones()
File "C:\Users\hp\Downloads\A453\task 3\mine\task 3 just for practice.py", line 58, in solution_for_phones
ReportFile.write ("\n"+"Case No is : "+(device))
NameError: name 'device' is not defined
Zwol's comment is the correct answer:
device is a local variable within choose_device. To make it accessible
from inside solution_for_phones you will have to pass it there as an
argument.
Here is how that works in code, since from your last comment it seems like you're still confused.
You define solution_for_phones with def solution_for_phones():. But it needs a value for device to work, since it uses device. So first change your function definition to:
def solution_for_phones(device):
Now solution_for_phones requires a value for device to be passed to it to run.
Next you need to make sure that everytime you call solution_for_phones, you pass a value for device. Everywhere in choose_device() where you have solution_for_phones(), you need to replace that with solution_for_phones(device).
You should also probably google something like "python passing values between functions" and read up some more on this, such as the difference between "positional" vs "keyword" parameters of functions.
Related
I think there is something wrong with my naming convention but I'm not sure how to fix it. it keeps giving me an invalid object even when tried to name it based on the vertex please help.
for i in range(1,100):
print i
def cactus():
#creating base of cactus
cmds.polyCylinder(sc=1,sa=10,sh=10, n= "cactus1_Base["+str(i)+"]")
The error I'm getting is:
# Error: TypeError: file <maya console> line 17: Object cactus1_Base[99].e[140:169] is invalid this is the error im getting and the code is
I dont have maya this week so I cant really check the result of this code
The first piece of codes woulld be for me the best solution but you have also the second one.
Note that in your code, character '[' and ']' are reserved in maya for components : vtx[], e[], f[]...etc
so you cant use them for naming
Secondly when you create your iteration 'i', it is outside your function so there is no real connection between i and your function cactus()
So you have to think on how you want to create cactus. That why I have written those two examples :
the first consider that you are creating cactus elements
the second one is just for creating a bunch of cactus
You could go beyond with kwargs and try to mimic cmds.polyCylinder
Just in case a bit python lessons for maya : https://www.youtube.com/watch?v=PDKxDbt6EGQ&t=4s
def nameChecker(name, start=0, max=100000, stringFormat=True):
if not '{' in name:
stringFormat = False
a = start
while a < max:
if stringFormat:
confName = name.format(a)
else:
confName = name + str(a)
if not cmds.objExists(confName):
return confName
a+=1
def create_cactus(baseName='cactus1_Base_{:03d}'):
name_conform = nameChecker(baseName)
cactus = cmds.polyCylinder(sc=1,sa=10,sh=10, n=name_conform)[0]
return cactus
cactus_output = []
for i in range(1,100):
cactus = create_cactus()
cactus_output.append(cactus)
print(cactus_output )
OR more simple :
def create_cactus(nb_of_cactus=100):
cactus_output = []
for nb in range(nb_of_cactus):
name = "cactus1_Base_{}".format(nb)
cactus = cmds.polyCylinder(sc=1,sa=10,sh=10, n=name)[0]
cactus_output.append(cactus)
return cactus
myCactus= create_cactus(100)
print(myCactus)
or based on selection :
def create_cactusVtx():
mysel = cmds.ls(sl=True, fl=True)
for i in range(len(mysel)):
id = mysel.split('[')[-1][:-1]
name = "cactus1_Base_{}".format(i)
cactus = cmds.polyCylinder(sc=1,sa=10,sh=10, n=name)[0]
I'm working on creating a short simple program for a nonprofit fundraiser to validate ticket numbers as guests check in to make sure no duplicate tickets are redeemed. I'm running Python 3.4.3 on a Windows 10 machine. Once the program is finalized it will be used on a Raspberry Pi with touchscreen at the fundraiser.
I've tried a couple different methods to build the list, save it, and search for duplicates. Ideally the list will be stored in a CSV file, but a plain text or other format is ok too.
Can you help me with the traceback error (TypeError: 'DictWriter' object is not iterable) due to the looping function to check ticket #'s against a list stored in a file to make sure no duplicate tickets are redeemed?
Thank you in advance for your help!
version = "v1.4"
fname="tickets.csv"
import csv
import datetime
import os.path
print("\nWelcome to TicketCheck", version)
extant = os.path.isfile(fname)
with open(fname, 'a', newline='') as csvfile:
fieldnames = ['ticketid', 'timestamp']
ticketwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
if extant == False:
ticketwriter.writeheader()
while True:
ticket = ""
print("Please enter a ticket # to continue or type exit to exit:")
ticket = str(input())
if ticket == "":
continue
if ticket == "exit":
break
print("You entered ticket # %s." % (ticket))
print("Validating ticket...")
for row in ticketwriter:
if row[0] == ticket:
print("\n\n\n===== ERROR!!! TICKET # %s ALREADY CHECKED IN =====\n\n\n" % (ticket))
continue
time = datetime.datetime.now()
print("Thank you for checking in ticket # %s at %s \n\n\n" % (ticket, time))
print("Ticket is now validated.")
ticketwriter.writerow({'ticketid': ticket, 'timestamp': time})
csvfile.flush()
continue
csvfile.close()
print("All your work has been saved in %s.\n Thank you for using TicketCheck %s \n" % (fname, version))
Hmm, I think you might be over-complicating this a bit! For something like that there's really no need to go to all that trouble. This is a great spot to use a dictionary, and for something with only two inputs, the id and the check-in time, you can easily just make a .txt log. I get the feeling this might be more of what you are looking for.
import time
go = True
while go:
the_guestlist = {}
the_ticket = input().strip()
file = open('somefile.txt', 'r')
for line in file:
my_items = line.split(',')
the_guestlist[my_items[0]] = my_items[1]
file.close()
if the_ticket in the_guestlist.keys():
print("Sorry, that ticket has been entered at {}".format(the_guestlist[the_ticket]))
elif the_ticket == 'exit':
go = False
print('Exiting...')
else:
the_guestlist[the_ticket] = '{}'.format(time.asctime())
file = open('somefile.txt', 'a')
file.write(the_ticket +','+the_guestlist[the_ticket]+'\n')
file.close()
Objects of the csv.DictWriter class are not iterable, i.e. you cannot iterate over them like you would a dictionary, list, or even string, hence your error message. It does not store the data you have previously written to file, only the file you wrote to stores that data.
To achieve your goal, you could do two things: either open your CSV file every time a new ticket needs to be validated, and check if the ticket number is present, or - since you are using relatively small amounts of data - store a dictionary in memory, and only write it out at the end of use, checking from that if the ticket is valid.
This is the error which comes up:
What type of device is it?phone
What make of phone is it? [Iphone, Samsung or other]samsung
Traceback (most recent call last):
File "C:\Users\Chris\Documents\Chris\School\School\computing\task 3 testing.py", line 79, in <module>
if ('4') in model_iphone:
NameError: name 'model_iphone' is not defined
I have no idea how to fix it. It would be helpful if someone could point out some potential problems with my code. I know its not the most efficient code but it would be great to have some help with it thanks.
My code:
apple_question = []
for row in apple_file:
apple_question.append(row)
other = open("task 3 other questions.csv")
other_file = csv.reader(other)
other_question = []
for row in other_file:
other_question.append(row)
pre_questions = open("task 3 pre questions.csv")
pre_questions_file = csv.reader(pre_questions)
pre_questions_question = []
for row in pre_questions_file:
pre_questions_question.append(row)
device_type = input(pre_questions_question[1][0])
device_type.lower()
if ('phone') in device_type:
make = input(pre_questions_question[2][0])
make.lower()
elif ('iphone')in make:
model_iphone = input(samsung_question[1][0])
model_iphone.lower()
elif ('samsung') in make:
model_samsung = input(samsung_question[1][0])
model_samsung.lower()
elif ('other') in make:
make_other = input(other_question[0][0])
make_other.lower()
model_other = input(other_question[1][0])
model_other.lower()
problem_other = input(other_question[2][0])
problem_other.lower
info = print(other_question[3][0])
#other
text_file = open('Otherdevice.txt', 'w' )
text_file.write(make_other)
text_file.write(model_other)
text_file.write(problem_other)
text_file.close()
#apple
if ('4') in model_iphone:
ios = input(apple_question[3][0])
elif ('5') in model_iphone:
ios = input(apple_question[3][0])
elif ('5c') in model_iphone:
ios = input(apple_question[3][0])
if ('7') in ios:
memory = input(apple_question[4][0])
elif ('8') in ios:
memory = input(apple_question[4][0])
elif ('9') in ios:
memory = input(apple_question[4][0])
else:
print("Sorry but you have entered invalid or not surported information please try again")
if ('8gb') in memory:
query = input(apple_question[5][0])
elif ('16gb') in memory:
query = input(apple_question[5][0])
elif ('32gb') in memory:
query = input(apple_question[5][0])
#samsung
if ('s4') in model_samsung:
android = input(samsung_question[2][0])
elif ('s5') in model_samsung:
android = input(samsung_question[2][0])
elif ('s6') in model_samsung:
android = input(samsung_question[2][0])
else:
print("Sorry but you have entered invalid or not surported information please try again")
if ('jellybean') in android:
service_provider = input(samsung_question[3][0])
elif ('lollipop') in android:
service_provider= input(samsung_question[3][0])
elif ('marshmallow') in android:
service_provider = input(samsung_question[3][0])
It's kind of hard to follow what's going on in your code, but from what I can see, it looks like you're never making the variable model_iphone. Instead it seems like, since you're inputting "samsung", the code is making a variable called model_samsung, which does the same thing. Instead of making all these different variables that do the same thing (and only ever initializing one of them), try just making one uniform variable:
#Previous code...
#check for device type
if ('phone') in device_type:
make = input(pre_questions_question[2][0])
make.lower()
#separate if statement block to process the make and model after determining the type
if ('iphone')in make: #I CHANGED THIS LINE AS WELL TO WHAT YOU INTENDED IT TO DO (I think)
model = input(samsung_question[1][0])
model.lower()
elif ('samsung') in make:
model = input(samsung_question[1][0])
model.lower()
elif ('other') in make:
make_other = input(other_question[0][0])
make_other.lower()
model = input(other_question[1][0])
model.lower()
problem_other = input(other_question[2][0])
problem_other.lower
info = print(other_question[3][0])
#other
text_file = open('Otherdevice.txt', 'w' )
text_file.write(make_other)
text_file.write(model)
text_file.write(problem_other)
text_file.close()
#apple
#ask the corresponding questions
if ('4') in model:
ios = input(apple_question[3][0])
#Continue code...
Note how all the inputs to the same question now all channel into the same variable, so that no matter what part of the if block is called, it will always initialize the variable you need, so that you can process later (I used model in the example).
It's also important to note that in an if block, if one part of the if block is used (the first one found when reading down), then all the other elif statements afterwords are ignored as well. If you want two unrelated if statements, you'd create the following code:
if statement1:
#code here
elif statement2:
#code not executed if statement1 is true
if statement3:
#code executed, regardless of whether or not
#either of the above statements are true or not
In this example, statements 1 and 2 are part of one if block, while statement 3 is part of another block. That might help fix some problems in your code as well. Good luck on coding, and keep at it!
So I wrote this code
spec = raw_input("Enter the specimen number: ")
naorimp = raw_input("Native or Implant (N/I)? ")
trial = raw_input("Trial number: ")
typana = raw_input("What do you want to analyze (contact area[CA]/contact pressure[CP])? ")
try :
if typana.lower() == "cp" :
naorimp = naorimp.upper()
TSfilnm = 'pressure'+spec+naorimp.upper()+trial+'.txt'
else :
naorimp = naorimp.upper()
TSfilnm = 'area'+spec+naorimp+trial+'.txt'
TSfile = open(TSfilnm, 'r')
myofilnm = 'accelerometer'+spec+naorim.upper()+trial+'.txt'
print myofilnm
myofile = open(myofilnm, 'r')
except :
print "File could not be found."
print "Please re-run the program."
exit()
print "OK"
I want to open a file based on user's input and several parameters (specimen no., native or implant, trial no., and type of analysis.) The file is already in the same folder as the python file code. But when I run the program I always end up with except statements (File could not be found. Please re-run the program). I have double-checked the real file name and the string inside the TSfilnm variable, and they are the same. However, the TSfile could not be executed.
P.S. The file name in my folder is: pressure3N1.txt, area3N1.txt, accelerometer3N1.txt
You are missing a p in the variable name in this line
myofilnm = 'accelerometer'+spec+naorim.upper()+trial+'.txt'
should be
myofilnm = 'accelerometer'+spec+naorimp.upper()+trial+'.txt'
Also don't use 'except' alone during development, it will only hide errors like in this case. It's better to do something like.
import sys
try:
#Your_code_here
except:
print sys.exc_info()[1]
#Any other code you wanna run
this is a code from a chat bot, and it's purpose is to save into a file all information about an user. That will work fine as long as it's only in 1 room, but if i want to save information of the same user in 2 different rooms, i got a problem. The bot won't just update the information getting the user and the room, instead it will always create new and new lines of that user and that room.
It's getting annoying and i would really like to not break this code a lot, so i'd like to know where it fails and how to fix it in a proper way without using dicts. (You can read all the comments inside the code to understand how i think it works).
Thank you for your time.
#First of all it reads the file
leyendoestadisticas = open("listas\Estadisticas.txt", "r")
bufferestadisticas = leyendoestadisticas.read()
leyendoestadisticas.close()
if not '"'+user.name+'"' in bufferestadisticas: #If the name of the user is not there, it adds all the information.
escribiendoestadisticas = open("listas\Estadisticas.txt", 'a')
escribiendoestadisticas.write(json.dumps([user.name, palabrasdelafrase, letrasdelafrase,
"1", user.nameColor, user.fontColor, user.fontFace, user.fontSize,
message.body.replace('"', "'"), room.name, 0, "primermensajitodeesapersona", fixedrooms])+"\n")
escribiendoestadisticas.close()
else: #If the name it's there, it will do the next:
#First of all, get all rooms where the name is saved, to do that...
listadesalas = []
for line in open("listas\Estadisticas.txt", 'r'):
retrieved3 = json.loads(line)
if retrieved3[0] == user.name: #If the name is found
if not retrieved3[9] == room.name: #But room is diferent
listadesalas.append(retrieved3[9]) #Adds the room to a temporal list
#Now that we got a list with all different lines of that user based on rooms... we do the next code
data = []
hablaenunanuevasala = "no"
with open('listas\Estadisticas.txt', 'r+') as f:
for line in f:
data_line = json.loads(line)
if data_line[0] == user.name: #If name is there
if data_line[9] == room.name: #And the room matches with actual room, then update that line.
data_line[1] = int(data_line[1])+int(palabrasdelafrase)
data_line[2] = int(data_line[2])+int(letrasdelafrase)
data_line[3] = int(data_line[3])+1
data_line[4] = user.nameColor
data_line[5] = user.fontColor
data_line[6] = user.fontFace
data_line[7] = user.fontSize
data_line[11] = data_line[8]
data_line[8] = message.body.replace('"', "'")
data_line[9] = room.name
data_line[12] = fixedrooms
else: #but if the user is there and room NOT matches, we want to add a new line to the file with the same user but a new room.
if not room.name in listadesalas: #And here is where i believe is the problem of my code.
hablaenunanuevasala = "si" #needed since i didn't found a way to properly add a new line inside this loop, so must be done outside the loop later.
data.append(data_line)
f.seek(0)
f.writelines(["%s\n" % json.dumps(i) for i in data])
f.truncate()
#Outside the loop - This would work if the program noticed it's a room that is not saved yet in the file for that user.
if hablaenunanuevasala == "si":
escribiendoestadisticas2 = open("listas\Estadisticas.txt", 'a')
escribiendoestadisticas2.write(json.dumps([user.name, palabrasdelafrase, letrasdelafrase,
"1", user.nameColor, user.fontColor, user.fontFace, user.fontSize,
message.body.replace('"', "'"), room.name, 0, "primermensajitodeesapersona", fixedrooms])+"\n")
escribiendoestadisticas2.close()
So... that's what i tried, and it works perfect as long as it's 1 room, it updates the info all the time. When i speak in a second room, it adds me a new record with that second room (perfect). But then if i speak again in ANY of those 2 rooms, the bot will add 2 more lines of code to the file instead of updating the information of the room where i did speak.
Edit Let me summarize it:
Let's say I speak in "whenever" room, the file will save a record
["saelyth", "whenever", "more info"]
If i speak in another room, the file should save a record
["saelyth", "anotherroom", "more info"]
It works great... but then it doesn't update the info. If now i speak in any of those 2 rooms, instead of updating the proper line, the bot will add more new lines into the file, wich is the problem.
Fix done... somehow.
I did choose to save info into different files for each room, that works.