Why doesn't it keep incrementing every time I run the block? - python

I'm an absolute beginner, and I don't understand why a is not incremented every time I run the code. It always prints a = 0 and a = 1.
a = 0
b = 2
print ("a = {}".format(a))
a = a + 1
print ("a = {}".format(a))
Output
I'm working on Google Colab. Thanks in advance!
EDIT: I just noticed if I keep the two first lines on a separate block like this, the code does increment. Why??

Use two separate cells, one for declaring the variables and one for incrementing:

Related

Code worked in coursera sandbox editor but fails in python 3

I am super new to Python. I've been taking a Python Course on Coursera and fooling around with a little bit of code. Prior to today I was doing the class on a chromebook, and therefore using the sandbox tool provided. I've purchased an actual PC to download python since. I wrote a little code that was working just fine in the sandbox tool, but when I enter it into python it keeps booting me out. Can anyone spot anything obviously wrong with my code that I should change?
It should take an input of a date, exercise, and then keep looping through asking you about your sets and reps, saving results as tuples in a dictionary, until you enter 0, where it exits the loop, and prints the results. Stumped!
dt = input("Date:")
ex = input("Exercise:")
d = dict()
set = 0
while True:
wrk = input("Insert as Reps x Weight: ")
if wrk == "0":
break
set = set + 1
d[set] = wrk
print(dt)
print(ex)
print(d)
Indentation is really important in Python since it uses whitespace to differentiate between blocks of code.
Here,
observe the indentation of the while statement. Note that the indentation in the if block remains the same. This is because we want break to execute only if wrk is 0.
On the other hand, we keep set+1 outside because the condition did not match and we wanted our program to keep running.
python
dt = input("Date:")
ex = input("Exercise:")
d = dict()
set = 0
while True:
wrk = input("Insert as Reps x Weight: ")
if wrk == "0":
break
set = set + 1
d[set] = wrk
print(dt)
print(ex)
print(d)
This works as expected.

How do i increase the value of an variable in a command line?

a = 1
for i in range(5):
browser.find_element_by_xpath("/html/body/div[6]/div/div/div[2]/div/div/div[1]/div[3]/button").click()
sleep(1)
I want to increase the 1 in div[1] by 1+ every loop, but how can i do that?
i thought i need to add a value, do "+a+" and last of all a "a = a + 1" to increase the value every time, but it didnt worked.
a = 1
for i in range(5):
browser.find_element_by_xpath("/html/body/div[6]/div/div/div[2]/div/div/div["+a+"]/div[3]/button").click()
a = a + 1
sleep(1)
for i in range(1,6):
browser.find_element_by_xpath("/html/body/div[6]/div/div/div[2]/div/div/div["+str(i)+"]/div[3]/button").click()
sleep(1)
you don't need 2 variables, just one variable i in the loop, convert it to string with str() and add it to where you need it, pretty simple. the value of i increases for every iteration of the loop going from 1 to 5 doing exactly what you need.
alternatively to Elyes' answer, you can use the 'global' keyword at the top of your function then a should increment 'correctly'.
You don't really need two variables for this unless you are going to use the second variable for something. However, look at the following code and it will show you that both i and a will give you the same result:
from time import sleep
a = 1
for i in range(1, 6):
path = "/html/body/div[6]/div/div/div[2]/div/div/div[{idx}]/div[3]/button".format(idx=i)
print(path, 'using i')
path = "/html/body/div[6]/div/div/div[2]/div/div/div[{idx}]/div[3]/button".format(idx=a)
a += 1
print(path, 'using a')
sleep(1)
Result:
/html/body/div[6]/div/div/div[2]/div/div/div[1]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[1]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[2]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[2]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[3]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[3]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[4]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[4]/div[3]/button using a
/html/body/div[6]/div/div/div[2]/div/div/div[5]/div[3]/button using i
/html/body/div[6]/div/div/div[2]/div/div/div[5]/div[3]/button using a
You can read up on range here

