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] );
Related
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?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm trying to make a program that gets a country name, goes to restcountries.com, gets the country's current population number, does the same thing another time, and tells if the population got bigger/smaller/same. I am a beginner at python and coding, so existing answers to similar questions were not so useful to me since they seem different than my problem. I have managed to make the code get the JSON from the site, keep it, and tell me the population number and it worked (I tested it with "Israel". But when I gave it to my pal, he wrote "Russia" and it failed. After a short investigation, I discovered restcountries.com calls Russia by the name "Russian Federation" and has a separate JSON dictionary key for common names called "common:". But I can't get to it and extract it by code. Here is the JSON from this URL: https://restcountries.com/v3/name/russia?fields=name,population
[{"name":{"common":"Russia","official":"Russian Federation","nativeName":{"rus":{"official":"Российская Федерация","common":"Россия"}}},"population":144104080}]
Here is my current code:
import bs4
import urllib.request
import json
country_name = input("Choose country: ")
# Getting updated list and saving it as "json_data"
link = 'https://restcountries.com/v3/name/' + country_name + '?fields=name,population'
webpage = str(urllib.request.urlopen(link).read())
soup = bs4.BeautifulSoup(webpage, "html.parser")
json_data = soup.get_text()
# Cleans json_data from all the bullshit
clean_json = json_data[:-1][2:].replace('\\', '.') \
.replace('.xc3.x85', 'A').replace('.xc3.xa7', 'c').replace('.xc3.xa9', 'e')
# Convert clean_json to a dictionary
loaded_json = json.loads(clean_json)
# Country search function
def search(name):
for p in loaded_json:
if p['name'] == name:
return p['population']
# Choose Country, save data.
country_population = search(country_name)
datafile = open('G:\HackerU\Python\Challenges\Population\dataname.txt','w')
def save(done):
datafile = open('G:\HackerU\Python\Challenges\Population\dataname.txt','w')
datafile.write(country_population)
datafile.close()
return True
saved_population_number = datafile.read()
if saved_population_number > country_population:
print("Population number has been decreased.")
elif saved_population_number < country_population:
print("Population number has risen.")
elif saved_population_number == country_population:
print("Population number stayed the same.")
else:
print("Unknown Error.")
How do I make my code recognize a country only by its "common" name?
It seems that there is a lot of unnecessary code here:
First of all, an API returns a JSON, therefore I don't see why you need to use bs4. You can load the JSON into a dict using json.loads.
Secondly, you don't want a string representation of the bytes object - but to decode the bytes. Therefore you can use urllib.request.urlopen(req).read().decode().
Therefore I would do something like this:
import json
import urllib.request
country_name = input("Choose country: ")
req = 'https://restcountries.com/v3/name/' + country_name + '?fields=name,population'
response = json.loads(urllib.request.urlopen(req).read().decode())[0]
Now you have the JSON response in a dictionary, and accessing response['population] gets you the country's population.
In addition, I would recommend learning about context managers and using them. For example, I would change the save function to (also, why does it return True?):
def save(country_population):
with open('G:\HackerU\Python\Challenges\Population\dataname.txt','w') as datafile:
datafile.write(country_population)
Good luck in the course, Python is a great language to start coding with.
Your issue has to do with how the json data is formatted. Replace if p['name'] == name: by if p['name']['common'] == name:
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
I'd like to split each line of a text file into two by " - ", but I keep getting this error:
File "quiz.py", line 21, in Vocab
questions, answers = line.split("-")
ValueError: too many values to unpack (expected 2)
I'm quite new to coding and could use some help. All tips are welcome as well!
import hashlib
testFile = ""
def qSearch():
options = input ("Vocab/Grammar/or Special? (v/g/s)")
if options == "v":
testFile = "Vocabtest"
Vocab()
elif options == "g":
Grammar()
testFile = "Grammartest"
elif options == "s":
Special()
testFile = "Specialtest"
else:
qSearch()
def Vocab():
with open('Vocabtest.txt','r') as f:
for line in f:
questions, answers = line.split("-") ### error
print (questions)
qSearch()
The text in my text file is formatted like so:
Magandang umaga - Good Morning
Magandang hapon - Good Afternoon
Magandang gabi - Good evening
Magandang umaga sa’yo - Good Morning to you
Magandang hapon din sa’yo - Good Afternoon to you to
"Unpacking" is the name for what you're doing when you write
value1, value2 = a_list
When you do an assignment like that, you're implicitly making an assumption about how many values are contained in a_list -- here it's 2. If there's more or less than 2, there's no good way to give value1 and value2 values without doing very surprising and unhelpful things (like leaving one empty, or leaving some elements of the list unassigned).
So too many values to unpack means that there's at least one line in your file where line.split('-') results in more than 2 elements -- that is, there's at least one line with more than one -.
The problem is because on line 21 in your input text (.txt) file you have more than one - but you only expect one.
A safer way to do it would be to only split once:
questions, answers = line.split("-", 1)
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)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am getting an invalid syntax error
SyntaxError: invalid syntax
root#collabnet:/home/projects/twitterBot# python twitterBot2.py
File "twitterBot2.py", line 58
return screenNames
when returning a dictionary from this function:
def getUserName(lookupIds):
l = len(lookupIds) # length of list to process
i = 0 #setting up increment for while loop
screenNames = {}#output dictionary
count = 0 #count of total numbers processed
print 'fetching usernames'
while i < l:
toGet = []
toAppend = []
if l - count > 100:#blocks off in chunks of 100
for m in range (0,100):
toGet.append(lookupIds[count])
count = count + 1
print toGet
else:#handles the remainder
print 'last run'
r = l - count
print screenNames
for k in range (0,r):#takes the remainder of the numbers
toGet.append(lookupIds[count])
count = count + 1
i = l # kills loop
toAppend = api.lookup_users(user_ids=toGet)
print toAppend
screenNames.append(zip(toGet, toAppend)
#creates a dictionary screenNames{user_Ids, screen_Names}
#This logic structure breaks up the list of numbers in chunks of 100 or their
#Remainder and addes them into a dictionary with their count number as the
#index value
#print str(len(toGet)), 'screen names correlated'
return screenNames
I am running the function like so:
toPrint = {}#Testing Only
print "users following", userid
toPrint = getUserName(followingids)#Testing Only
I have tried commenting out and just printing screenNamesand I still get the same error except on the print statement instead. I am pretty sure I am running the return right thanks for the look.
You forgot a closing parenthesis on a preceding line:
screenNames.append(zip(toGet, toAppend)
# ^ ^ ^^?
# | \---- closed ---/|
# \----- not closed ---/
You'll have another problem here, as screenNames is a dict object, not a list, and has no .append() method. If you wanted to update the dictionary with key-value pairs, use update() instead:
screenNames.update(zip(toGet, toAppend))