anytime I run python I get the following error:
Screenshot of when I run Python
Python typically works fine despite the error. However, I when I run a script with this function:
def selectFromDict(options, name):
index = 0
indexValidList = []
print('Select a ' + name + ':')
for optionName in options:
index = index + 1
indexValidList.extend([options[optionName]])
print(str(index) + ') ' + optionName)
inputValid = False
while not inputValid:
inputRaw = input(name + ': ')
inputNo = int(inputRaw) - 1
if inputNo > -1 and inputNo < len(indexValidList):
selected = indexValidList[inputNo]
print('Selected ' + name + ': ' + selected)
inputValid = True
break
else:
print('Please select a valid ' + name + ' number')
return selected
This is the result:
Screenshot of Error with I use selectFromDict()
How can I fix the error when I run Python?
Related
After F5 in Idle the input prompt appears, I enter a number the file is generated - everything works.
If I try to execute the script directly from the file a console is opened and closed with no result.
If I move the f = open("galaxies.txt","w+") before the outer most FOR loop the script doesn't work at all.
Any suggestions for a fix and reasons why it behaves like this?
import string, random
f = open("galaxies.txt","w+")
def inputNumber(message):
while True:
try:
howmany = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return howmany
break
string.ascii_letters
type_galaxy = ['elliptical','spiral','irregular']
howmany = inputNumber('How many galaxies to generate? ')
for i in range(howmany):
planet_names = []
pos_0 = 'g' + random.choice(string.ascii_letters).upper() + random.choice(string.ascii_letters).upper() + random.choice(string.ascii_letters).upper() + '-' + random.choice(string.ascii_letters).upper() + str(random.randint(1, 9999))
gal_type = type_galaxy[random.randint(0,2)]
num_of_planets = random.randint(1,43)
for k in range(num_of_planets):
pos_1 = 'p' + random.choice(string.ascii_letters).upper() + random.choice(string.ascii_letters).upper() + '-' + random.choice(string.ascii_letters).upper() + str(random.randint(1, 99))
planet_names.append(pos_1)
if i < 1:
f.write('-----Galaxy '+pos_0+'----- \n')
else:
f.write('\n-----Galaxy '+pos_0+'----- \n')
f.write('Type: '+gal_type + ' \n')
f.write('There are '+str(num_of_planets)+' planets in the galaxy. Their names are: \n')
for x in planet_names:
f.write (x + ' and it has ' + str(random.randint(0,56)) + 'moons \n')
f.write('-----Thats all from Galaxy '+pos_0+'----- \n')
f.close()
I need to put a space between the list (a cat's name) and the index.
Right now it comes out like this:
Pussy0
Pinky1
Fats2
I want it to print out like this:
Pussy 0
Pinky 1
Fats 2
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
#print(name)
for i in range(len(catNames)):
print(catNames[i] + str(i))
Just do this:
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
#print(name)
for i in range(len(catNames)):
print(catNames[i] + " " + str(i))
Though its always better to use f-strings or format:
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
#print(name)
for i in range(len(catNames)):
print(f"{catNames[i]} {str(i)}")
Using f-strings makes the code much cleaner, and simpler to understand. Look here for more details. Note that f-strings are only for python 3.6 or above. If you have a version of python below 3.6, check my previous answer to see how you can use f-strings in below python 3.6.
Try string formatting:
catnames = ['Fuzzy', 'Pinky', 'Fats']
for i, cname in enumerate(catnames):
print('{} {}'.format(cname, str(i)))
I would suggest using string interpolation for this:
for i in range(len(catNames)):
print(f"{catNames[i]} {i}")
I with the help of "Demolution Brother" showed me how to write a list in a string followed by an index.
print(str(i),":",catNames[I])
print function
Turn the interfere into a string - (str(
After the str( we now have the interfere (str(I)
Important to use the , to separate the string to put in " : ". It has to be done with
double-quotes.
Now after the comma , we can continue with catNames[I]) (The List)
List item now prints after the index.
Answer - print(catNames[i], " : ", str(I))
Some of the other ways to it was tried out:
#print(str(i),":",catNames[i])
#print(catNames[i], i, end=' ')
#print(catNames[i],end=' ' + str(i))
The code -cat_names
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] # list concatenation
print('The cat names are:')
#for name in range(len(catNames)):
#print(name)
for i in range(len(catNames)):
print(str(i),":",catNames[i])
#print(catNames[i], " : ", str(i))
Using Python 3.7.
Is there any way to use a local variable as a counter?
I tried and received error:
UnboundLocalError
I did find a recommendation to use a glbal variable which is working, but if possible I would prefer to use a local variable.
Thanks,
-w
Working code using global variable for counter:
count = 0
def my_collatz(number):
global count
count +=1
if int(number)%2 == 0:
r = int((number)//2)
else:
r = int(((number * 3) + 1))
print('Attempt : ' + str(count) + ',' + str(r))
if r != 1:
return my_collatz(int(r))
print('Please enter a number : ')
number=input()
my_collatz(int(number))
It is a very strange function indeed. Anyway, you can avoid using a global variable by converting it into an input parameter:
count = 0
def my_collatz(number, count):
count +=1
if int(number)%2 == 0:
r = int((number)//2)
else:
r = int(((number * 3) + 1))
print('Attempt : ' + str(count) + ',' + str(r))
if r != 1:
return my_collatz(int(r), count=count)
print('Please enter a number : ')
number=input()
my_collatz(int(number),count)
One possible solution is to move the count variable as parameter to the function and increment it each call:
def my_collatz(number, count=1):
if number % 2 == 0:
r = number // 2
else:
r = (number * 3) + 1
print('Attempt : ' + str(count) + ',' + str(r))
if r != 1:
return my_collatz(r, count + 1)
print('Please enter a number : ')
number=input()
my_collatz(int(number))
Prints:
Please enter a number :
6
Attempt : 1,3
Attempt : 2,10
Attempt : 3,5
Attempt : 4,16
Attempt : 5,8
Attempt : 6,4
Attempt : 7,2
Attempt : 8,1
Other solution is to not use count at all, and instead make the function a generator (using yield). Then you can use enumerate() to obtain your number of steps:
def my_collatz(number):
if number % 2 == 0:
r = number // 2
else:
r = (number * 3) + 1
yield r
if r != 1:
yield from my_collatz(r)
print('Please enter a number : ')
number=input()
for count, r in enumerate(my_collatz(int(number)), 1):
print('Attempt : ' + str(count) + ',' + str(r))
I wrote some code but I can't get why the pyscripter is telling a syntax error in the if statement:
#search for 9 elements
file_writer = open('C:\\PythonProject2\\commands_NUM.txt','w')
for item in data_indices:
flag= search_object(item,data,obj_value_min,obj_value_max)
if flag = True:###ERROR
file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n') ##Here is the syntax error
file_writer.close()
def search_object(pixel,frame,min_val,max_val):
(obj_y,obj_x) = pixel
y_center = pixel[0]+1
x_center = pixel[1]+1
if(obj_y<=597 and obj_x<=797 ):
for y in range(0,3):
for x in range(0,3):
if((frame[obj_y+y][obj_x+x])<=min_val or(frame[obj_y+y] [obj_x+x])>=max_val ):
return False
return True
if statement is indented inwards in for loop. And also = means assignment use == instead
for item in data_indices:
flag= search_object(item,data,obj_value_min,obj_value_max)
if flag == True: #here indent this if one step back
file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n') ##He
there should be == in if statement
for item in data_indices:
flag= search_object(item,data,obj_value_min,obj_value_max)
if flag == True:
file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n')
1) Put your search_object function above - declare it before using it.
2) Fix if flag = True: to if flag:
3) Fix file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n') line indentation.
4) return True inside the function search_object is with wrong indentation too. Fix it.
I would recommend you to look at PEP 8.
I'm having some trouble with the current program I'm writing.
I'm letting the user type in a country, and then a city city in that country, and then see a weather forecast for the choosen city using API.
I'm using a class, like this:
class requestChoice:
def __init__(self):
self.countrychoice = None
self.citychoice = None
def countryChoice(self):
self.countrychoice = input("Enter which country your city is in(in english): ")
def cityChoice(self):
self.citychoice = input("Enter the name of the city: ")
And my main program looks like this:
from requestchoice import requestChoice
import requests
if __name__ == '__main__':
"""Introducion"""
print ("\nThis program lets you see a weather forecast for your choosen city.")
rc = requestChoice()
while True:
print("\nWhen you have typed in country and city, press 3 in the menu to see the weather forecast for your choice.\n")
menu = input("\nPress 1 for contry\nPress 2 for city\nPress 3 to see forecast\nPress 4 to exit\n")
if menu == "1":
rc.countryChoice()
elif menu == "2":
rc.cityChoice()
elif menu == "3":
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countrychoice + "/" + citychoice + ".json")
data = r.json()
try:
for day in data['forecast']['simpleforecast']['forecastday']:
print (day['date']['weekday'] + ":")
print ("Conditions: ", day['conditions'])
print ("High: ", day['high']['celsius'] + "C", '\n' "Low: ", day['low']['celsius'] + "C", '\n')
except Exception as e:
print ("\nHave you typed in the correct country and city?\nBecause we got a" ,e, "error")
else:
print ("\nGoodbye")
break
When I run my program I get the error NameError: name 'countrychoice' is not defined. It is going to be the same error with the citychoice. I've tried creating a list in my class and append the countrychoice to the list but without any luck. How am I supposed to make it work as wished?
You are getting a NameError on here:
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countrychoice + "/" + citychoice + ".json")
because you have no names countrychoice and citychoice defined. Perhaps you meant to use rc.countrychoice and rc.citychoice instead?
You have to access them with the corresponding object name. In this case
rc.countrychoice
rc.citychoice
So, this line
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countrychoice + "/" + citychoice + ".json")
becomes
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + rc.countrychoice + "/" + rc.citychoice + ".json")
You need to use rc.countrychoice and rc.citychoice here
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + rc.countrychoice + "/" + rc.citychoice + ".json")