IndexError: list index out of range even though printing individual lists and index doesn't seem to have an error

take = randint(0, len(teacherClass[teacher])-1)
print(take)
print(teacherClass)
print(teacher)
print(teacherClass[teacher])
triesDone = 0
while triesDone < len(teacherClass[teacher]):
cp = teacherClass[teacher][take]
if (cp not in (blocks[teacher][day])) and (blocksS[cp][day][block] == ""):
blocks[teacher][day][block] = cp
blocksS[cp][day][block] = teacherSub[teacher]
take +=1
triesDone += 1
if take == len(teacherClass[teacher])-1:
take = 0
When I run the program after some time, the above part is hit and the program starts working as intended but line 8 raises the error ("IndexError: list index out of range").
Trying to solve that and understand the problem, I tried to print the entire dictionary(teacherClass) and the indices used(teacher and take) but even after that, it seems the line 8 should work.
Output I am getting:
Output with list and index
Please help me understand the problem and a solution. Thanks
There is a possibility that take could be: len(teacherClass[teacher])-1 from the assignment on the first line. Later there is take += 1. This mean that it is larger than the limit, so take = 0 is never executed.
Did you mean:
if take >= len(teacherClass[teacher])-1:
take = 0

Conditionally increase integer count with an if statement in python

I'm trying to increase the count of an integer given that an if statement returns true. However, when this program is ran it always prints 0.I want n to increase to 1 the first time the program is ran. To 2 the second time and so on.
I know functions, classes and modules you can use the global command, to go outside it, but this doesn't work with an if statement.
n = 0
print(n)
if True:
n += 1
Based on the comments of the previous answer, do you want something like this:
n = 0
while True:
if True: #Replace True with any other condition you like.
print(n)
n+=1
EDIT:
Based on the comments by OP on this answer, what he wants is for the data to persist or in more precise words the variable n to persist (Or keep it's new modified value) between multiple runs times.
So the code for that goes as(Assuming Python3.x):
try:
file = open('count.txt','r')
n = int(file.read())
file.close()
except IOError:
file = open('count.txt','w')
file.write('1')
file.close()
n = 1
print(n)
n += 1
with open('count.txt','w') as file:
file.write(str(n))
print("Now the variable n persists and is incremented every time.")
#Do what you want to do further, the value of n will increase every time you run the program
NOTE:
There are many methods of object serialization and the above example is one of the simplest, you can use dedicated object serialization modules like pickle and many others.
If you want it to work with if statement only. I think you need to put in a function and make to call itself which we would call it recursion.
def increment():
n=0
if True:
n+=1
print(n)
increment()
increment()
Note: in this solution, it would run infinitely.
Also you can use while loop or for loop as well.
When you rerun a program, all data stored in memory is reset. You need to save the variable somewhere outside of the program, on disk.
for an example see How to increment variable every time script is run in Python?
ps. Nowadays you can simply do += with a bool:
a = 1
b = True
a += b # a will be 2

Asterisk coming up in Jupyter Notebook with a specific code

I am using Jupyter Notebook, I keep getting the asterisk that indicates the kernel is busy when I run this specific code:
var = 2
var += 1
var_rem = var % 3
while var_rem == 0:
var += 2
print var
In order to give some context, I am trying to solve the following exercise:
Define a new number variable and choose a value for it. If the
variable + 1 can be divided by three, increase the variable by two.
Test by printing the final value of the variable and varying the
initial value of that same variable.
I have tried restarting the kernel as it was recommended in front of the asterisk issue but it doesn't work. What is specific about this code that the kernel cannot process it? How do I then solve the exercise?
Note: First post around here, I hope it's relevant.
Your code results in an infinite loop. Your variable var_rem does not change its value in the loop, therefore it runs forever (because it remains 0)
You have to recalculate the while condition within the loop.
Based on the statement your logic is wrong. Try this...
var = 2
if ((var + 1) % 3) == 0:
var +=2
print var
else:
print 'Not divisible by 3'

Categories