I want show two variables in a prompt line in Python as this:
a = 35
b = 11
captcha = int(input(a, '+', b '='))
It must looks like:
35 + 11 =
The terminal say there is a SyntaxError. Can someone fix my syntax please? Thanks!
You've got two problems.
You miss the third comma to separate b and =.
Then input takes only one argument. If you try and concatenate strings in a function, python will think you are trying to add multiple arguments. Try using f-strings instead.
captcha = int(input(f'{a} + {b} ='))
Try an f string:
captcha = int(input(f'{a} + {b} = '))
Here's a simpler way to do what you are trying to do:
captcha = int(input(f"{a}+{b}="))
Related
x= 1
a_1_add = "message 1"
a_2_add = "message 2"
while x<3:
y = "a_" + x + "_add"
print(y)
x += 1
How do I get python to get make it print "message 1', "message 2" instead of "a_1_add"?
I want to specifically make the string in y to be recognised as a variable. How to I do that?
I want to have a code that automatically change from the variable "a_1_add" to "a_2_add" and so on but don't want to manually write it out since the difference is only the number in the middle.
Edit: I know of "for loop" (a thank you to those that suggested it) but for my code (not so simple as the example I wrote out) I really need to use the while loop.
Thanks in advance. I am a beginner in python. Really appreciate your help.
Since you're beginner, I would assume, you should look toward something like this instead:
a_1_add = "message 1"
a_2_add = "message 2"
container = [a_1_add, a_2_add]
for element in container:
print(element)
Note, you can still access the contents of both variables a_1_add and a_2_add, change them, add more variables to the container and so on.
Maybe you can use the for loop to loop through all the variables.
var1 = “message 1”
var2 = “message 2”
var3 = “message 3”
for i in [var1, var2, var3]:
print(i)
Edit:
Yes, as #juanpa.arrivillage suggested , string list dictionary etc. are all data types (built in) in Python. Variables are user-defined, just a name representing the value assigned to it.
I think I get what you mean: like create variables using whilè loop? If so, I m afraid that it is not possible. Maybe you can use an array to contain those all values instead ? and access them using index or slicing.
x = 1
all_val = [] # this is a list here
while x < 3:
all_val.append(f"a_{x}_add")
x += 1
print(all_val[0])
print(all_val[1])
print(all_val[1:])
Hope it can answer you question.
How to print variable name by input, Example:
a = 1
b = 2
what_variable = input('Which Variable?: ') #User for example introduces 'b'
Console: 2
You can write
print(globals()[what_variable])
but it's not a good approach. Use a dict instead
You can use exec:
var = input('Which Variable?: ')
exec("print(" + var + ")")
Output:
Which Variable?: b
2
>>
Just do the following:
print(eval(input('Which Variable?: ')))
You can also do
print(globals()[input('Which Variable?: ')])
While the other answers seem to address the obvious solution, it's not very 'Pythonic'. The main issues with these is, by far, safety. Let's say that your user inputs apiKey, and you happen to have a variable by that name... let's just say your bank statement is probably looking at a slight increase in magnitude. What most people in these answers don't realise is that using .globals()[input()] is no safer than eval(input()), because, shockingly, people store private info in variables. Alternatively, if it points to a method, e.g
a = print
b = os.system
eval(input())()
I could enter any function name there, and the damage would be done before the second () executes.
Why? Well, let's take a look at how exec and eval work (I won't go into the difference here, see this question for that). All they do is evaluate the string as Python code, and (simplifying here) return the value of the evaluation:
var1 = 3
print(eval("var1"))
# ====is equal to====
var1 = 3
print(var1)
(where var1 as a string obviously comes from the input typed in)
But if someone enters something malicious, this is essentially the basis of an SQL injection:
(where userInput is substituted by a user's input into an input())
userInput = "a + os.system('reboot now')"
print(eval(userInput))
# ====is equal to====
print(a + os.system('shutdown now')
and you suddenly find your computer's off.
Therefore, we'd either use a:
Dictionary (or object): x={a:1, b:2}, then do x[input()]
Array x=[1, 2], then do x[["a", "b"].index(input())]
Simply don't. Find a way to work around it. What's wrong with an if/else set? It's not good practise, because of the safety concerns outlined above. What most people seem to miss about dictionaries (or my array option) is that if you enter a malformed input (i.e not a or b), it would result in either uncaught errors being thrown, or undefineds being thrown around. And if you're going to do input validation, you're using an if statement anyway, so why not do it from the onset?
I found this question on HackerRank and I am unable to understand the code(solution) that is displayed in the discussions page.
The question is:
Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer at position .
print: Print the list.
remove e: Delete the first occurrence of integer .
append e: Insert integer at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Even though I have solved the problem using if-else, I do not understand how this code works:
n = input()
slist = []
for _ in range(n):
s = input().split()
cmd = s[0]
args = s[1:]
if cmd !="print":
cmd += "("+ ",".join(args) +")"
eval("slist."+cmd)
else:
print slist
Well, the code takes advantage of Python's eval function. Many languages have this feature: eval, short for "evaluate", takes a piece of text and executes it as if it were part of the program instead of just a piece of data fed to the program. This line:
s = input().split()
reads a line of input from the user and splits it into words based on whitespace, so if you type "insert 1 2", s is set to the list ["insert","1","2"]. That is then transformed by the following lines into "insert(1,2)", which is then appended to "slist." and passed to eval, resulting in the method call slist.insert(1,2) being executed. So basically, this code is taking advantage of the fact that Python already has methods to perform the required functions, that even happen to have the same names used in the problem. All it has to do is take the name and arguments from an input line and transform them into Python syntax. (The print option is special-cased since there is no method slist.print(); for that case it uses the global command: print slist.)
In real-world code, you should almost never use eval; it is a very dangerous feature, since it allows users of your application to potentially cause it to run any code they want. It's certainly one of the easier features for hackers to use to break into things.
It's dirty code that's abusing eval.
Basically, when you enter, for example, "remove 1", it creates some code that looks like sList.remove(1), then gives the created code to eval. This has Python interpret it.
This is probably the worst way you could solve this outside of coding competitions though. The use of eval is entirely unnecessary here.
Actually I Find some error in the code, but I came to an understanding of how this code runs. here is it:
input :
3
1 2 3
cmd = 1 + ( 2 + 3)
then eval(cmd) i.e., eval("1 + (2 + 3)") which gives an output 6
another input:
4
4 5 6 2
cmd = 4 + ( 5 + 6 + 2)
eval(cmd)
if __name__ == '__main__':
N = int(raw_input())
lst=[]
for _ in range(N):
cmd, *line = input().split()
ele= list(map(str,line))
if cmd in dir(lst):
exec('lst.'+cmd+'('+','.join(ele)+')')
elif cmd == 'print':
print(lst)
else:
print('wrong command', cmd)
I have a string in the form of ( + m1 + "|" + m2 + ) and ( + m1 + "." + m2 + )
where m1 an m2 are strings made up of "6", "7", "8", "a".
These are some of the valid expressions:
"(6|7)"
"((8.7)|(6.7).(a.2))"
Now my question is, if I want to split at the "." basically that works a a divisor, how would I do that?
What I did was tried finding a middle point but the thing is it's not always in the middle.
I also tried doing s.rindex(".") and s.index(".") and s.find(".") but they also don't seem to work.
I was thinking of calling the outer most brackets and then work it's way inside
but I don't think that's gonna work.
I am thinking there is some relation perhaps with the brackets but I just can't seem to figure out what it is.
Any suggestion on how do I approach this problem? or hint about how i can find that splitting point?
Any help will be appreciated.
Thanks in advance
This is my interpretation of what you're asking. Without more information, an explicitly stated problem, expected output, or code showing your own attempts, I can't do much more.
test1 = "(6|7)"
test2 = "((8.7)|(6.7).(a.2))"
# Not really sure what your output is suppose to look
# Like so this is my interpretation
test1_split = test1.replace("(", "").replace(")", "").split("|")
print test1_split # output --> ['6', '7']
# creates a list containing the string 6 and 7
# You said the . works an a divisor. If you mean a delimiter then you can use the split("."") method
# If you mean that it is a symbol for a divide sign then see below
test2 = test2.replace(".", "/") # convert periods into dividing sign
test2_split = test2.split("|") # seperates (8/7) (6/7)/(a/2))
print test2_split # output ['((8/7)', '(6/7)/(a/2))']
# now if this is an equation I would continue...Since I don't know the output
# I leave the rest to you
Ok guys, I am using python to try to complete a task. In short, I need to read in a number from a text file that can be thousands of digits long. I'm getting this error as I try to take the digits from the string and cast them to integers so I can do some math with them.
of = open("input.txt","r")
counter = 0
big=0
of.seek(0,0)
while True:
temp = of.read(5)
if temp=="":
break
else:
a=int(temp[0])
b=int(temp[1])
c=int(temp[2])
d=int(temp[3])
e=int(temp[4])
if a*b*c*d*e>big:
big = a*b*c*d*e
counter+=1
of.seek(counter,0)
print big
of.close()
I'm really stuck on this one so any help much appreciated.
Thanks in advance.
EDIT==============================================================
After tinkering around a bit I finally got the code to run correctly. Here's what I ended with:
x = int(open("input.txt","r").read())
y = str(x)
big = 0
for i in range(0,len(y)-5):
a = int(y[i])
b = int(y[i+1])
c = int(y[i+2])
d = int(y[i+3])
e = int(y[i+4])
if a*b*c*d*e>big:
big = a*b*c*d*e
print big
thanks for the help
Python supports long integers so if the file is just one big integer you can read it like this:
bignum=int(open("input.txt","r").read())
Your indentation is wrong; if-else should be nested inside the while loop.