add string to the end of a letter python - python

How can I do the following in python;
for i in range(4):
s_i = 3
so I get
s_0 = 3
s_1 = 3
s_2 = 3
s_3 = 3

Keep data out of your variable names. If you want numbered variables, you really need a list:
s = [3] * 4
Then you can access elements with indexing notation:
s[2] = 5
instead of trying to build variable names dynamically.
If you want more general dynamically-named variables, like variables whose names come from user input, you really need a dict:
parents = {}
for i in xrange(5):
child = raw_input('Enter child name:')
parent = raw_input('Enter parent name:')
parents[child] = parent

While the following works, it seems like a very, very bad idea:
>>> for j in range(4):
... globals()['s_{}'.format(j)] = 3
...
>>> s_0
3
>>> s_1
3
>>> s_2
3
>>> s_3
3
EDIT Replaced locals() with globals(). According to the docs for locals():
The contents of this dictionary should not be modified; changes may
not affect the values of local and free variables used by the
interpreter.

I didn't get your question exactly. But I have tried this:
for i in range(4):
exec('s_'+str(i) + '=i')
Out Put :
s_0 = 0
s_1 = 1
s_2 = 2
s_3 = 3
on the fly we are creating 4 variables and assigning values to it.

Related

How do i use the answer of one of my variables to store more information in another variable

This is my code
a = 0
b = 0
c = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t']
while a is not '':
b = b + 1
d = c[b]
row = input('Enter row')
I am trying to get it so that instead of the information being stored in the variable row, it is stored in the answer of the variable d.
So say if the variable b is 5, the variable d will get the sixth string in the list c, which is 'f'. I then want 'f' to be the variable name instead of 'row'

Extract key1:value1 from dictionary 1 and key1:value1 from dictionary 2, assign them to 4 different variables, loop

What I need to do:
for each key in dictionary1 extract key1:value1 from dictionary1 and key1:value1 from dictionary2
assign those 2 pairs to 4 different variables
use those variables in other methods
move on to the next iteration (extract key2:value2 of both dictionaries 1 and 2, and assign to the same 4 variables)
Example:
d_one = {1:z, 2:x, 3:y}
d_two = {9:o, 8:n, 7:m}
the result has to be
a = 1
b = z
c = 9
d = o
(calling some other methods using those variables here)
(moving on to the next iteration)
a = 2
b = x
c = 8
d = n
(and so on)
My brain is overloaded on this one. Since I can't nest for loops to accomplish this task, I guess the correct usage of 'and' statement should do it? I have no idea how so I try to split it up...
d_one = {'1':'z', '2':'x', '3':'y'}
d_two = {'9':'o', '8':'n', '7':'m'}
for i in range(0, len(d_one)):
for a in list(d_one.keys())[i]:
a = d_one.keys()[i]
b = d_one[a]
for c in list(d_two.keys())[i]:
c = d_two.keys()[i]
d = d_two[c]
print(a, b, c, d)
output:
TypeError: 'dict_keys' object is not subscriptable
Try this:
d_one = {'1':'z', '2':'x', '3':'y'}
d_two = {'9':'o', '8':'n', '7':'m'}
for (a,b), (c,d) in zip(d_one.items(), d_two.items()):
print(a, b, c, d)

choose variable via input (python)

i wanna choose the variable via an input
a=1
b=2
c=3
x=input("a/b/c")
The Idea is now that the calculation is 7 times 1 and therefore the solution: 7
solution=7*a
print(solution)
But python recognizes the input as string not as a variable. How do i change that?
You need to create a 'lookup table' that will map the chars to numbers.
lookup = {'a':1,'b':2,'c':3}
x=input("a/b/c: ")
value = lookup.get(x)
if value is None:
print('invalid input')
else:
print(f'Solution is {7 * value}')
You can turn a string into a variable like this.
a = 1
b = 2
c = 3
x = input("a/b/c: ")
x = locals()[x]
solution = 7 * x
print(solution)

Python Iterating over variables

I want to write a for loop that iterates over variables and updates their values.
for example:
x = 1
y = 1
for varNames in [x,y]:
varNames = varNames + 1
print(x)
print(y)
Here I want to have the function print the value 2 for both x and y, but my output is still 1. It is because the varNames variable gets updated but not x and y. How do I update the values for actual variable names x and y?
Thanks for the help!
At the global level (i.e. not within a function) you could do this using the globals() function.
x = 1
y = 1
for varName in ["x","y"]:
globals()[varName] += 1
print(x) # 2
print(y) # 2
However, if you need to do that kind of thing in your program, you might want to learn more about lists and dictionaries which would be the preferred approach.
data = dict()
data["x"] = 1
data["y"] = 1
for varName in data:
data[varName] = data[varName] + 1
print(data["x"]) # 2
print(data["y"]) # 2
You can just make a list containing the variables and then you can iterate over them and print each object of the list.
x = 1
y = 3
mylist=[x,y]
for index in mylist:
print(index)

How can I use string formatting to assign unique variable?

I've got a list and i've managed to turn the list into strings. Now I want to assign a variable to each item in the list by using string formatting to append a 1 onto the end of the variable.
listOne = ['33.325556', '59.8149016457', '51.1289412359']
itemsInListOne = int(len(listOne))
num = 4
varIncrement = 0
while itemsInListOne < num:
for i in listOne:
print a = ('%dfinalCoords{0}') % (varIncrement+1)
print (str(listOne).strip('[]'))
break
I get the following error: SyntaxError: invalid syntax
How can I fix this and assign a new variable in the format:
a0 = 33.325556
a1 = 59.8149016457 etc.
Your current code has a few issues:
listOne = ['33.325556', '59.8149016457', '51.1289412359']
itemsInListOne = int(len(listOne)) # len will always be an int
num = 4 # magic number - why 4?
varIncrement = 0
while itemsInListOne < num: # why test, given the break?
for i in listOne:
print a = ('%dfinalCoords{0}') % (varIncrement+1) # see below
print (str(listOne).strip('[]')) # prints list once for each item in list
break # why break on first iteration
One line in particular is giving you trouble:
print a = ('%dfinalCoords{0}') % (varIncrement+1)
This:
simultaneously tries to print and assign a = (hence the SyntaxError);
mixes two different types of string formatting ('%d' and '{0}'); and
never actually increments varIncrement, so you will always get '1finalCoords{0}' anyway.
I would suggest the following:
listOne = ['33.325556', '59.8149016457', '51.1289412359']
a = list(map(float, listOne)) # convert to actual floats
You can easily access or edit individual values by index, e.g.
# edit one value
a[0] = 33.34
# print all values
for coord in a:
print(coord)
# double every value
for index, coord in enumerate(a):
a[index] = coord * 2
Looking at your previous question, it seems that you probably want pairs of coordinates from two lists, which can also be done with a simple list of 2-tuples:
listOne = ['33.325556', '59.8149016457', '51.1289412359']
listTwo = ['2.5929778', '1.57945488999', '8.57262235411']
coord_pairs = zip(map(float, listOne), map(float, listTwo))
Which gives:
coord_pairs == [(33.325556, 2.5929778),
(59.8149016457, 1.57945488999),
(51.1289412359, 8.57262235411)]

Categories