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"]
Related
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(...)).
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.
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 3 years ago.
I am using python on a Raspberry Pi.
One of my function's argument will be a string containing an unknown amount of numbers.
I need to extract them all and put them in different variables.
I will then pass those variables as arguments to :
t.write(serial.to_byte([OtherVar1, OtherVar2, OtherVar3, EXTRACTEDVar1, EXTRACTEDVar2, EXTRACTEDVAR3, etc])
I have decided (but it can change upon recommendation) that the string will have the following format: NUMBER,NUMBER,NUMBER... each number is going to be separated by a ,.
Additionnal difficulty: Each number represents a 16 bit value that has to be put in 2 separate bytes. (So 8 would give me VAR1=0x00 and VAR2=0x08)
How can I extract them?
Is there a way to generate a undefined amount of variables in a loop?
For those familiar with MODBUS, I am trying to create the MODBUS function 16, Write Multiple Registers. And I don't know how to deal with the unknown amount of Data I have to send.
Thank you for your help
You can do this:
# number is your string of numbers
splitted = numbers.split(',')
result = [(num[:2],num[2:]) for num in splitted]
Note that result contains tuples of string, then you will need to convert them to a number depending on which base you will use.
This question already has answers here:
Python- Turning user input into a list
(3 answers)
Create a tuple from an input in Python
(5 answers)
Closed 10 months ago.
Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.
values = input("Input some comma separated numbers : ")
list = values.split(",")
tuple = tuple(list)
print('List : ',list)
print('Tuple : ',tuple)
This does work but is there any other easier way?
If you're looking for a more efficient way to do this, check out this question:
Most efficient way to split strings in Python
If you're looking for a clearer or more concise way, this is actually quite simple. I would avoid using "tuple" and "list" as variable names however, it is bad practice to name variables as their type.
Well, the code that you have written is pretty concise but you could remove few more line by using the below code:
values = input("Enter some numbers:\n").split(",")
print(values) #This is the list
print(tuple(values)) #This is the tuple
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.