Changing variables after checking them with 'if' python [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
Hi I am quite new to python and I am getting an error when I try to change a variable after checking it with 'if'. (note I only just started python I mostly only do lua)
so this is an example that didn't work for me
var = 5
if var == 5:
var = var + 1
return
This is works in lua for me so I am confused.
In lua its
var = 5
if var == 5 then
var = var + 1
end
can someone help me with this?

#In this example, return is not needed
var = 5
if var == 5:
var = var + 1
print(var)
#use return when using a function as per the example below
def my_var():
var = 5
if var == 5:
var = var + 1
return var
res = my_var()
print(res)

You don't need return here. Why is it there? It's not a function. You don't have to retun anything. The variable though is being updated.
var = 5
if var == 5:
var = var + 1
print(var)

Welcome to SO, I think you should be posting your question along with the error that you are getting, which will give more context.
I can see you have used return, are you using this inside a function, i dont think it is needed otherwise?

Related

Confused about how the return works in python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
The program runs and the function works but I am not able to see my docCountryList in the output. Can someone tell me why?
I have this code
def ViewByCountry(docID,user_selection):
docCountryList=[]
for x in jfile:
if x.get('subject_doc_id') == docID:
docCountryList.append(x['visitor_country'])
if user_selection == '2a':
x = []
y = []
#Insert countries and number of occurences in two seperate lists
for k,v in Counter(docCountryList).items():
x.append(k)
y.append(v)
plt.title('Countries of Viewers')
plt.bar(range(len(y)), y, align='center')
plt.xticks(range(len(y)), x, size='small')
plt.show()
return docCountryList
and in my main
from program import ViewByCountry
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
docID = input("Enter required document ID: ")
user_selection = input("Enter selection")
ViewByCountry(docID,user_selection)
You never print out the value of docCountryList, so try this:
print(ViewByCountry(docID,user_selection))
This will print out the value.
You can do this as well:
lst = ViewByCountry(docID,user_selection)
print(lst)
In your main you can change to myView = ViewByCountry(docID,user_selection) and then add print(myView). This saves the list created by your function to a variable to be printed or used later.

Why does my while loop not stop? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
RANDOM_COR=random.randrange(5,6)
def check_xy_data():
global COUNT
COUNT=0
input_xy=input("input(x,y) : ")
think_xy=list(map(int,input_xy.split(",")))
if(random_array[think_xy[0]][think_xy[1]] == "C"):
screen_array[think_xy[0]][think_xy[1]] = "O"
COUNT=COUNT+1
else:
screen_array[think_xy[0]][think_xy[1]] = "X"
def main():
make_intro()
init_screen_array ()
init_random_array ()
make_random_num(RANDOM_COR)
while(True):
check_xy_data()
draw_outline_start(TOTAL_COL_NUM//2)
draw_out_rowline(TOTAL_COL_NUM//2, "Input : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Correct : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Error : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Total : ")
draw_outline_mid(TOTAL_COL_NUM//2)
if(COUNT==RANDOM_COR-1):
break
The if at the bottom of my code is supposed to get me out of the while loop, but I'm stuck in an infinite loop. Help?
(assignment, 2016) 예고편 The Assignment | 어싸인먼트 감독: 월터 힐 각본: 월터 힐, 데니스 해밀 출연: 김성훈 출연 현빈, 유해진, 김주혁 개봉 2016 한국 상세보기 그간...
Try this change:
RANDOM_COR=random.randrange(5,6)
COUNT = 0
def check_xy_data():
global COUNT
With COUNT inside check_xy_data, you set it back to 0 on every call. It can never reach more than 1. Your check is whether it's in the range 5-6. This is never true, so you can never leave the loop.
Note that trivial debugging skills would have found this: just stick a print statement before you test your loop condition, to see what the values are. Use that next time ... :-)

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'

Unresolved Reference - Python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a function that takes a string input. I want to count no of times a string occurs in the input.
Example, I have a string cars = "Toyota, Honda, Toyota, BMW, Toyota"
I want a function that returns no of times a string occur
toyota_count = 0
honda_count = 0
BMW_count = 0
def count_cars(cars):
if "toyota" in cars:
toyota_count += 1
if "honda" in cars:
honda_count += 1
But this gives me error on toyota_count in the function, it says "Unresolved reference toyota_count"
Its because toyota_count is global.
Either define the variable inside your method (preferred) or specify it inside your methot as global like so:
def myfunc():
gobal toyota_count
EDIT
You can also just use cars.count("Toyota") to get the total number of substrings in a string.
Assuming your strings don't overlap, just use the string count() method. Whilst this isn't uber-efficient (three calls to count() and therefore 3 searches) it fits your described use case.
cars = "Toyota, Honda, Toyota, BMW, Toyota"
toyota_count = cars.count("Toyota")
honda_count = cars.count("Honda")
toyota_count = 0
honda_count = 0
BMW_count = 0
def count_cars(cars):
global toyota_count
toyota_count = cars.count('Toyota')
count_cars("Toyota, Honda, Toyota, BMW, Toyota")
print (toyota_count)

Python - SyntaxError: can't assign to literal [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to read from a file the variables (they are links) and then open them with urlopen in a while loop so that every link is opened.
My code is:
# Variables
from config import *
# Imports
import urllib
i = 0
url = 100
while i < 25:
page = urllib.urlopen( url );
page.close();
i = i + 1
url = 100
url = url + i
The error i get is SyntaxError: can't assign to literal. I kind of understand why, but i don't know how to bypass it!
config.py
100 = 'https:link'
101 = 'https:link'
102 = 'https:link'
The error is telling you exactly what the error is. You can't assign to a literal. 100 is a literal because it literally has the value 100. Your config.py is trying to change the value of the integer 100.
If you're trying to iterate over a list of variables or values starting with 100, one solution would be to create a dictionary and use the numbers for the keys. For example:
# config.py
urls = {
100: "https:link",
101: "https:link",
102: "https:link"
}
Then, in your code you can do something like this:
i = 0
while i < 25:
url_number = 100 + i
page = urllib.urlopen( urls[url_number] );

Categories