Usage of colon and equals signs in Python [duplicate] - python

This question already has answers here:
What are variable annotations?
(2 answers)
Closed 2 years ago.
class PrepareTableOperator(BaseOperator):
def _load_table(self):
drop_table_query: str = ( "drop table if exists " + self.get_table() )
I'm a complete newbie to python but I do have a bit of a Java background.
What I don't get is the usage of colons in python. I've googled around, and it's used for slicing and for starting function definitions. But there's no 'def' syntax in the above, so to me this doesn't look like a function.
My question is, what is the colon in Python, is it another assignment operator for dictionary values, similar to a key value pair? Is that what it's doing here? What is it doing here, essentially?

In your code snippet, it is a type annotation. It is a relatively new feature of Python that lets you keep track of the data types, so in this case, it is declaring that drop_table_query is a string.
Type annotations are checked by IDE, but not enforced by the Python interpreter. This means that drop_table_query could actually be an int and Python itself won't complain. The type annotation is just a sort of recommendation.

What it is doing here is defining that the variable will be a string (str data type). The colon is used in while loops, for loops, if statements, and functions. The colon helps the code flow into the following indented block. A single equal sign is used to assign a value to a variable, a double equal sign is used for conditions, like if var == other_var:. There is also +=, -=, *=, and /=. Those are used to shorten things like, var = var + 1, to var += 1.

Related

Naming a list with a number [duplicate]

This question already has answers here:
Can variable names in Python start with an integer?
(2 answers)
Closed 1 year ago.
Can you name a list with the first character being a number? I get an error when I try to do this. I am taking names of products and making lists and dictionaries with them and some of the names of the products start with a number.
like:
11T25M = ["Grade", "Tensile", "Elongation"]
I get
11T25M = ["Grade", "Tensile", "Elongation"]
^
Syntax Error: invalid decimal literal
No, you're not allowed to start a variable name with a number, regardless of the type of the variable (i.e. not just lists), the parser disallows it. This is fairly common amongst a lot of languages.
2e1 is a valid number in python (20), imagine if you wrote my_var = 2e1, is 2e1 a variable or a number? How is the parser to know?
Technically you could force a variable starting with a number for the name to exist through globals() but other than being terrible practice, it would be such a faff it's not worth the time or extra writing it would require.
No you cannot start a variable name with a number. One solution is instead of having a bunch of variables, you can contain them all in a dictionary.
my_dict = {}
my_dict["11T25M"] = ["Grade", "Tensile", "Elongation"]
print(my_dict["11T25M"])
Now instead of having a list called 11T25M, you have a list called my_dict["11T25M"]

how to decide type of a variable in python? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
enter image description here
I wrote a simple code in python.
Originally my assignment is to receive two inputs(name of person) and print them.
Here's my question.
When I try to sum two variables but one of them is int and another one is str, an error occurs.
But in this case (the picture) why variable 'a' is recognized as a str not int?
I think there must occurs an error but a is recognized as a str and work well.
In Python 3, input() always returns a string. (In Python 2, input() would try to interpret – well, evaluate, actually – things, which was not a good idea in hindsight. That's why it was changed.)
If you want to (try to) make it an int, you'll need int(input(...)).

Convert string to variable in python? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 5 years ago.
I am very new with python and programming altogether and have been trying to figure out how to do this for a while.
Here's what I need help with:
y=0
x=2
p01='hello'
p02='bye'
print('p'+(str(y)+str(x)))
The output is of course 'p02', but how can I make the output instead the value of p02 ('bye')
Hope this makes sense and I look forward to any answers.
You could use eval()...
It evaluates an expression stored in a string as if it were Python code.
In your case, 'p'+(str(y)+str(x)) becomes 'p01', so it gets the result of the expression p01, which is of course 'bye'.
print(eval('p'+(str(y)+str(x))))
Note however that you should never do this - there is almost always a better way. Please read Why is using 'eval' a bad practice?
So, what can we do?
globals() gives us a dictionary of all of the global variables in your Python program, with their name as a string index and their value as the dictionary value. Thus, we can simply do:
globals()['p'+(str(y)+str(x))]
Which evaluates to globals()['p01'], which gets the value of global p01 - which is bye.
Again, this is a workaround to a bigger problem
Restructure your code. Make them into an array or dictionary and get the index of it. Think through why you would want to do this, and change your code so that you do not have to. It is bad to be in a situation where eval looks like the best option.

Replace string value in regular expression with integer value in python [duplicate]

This question already has answers here:
Safety of Python 'eval' For List Deserialization
(5 answers)
Closed 8 years ago.
In my python code, a user enters a mathematical expression. I want to replace the variables with integer values and calculate the result. I can user regular expression in python to replace the variables with integer values but I cant calculate the sum as the replaced string I get is of type string. I can do it in tcl. It has a built in expr command where I simply pass the string and it automatically converts it to mathematical expression and calculates the result. Is there a way to do the same in python?
Thank you
Yes there is eval.
for example:
a=3
b=4
s="(a*a+b*b)**.5"
eval(s)
But be warned it maybe an security risk.
You may better use SymPy
http://sympy.org/en/index.html

trying to advance from java to Python with no luck [duplicate]

This question already has answers here:
Iterating each character in a string using Python
(9 answers)
Closed 9 years ago.
so i want to write this simple java code in python, but i cant, i want to print all the Strings letters form the first index to the last, so if my string is "josh", i want to print:
j
o
s
h
or like this java code:
String name = josh;
for(int i = 0; i < josh.length(); i++){
print(josh.CharAt(i));
}
i cant find any method that is like charAt, i'm guessing that it doesn't exists
but there has to some other way to do it, i know its kinda dumb question, but i couldn't
find anything online or here(on this website) to help me, so any ideas?
Try this:
name = "josh"
for i in name:
print i
# print(i) # python 3
name is the variable to which we assign string literal "josh". name is a str (or unicode in Python 3)
we iterate over name since strings are iterable (have __iter__() methods) with the loop iteration syntax. Each consecutive character is assigned to loop variable i per iteration over name's length.
Note that we cannot assign to name[i], only read from it since strings are immutable in python.

Categories