Python integer incrementing with ++
Python doesn't support ++
, but you can do:
number += 1
Behaviour of increment and decrement operators in Python
++
is not an operator. It is two +
operators. The +
operator is the identity operator, which does nothing. (Clarification: the +
and -
unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical ++
operator to work on strings.)
++count
Parses as
+(+count)
Which translates to
count
You have to use the slightly longer +=
operator to do what you want to do:
count += 1
I suspect the ++
and --
operators were left out for consistency and simplicity. I don't know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:
- Simpler parsing. Technically, parsing
++count
is ambiguous, as it could be+
,+
,count
(two unary+
operators) just as easily as it could be++
,count
(one unary++
operator). It's not a significant syntactic ambiguity, but it does exist. - Simpler language.
++
is nothing more than a synonym for+= 1
. It was a shorthand invented because C compilers were stupid and didn't know how to optimizea += 1
into theinc
instruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable. - Confusing side-effects. One common newbie error in languages with
++
operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language "gotcha"-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.
Incrementing an integer by +1 and adding to string
You stated that you want to add them to a URL so the way to do it would be:
url = "thisisanamazingurl{0:0>4}" # insert your URL instead of thisisanamazingurl
for i in range(10000):
tempurl = url.format(i)
print(tempurl) # instead of print you should do whatever you need to do with it
This works because :0>4
fills the "input string" with leading zeros if it's shorter than 4 characters.
For example with range(10)
this prints:
thisisanamazingurl0000
thisisanamazingurl0001
thisisanamazingurl0002
thisisanamazingurl0003
thisisanamazingurl0004
thisisanamazingurl0005
thisisanamazingurl0006
thisisanamazingurl0007
thisisanamazingurl0008
thisisanamazingurl0009
or if you want to store them as a list:
lst = [url.format(i) for i in range(10000)]
increment integer in python
I don't know the specifics of your application, but I would send the data to a list, and then use Python's slice notation to select every 1000th data point.
Try the following snippet.
data = range(100)
every_tenth = data[::10]
Also, you can eliminate the need to explicitly close files if you use the with
keyword.
with open(filename) as f:
data = f.readlines()
The following is your code re-written more 'Pythonically'--that is, it takes advantage of some of the shortcuts that Python offers you over C. You may have to fiddle with it a little to get it to run. I am not sure how you are handling your files.
def CumulativePerSecond(filename, freq=1000):
data = []
with open(filename) as input_file:
data = input_file.readlines()
output_file = os.path.splitext(filename)[0] + "_1s.txt"
with open(out_filename, 'a+') as output:
for line in data[::freq]:
output.write(line)
Post increment value while passing to function call
def col(n):
sp = [n]
if n < 1:
return []
while n > 1:
if n % 2 == 0:
n = n * 2
else:
n = 3 // n - 1
sp.append(n)
print(n)
for i in sp:
print(i, end = ' ')
a = 1
while True:
col(a)
a+=1
This will work.
Incrementing integer using variable name string
Its never a good idea to eval or exec code, 99 times out of 100 there is a better way to do it. In this case unless you have any other reason that really needs to use eval and exec you could achieve what your trying with a dict. it can hold a key ("name") used to reference or look up your value quite safely.
class MyClass:
def __init__(self):
self.my_counts = {
'rhce': 0,
'rhcsa': 0
}
def add_cert_user(self, userid, args):
print("start of function", self.my_counts)
for cert in args:
if cert in self.my_counts:
self.my_counts[cert] += 1
print("end of function", self.my_counts)
me = MyClass()
args = ['rhce','rhcsa']
me.add_cert_user("test", args)
me.add_cert_user("test", args)
me.add_cert_user("test", args)
OUTPUT
start of function {'rhce': 0, 'rhcsa': 0}
end of function {'rhce': 1, 'rhcsa': 1}
start of function {'rhce': 1, 'rhcsa': 1}
end of function {'rhce': 2, 'rhcsa': 2}
start of function {'rhce': 2, 'rhcsa': 2}
end of function {'rhce': 3, 'rhcsa': 3}
Python - Increment last character in a String by 1
Below is the sample code that would work.
value = 'Run1'
value = value[:-1] + str(int(value[-1])+1)
print(value)
'Run2'
How to check if a list contains integers incrementing by one
In one line:
my_list == list(range(my_list[0], my_list[0] + len(my_list)))
But this probably isn't the most readable.
As a function
def is_incremental(my_l):
return my_l == list(range(my_l[0], my_l[0] + len(my_l)))
Related Topics
Xrange(2**100)' -> Overflowerror: Long Int Too Large to Convert to Int
How to Change the Host and Port That the Flask Command Uses
Iterating Through Two Lists in Django Templates
How to Get Dict from SQLite Query
Logging, Streamhandler and Standard Streams
How to Left Align a Fixed Width String
Python Map Object Is Not Subscriptable
Using a Python Subprocess Call to Invoke a Python Script
How to Create Collapsible Box in Pyqt
Using a Where _ in _ Statement
If Two Variables Point to the Same Object, Why Doesn't Reassigning One Variable Affect the Other
How to Trace the Path in a Breadth-First Search
How to Get Element-Wise Matrix Multiplication (Hadamard Product) in Numpy
Find Usa Phone Numbers in Python Script
Why Does Indexing Numpy Arrays with Brackets and Commas Differ in Behavior