beginer question:
I often have to repeat the same line of code 10 times for 10 different variables (i read you can't or should not create variable dynamically)
I thought to help me once i written it once I could iterate with a find replace (I am currently doing it in word)
I wrote this but get tons of error when i input code like if console trying to execute the code. what am i missing? is it because i paste it i the console does it need to be imported from a ext file ?
LineOfCode = input("Enter the code you want to iterate the iteration variable need be 8")
for i in range(10):
LineOfCode.replace("8",str(i))
print(LineOfCode)
Your code is almost correct:
String.replace() returns a new string with the changes, doesn't change the existing string. So the code should be like:
LineOfCode = input("Enter the code you want to iterate the iteration variable need be 8")
for i in range(10):
var = LineOfCode.replace("8", str(i))
print(var)
The question isn't clear enough, so if this isn't what you wanted, edit the question.
Besides this, you can use Visual Code as an IDE, it'll make things much, much easier than Word.
About the errors, I think you might be trying to run the code directly in console. Instead of typing only the file name, type python file.py, assuming the file name is file. The file must be a python file (ending with .py), also it shouldn't be saved as a word file. It must be plain text.
If you want to run the same code on multiple variables, you can create the code as a string, and then use the builtin exec to execute it. Example:
a = 1
b = 2
c = 3
variables = ["a", "b", "c"]
for var in variables:
exec("print(" + var + ")") # print the variable before modifying
exec(var + " *= 2") # multiply the current variable by 2
exec("print(" + var + ")") # print the variable after modifying
If this is not what you need, your question was not clear enough and i misunderstood it, you just have to provide more information on what excatly you need by adding a comment under your question, in which you first type #Programmer and then your text.
Related
This function requests a string input and reverses it. For some reason, I just cannot wrap my head around the logic behind it.
def reverse(s):
new = ""
for i in s:
print(new)
new = i + new
return new
oldStr = input("String?")
newStr = reverse(oldStr)
print(newStr)
print(reverse("good bye"))
A friend suggested I print the variable new in the string which I added and it helped a little, but I just don't understand it.
It looks to me as if you are in a stage where you want to learn how to debug small programs.
For questions on StackOverflow, you want to provide a minimal reproducible example. What does that mean in your case?
"repoducible" means that you should not depend on user input. Replace user input by hardcoded values.
"minimal" means that you don't call the function twice. Once is enough.
For that reason, I'll not walk you through your original program, but through this one instead:
def reverse(s):
new = ""
for i in s:
print(new)
new = i + new
return new
print(reverse("abcdef"))
I'll use a free program called PyCharm Community Edition. You set a breakpoint where you want to understand how things work. Since you don't understand the reverse() method, put it right at the beginning of that method. You do that by clicking between the line number and the text:
Even if your code has no bug, go to the Run/Debug menu:
Execution will stop at the breakpoint and you'll now be able to see all the variables and step through your code line by line.
Look at all the variables after each single line. Compare the values to what you think the values should be. If there is a mismatch, it's likely a misunderstanding on your side, not by Python. Do that a few times and it'll be obvious why and how the string is reversed.
Let analysis it:
Iteration 1:
new = 'A', i = g
Perform new = i + new : new = gA
Iteration 2:
new = gA, i = o
Perform new = i + new: new = ogA
.
.
.
This happens because we add new i before we add the existing string from previous iteration.
the key is in "new = i + new" note that new is the previous iteration character and is in the right side of the current character, this cause the string to reverse
I have the following code (it changes the string/filepath, replacing the numbers at the end of the filename + the file extension, and replaces that with "#.exr")
I was doing it this way because the name can be typed in all kinds of ways, for example:
r_frame.003.exr (but also)
r_12_frame.03.exr
etc.
import pyseq
import re
#create render sequence list
selected_file = 'H:/test/r_frame1.exr'
without_extention = selected_file.replace(".exr", "")
my_regex_pattern = r"\d+\b"
sequence_name_with_replaced_number = re.sub(my_regex_pattern, "#.exr" ,without_extention)
mijn_sequences = fileseq.findSequencesOnDisk(sequence_name_with_replaced_number)
If I print the "sequence_name_with_replaced_number" value, this results in the console in:
'H:/test/r_frame#.exr'
When I use that variable inside that function like this:
mijn_sequences = fileseq.findSequencesOnDisk(sequence_name_with_replaced_number)
Then it does not work.
But when I manually replace that last line into:
mijn_sequences = fileseq.findSequencesOnDisk('H:/test/r_frame#.exr')
Then it works fine. (it's the seems like same value/string)
But this is not an viable option, the whole point of the code if to have the computer do this for thousands of frames.
Anybody any idea what might be the cause of this?
After this I will do simple for loop going trough al the files in that sequence. The reason I'm doing this workflow is to delete the numbers before the .exr file extensions and replace them with # signs. (but ognoring all the bumbers that are not at the end of the filename, hence that regex above. Again, the "sequence_name_with_replaced_number" variable seems ok in the console. It spits out: 'H:/test/r_frame#.exr' (that's what I need it to be)
I fixed it. the problem as stated was correct, every time I did a cut and past from the variable value in the console and treated it as manual input it worked.
Then I did a len() of both values, and there was a difference by 2! What happend? The console added the ''
But in the generated variable it had those baked in as extra letters. i fixed it by adding cleaned_sequence = sequence_name_with_replaced_number[1:-1] so 'H:/test/r_frame1.exr' (as the console showed me) was not the same as 'H:/test/r_frame1.exr' (what I inserted manually, because I added these marks, in the console there are showed automatically)
I currently have the below syntax -
BEGIN PROGRAM.
import spss,spssdata
varlist = [element[0] for element in spssdata.spssdata('CARD_2_Q2_1_a').fetchall()]
varstring = " ".join(str(int(i)) for i in varlist)
spss.submit("if (Q4_2 = 2 AND CARD_2_Q2_1_a = %(varstring)s) Q4_2_FULL = %(varstring)s." %locals())
END PROGRAM.
I thought this would just loop through the values in my variable CARD_2_Q2_1_a and populate Q4_2_FULL where appropriate. It worked in long hand without Python use, but the code above doesn't change the input file at all. Any reason why this might not be working or an alternative way of doing this?
varstring will be a string of integers joined by blanks. Therefore, your test condition in the IF will never be satisfied. Hence Q4_2_FULL will never be populated. You can print out the command you are submitting to see this.
I'm not sure exactly what your desired result is, but remember that the IF command you are submitting will execute over the entire dataset.
I'm fairly new to python, but I'm making a script and I want one of the functions to update a variable from another file. It works, but when I exit the script and reload it, the changes aren't there anymore. For example (this isn't my script):
#File: changeFile.txt
number = 0
#File: changerFile.py
def changeNumber():
number += 1
If I retrieve number during that session, it will return 1, but if I exit out and go back in again and retrieve number without calling changeNumber, it returns 0.
How can I get the script to actually save the number edited in changeNumber to changeFile.txt? As I said, I'm fairly new to python, but I've looked just about everywhere on the Internet and couldn't really find an answer that worked.
EDIT: Sorry, I forgot to include that in the actual script, there are other values.
So I want to change number and have it save without deleting the other 10 values stored in that file.
Assuming, as you show, that changeFile.txt has no other content whatever, then just change the function to:
def changeNumber():
global number # will not possibly work w/o this, the way you posted!
number += 1
with open('changeFile.txt', 'w') as f:
f.write('number = {}\n'.format(number))
ADDED: the OP edited the Q to mention (originally omitted!-) the crucial fact that changefile.txt has other lines that need to be preserved as well as the one that needs to be changed.
That, of course, changes everything -- but, Python can cope!-)
Just add import fileinput at the start of this module, and change the last two lines of the above snippet (starting with with) to:
for line in fileinput.input(['changefile.txt'], inplace=True):
if line.startswith('number ');
line = 'number = {}\n'.format(number)'
print line,
This is the Python 2 solution (the OP didn't bother to tell us if using Py2 or Py3, a crucial bit of info -- hey, who cares about making it easy rather than very hard for willing volunteers to help you, right?!-). If Python 3, change the last statement from print line, to
print(line, end='')
to get exactly the same desired effect.
I was not clear enough in my last question, and so I'll explain my question more this time.
I am creating 2 separate programs, where the first one will create a text file with 2 generated numbers, one on line 1 and the second on line 2.
Basically I saved it like this:
In this example I'm not generating numbers, just assigning them quickly.
a = 15
b = 16
saving = open('filename.txt', "w")
saving.write(a+"\n")
saving.write(b+"\n")
saving.close()
Then I opened it on the next one:
opening = open('filename.txt', "w")
a = opening.read()
opening.close()
print(a) #This will print the whole document, but I need each line to be differnet
Now I got the whole file loaded into 'a', but I need it split up, which is something that i have not got a clue on how to do. I don't believe creating a list will help, as I need each number (Variables a and b from program 1) to be different variables in program 2. The reason I need them as 2 separate variables is because I need to divide it by a different number. If I do need to do a list, please say. I tried finding an answer for about an hour in total, though I couldn't find anything.
The reason I can't post the whole program is because I haven't got access to it from here, and no, this is not cheating as we are free to research and ask questions outside the classroom, if someone wonders about that after looking at my previous question.
If you need more info please put it in a comment and I'll respond ASAP.
opening = open('filename.txt') # "w" is not necessary since you're opening it read-only
a = [b.split() for b in opening.readlines()] # create a list of each line and strip the newline "\n" character
print(a[0]) # print first line
print(a[1]) # print second line