Python functions and formatting not working - python

I'm currently having a problem with a function in python. This is my code before I tried putting it in a function:
for i in range(4):
for y in Days:
for x in "ABCDEF":
data = input("What was the punctuality for bus " + x + " on " + str(y) + ", Week " + str(Week) + "? ")
Bus = "Bus" + str(x)
Buses[Bus].append(str(data))
print()
Week += 1
And it works like it is meant to, however I tried putting it in a function:
def InputData():
for i in range(4):
for y in Days:
for x in "ABCDEF":
data = input("What was the punctuality for bus " + x + " on " + str(y) + ", Week " + str(Week) + "? ")
Bus = "Bus" + str(x)
Buses[Bus].append(str(data))
print()
Week += 1
And I am getting errors about the whole Week += 1 part. They say:
[pyflakes] local variable 'Week' (defined in enclosing scope on line 11)
referenced before assignment
[pyflakes] local variable 'Week' is assigned to but never used
Any help would be greatly appreciated.

Week = 0
Put this at the beginning of your code.

Related

Type Error: unsupported operand type(s) for +: 'NoneType' and 'str' exit status 1

I keep editing my text but I keep on getting the same error!
My code:
import random
Female_Characters = ["Emily", "Ariel", "Jade", "Summer"]
Male_Characters = ["Blake", "Max", "Jack", "Cole", "Daniel"]
PlacesToMeet = ["Beach", "Park", "Train Station", "Cave"]
SheSaid = ["Lets go explore!", "I'm tired", "I saw a purple frog", "My tounge hurts"]
HeSaid = ["I didnt get much sleep", "I wanna go inside that cave!", "Oh, ok"]
Outcomes = ["They never got to", "They were never found again.", "They enjoyed their day and went to
get Ice Cream!"]
ChosenFemale = random.choice(Female_Characters)
ChosenMale = random.choice(Male_Characters)
ChosenMeet = random.choice(PlacesToMeet)
ChosenShesaid = random.choice(SheSaid)
ChosenHeSaid = random.choice(HeSaid)
print ("There were two friends, their names are ") + (ChosenMale) + (", and ") + (ChosenFemale) + (".") + ("One day when they were at the") + (ChosenMeet) + (", ") + (ChosenFemale) + (" Said, ") + (ChosenShesaid) + (". Then") + (ChosenMale) + (" Said ") + (ChosenHeSaid) + (". After that, ") + random.choice(Outcomes)
Still new to python
You have incorrect parentheses on the print line.
print("There were two friends, their names are " + ChosenMale + ", and " + ChosenFemale + "." + "One day when they were at the" + ChosenMeet + ", " + ChosenFemale + " Said, " + ChosenShesaid + ". Then" + ChosenMale + " Said " + ChosenHeSaid + ". After that, " + random.choiceOutcomes)
Your code was calling
print("There were two friends, their names are ")
which returns None, and then trying to concatenate that with all the other strings.
Maybe you were following Python 2.x instructions. In Python 2, print is a statement so it didn't take an argument in parentheses, but in Python 3 it's an ordinary function.
remove the parenthesis at the end of this string
print("There were two friends, their names are "
and add it at the end of
random.choice(Outcomes)
so it should be:
print ("There were two friends, their names are " + (ChosenMale) + (", and ") + (ChosenFemale) + (".") + ("One day when they were at the") + (ChosenMeet) + (", ") + (ChosenFemale) + (" Said, ") + (ChosenShesaid) + (". Then") + (ChosenMale) + (" Said ") + (ChosenHeSaid) + (". After that, ") + random.choice(Outcomes))

Need help to make while loop restart my Python program from top

I would like to get help with this program I have made. The function of the code is so the users can input a city anywhere in the world and they will then get data about the weather for that city.
I want it to restart the program from the top, but it only restarts the program from where the results are.
# - Weather Program -
#Import
import datetime
import requests
import sys
#Input
name_of_user = input("What is your name?: ")
city = input('City Name: ')
#API
api_address='http://api.openweathermap.org/data/2.5/weather?appid=<app_id_token>&q='
url = api_address + city
json_data = requests.get(url).json()
#Variables
format_add = json_data['main']['temp']
day_of_month = str(datetime.date.today().strftime("%d "))
month = datetime.date.today().strftime("%b ")
year = str(datetime.date.today().strftime("%Y "))
time = str(datetime.datetime.now().strftime("%H:%M:%S"))
degrees = format_add - 273.15
humidity = json_data['main']['humidity']
latitude = json_data['coord']['lon']
longitude = json_data['coord']['lat']
#Loop
while True:
#Program
if degrees < 20 and time > str(12.00):
print("\nGood afternoon " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a mild " + "{:.1f}".format(degrees) +
"°C, you might need a jacket.")
elif degrees < 20 and time < str(12.00):
print("\nGood morning " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a mild " + "{:.1f}".format(degrees) +
"°C, you might need a jacket.")
elif degrees >= 20 and time > str(12.00):
print("\nGood afternoon " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a warm " + "{:.1f}".format(degrees) +
"°C, don't forget to drink water.")
elif degrees >= 20 and time < str(12.00):
print("\nGood morning " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a warm " + "{:.1f}".format(degrees) +
"°C, don't forget to drink water.")
#Loop
restart = input('Would you like to check another city (y/n)?: ')
if restart == 'y':
continue
else:
print('Goodbye')
sys.exit()
So this is what happens.. The loop only loops the question with the input and data already filled in.
What is your name?: Test
City Name: Oslo
Good afternoon Test.
The date today is: 01 May 2019
The current time is: 20:23:36
The humidity is: 76%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 12.7°C, you might need a jacket.
Would you like to check another city (y/n)?: y
Good afternoon Test.
The date today is: 01 May 2019
The current time is: 20:23:36
The humidity is: 76%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 12.7°C, you might need a jacket.
Would you like to check another city (y/n)?: n
Goodbye
Process finished with exit code 0
I want the code to loop from the top so I can press y so the program will ask me for another city to input.
You are never updating your values. Let's take a simpler example:
x = int(input("What is the number you choose? "))
while True:
if x >3:
print(x)
continue
else:
break
If I run this, I will get x printed out forever if I choose, say 5. The code defining x will never be re-run because it's outside of the loop. To fix this, I can move my code for x into the while loop:
while True:
x = int(input("What number do you choose? "))
if x>3:
print(x)
else:
break
This will run the code for x every time the loop executes, so x can now change. Applying this to your code:
# loop is now up near the top
while True:
# You want these values to change on each iteration of the while
# loop, so they must be contained within the loop
name_of_user = input("What is your name?: ")
city = input('City Name: ')
#API
api_address='http://api.openweathermap.org/data/2.5/weather?appid=<app_id_token>&q='
url = api_address + city
json_data = requests.get(url).json()
#Variables
format_add = json_data['main']['temp']
day_of_month = str(datetime.date.today().strftime("%d "))
month = datetime.date.today().strftime("%b ")
year = str(datetime.date.today().strftime("%Y "))
time = str(datetime.datetime.now().strftime("%H:%M:%S"))
degrees = format_add - 273.15
humidity = json_data['main']['humidity']
latitude = json_data['coord']['lon']
longitude = json_data['coord']['lat']
if degrees... # rest of your statements
Now the value for City can change, and you can apply that to the other data structures as well
Put your while loop starting above the first input. Don't forget to declare your constant variables above the main loop.
The while loop only covers the code that display the results, the code that takes input and request the results is only executed once.
You need to have everything except the import statements within the while loop
All you need to is put the input section and the API sections inside your while true loop.
I will say, I was unable to actually test my solution, but I am almost completely sure that it will work. Good luck!

unsupported operand type "float" and "str" [duplicate]

This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 6 years ago.
i'm trying to print the operation however the first statement is working but second statement has error.
conSwitch = raw_input("Enter cycle of context switch: ")
cycleOpr = raw_input("Enter cycle operation: ")
totalCycle = float(conSwitch) + float(cycleOpr) + float(conSwitch)
print "Context =", conSwitch
print "Cycle operation =", cycleOpr
print "Context switch back =", conSwitch
print("\n")
print (conSwitch + " + " + cycleOpr + " + " + conSwitch)
print ("Total number of cycle is: " + format(totalCycle))
print("===================================================")
reqSecond = raw_input("Enter cycle request second:")
print "Total cycle request =", totalCycle
print "Cycle request per second =", reqSecond
print("\n")
totalSpent = float(totalCycle) * float(reqSecond)
print (totalCycle + " * " + reqSecond)
print ("Total number of spent = " + format(totalSpent))
==============================================================
First statement
Work===>> print (conSwitch + " + " + cycleOpr + " + " + conSwitch)
Second statement
Error===>> print (totalCycle + " * " + reqSecond)
The problem here is that the variable totalCycle is of type float. Python does not know what it means to do + between a type float and string (because " * " is a string).
To do it the way you showed you have to convert totalCycle to string first, like this:
print (str(totalCycle) + " * " + reqSecond)
FORMAT Syntax
"First, thou shalt count to {0}" # References first positional argument
"Bring me a {}" # Implicitly references the first positional argument
"From {} to {}" # Same as "From {0} to {1}"
"My quest is {name}" # References keyword argument 'name'
"Weight in tons {0.weight}" # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}" # First element of keyword argument 'players'.

How do I return the value from each iteration of a loop to the function it is running within?

I'm making a program that scrapes local bus times from a real time information server and prints them. In order to return all the bus times, it does this:
while i < len(info["results"]):
print "Route Number:" + " " + info['results'][i]['route']
print "Due in" + " " + info["results"][i]["duetime"] + " " + "minutes." + "\n"
i = i + 1
This works fine, and returns all of the results, one by one like so:
Route Number: 83
Due in 12 minutes.
Route Number: 83
Due in 25 minutes.
Route Number: 83A
Due in 39 minutes.
Route Number: 83
Due in 55 minutes.
However, as I'm using this feature within another script, I turned the code to fetch times and return them into a function:
def fetchtime(stopnum):
data = "?stopid={}".format(stopnum)+"&format=json"
content = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation"
req = urllib2.urlopen(content + data + "?")
i = 0
info = json.load(req)
if len(info["results"]) == 0:
return "Sorry, there's no real time info for this stop!"
while i < len(info["results"]):
return "Route Number:" + " " + str(info['results'][i]['route']) + "\n" + "Due in" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n"
i = i + 1
This works, however it only returns the first bus from the list given by the server, instead of however many buses there may be. How do I get the printed result of the function to return the info supplied in each iteration of the loop?
Can you not just make a list and return the list?
businfo = list()
while i < len(info["results"]):
businfo.append("Route Number:" + " " + str(info['results'][i]['route']) + "\n" + "Due in" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n")
i = i + 1
return businfo
You will have to edit the printing commands that this function returns to.
I would suggest you to use the yield statement instead return in fetchtime function.
Something like:
def fetchtime(stopnum):
data = "?stopid={}".format(stopnum)+"&format=json"
content = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation"
req = urllib2.urlopen(content + data + "?")
i = 0
info = json.load(req)
if len(info["results"]) == 0:
yield "Sorry, there's no real time info for this stop!"
while i < len(info["results"]):
yield "Route Number:" + " " + str(info['results'][i]['route']) + "\n" + "Due in" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n"
i = i + 1
It would allow you to pick one data at a time and proceed.
Lets say that info["results"] is a list of length 2, then you could do:
>> a = fetchtime(data)
>> next(a)
Route Number: 83 Due in 25 minutes.
>> next(a)
Route Number: 42 Due in 33 minutes.
>> next(a)
StopIteration Error
or simple do:
>> for each in a:
print(each)
Route Number: 83 Due in 25 minutes.
Route Number: 42 Due in 33 minutes.
# In case if there would be no results (list would be empty), iterating
# over "a" would result in:
>> for each in a:
print(each)
Sorry, there's no real time info for this stop!

python ParseError: Bad Input on line

ok so I a trying to make a calculator in python and it comes up with ParseError: Bad Input on line 7 and ParseError: Bad Input on line 6 etc. all the way down to ParseError: Bad Input on line 1, can anyone spot the error and how to fix it.
1:) n = input(" select first number: ")
2:) d = raw_input("What operation: ")
3:) print " What operation: " + str(d)
4:) n1 = input(" select second number ")
6:) if d == "+":
7:) print "Did you know that " + str(n) + " plus " + str(n1) + " is "
7:) + str(n+n1)+ "?"
8:)
9:)print " "
10:)print "Goodbye"
The line:
print "Did you know that " + str(n) + " plus " + str(n1) + " is "
will happily print something. Then the interpreter sees this:
+ str(n+n1)+ "?"
and has no idea what you mean, because it doesn't know you're continuing the previous line's print statement. You can fix this by adding parentheses:
>>> print ("Did you know that " + str(1) + " plus " + str(1) + " is "
... + str(2)+ "?")
Did you know that 1 plus 1 is 2?
Now the interpreter knows that, when you finish that first line, you're not done entering the expression. It will wait for you to finish a valid statement before processing it. See also logical lines and physical lines in Python.

Categories

Resources