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!
Related
I just started learning Python 2 days ago and I created a simple "store" that you can order and the program would tell you the total. But the problem is that I don't know how to make a person's answer to show the total value of the product. As in if person A orders an iPhone, it'll show the price of the iPhone.
I kind of did it but I used the if statements, but I know that this method isn't efficient, as well as if Person B chooses more than 1 product, I don't know how to make a sum of the prices automatically instead of using the if statements, here is my code, thank you!
print("Welcome to the Apple Store!")
name = input("What is your name?\n")
print("Hello " + name + ", welcome to the Apple store!\n\n")
products = "iPhone 14 $10,000, Macbook Air $14,000, iPhone 13 $8,000\n"
value = input
iPhone_14 = 10000
Macbook_Air = 14000
iPhone_13 = 8000
a = iPhone_14 + Macbook_Air
order = input("Here is our list of products, what would you want?\n" + products)
if order == "iPhone 14":
print("Alright " + name + ", your " + order + " will be prepared.\n\n" + "The total amount will be " + str(iPhone_14))
if order == "Macbook Air":
print("Alright " + name + ", your " + order + " will be prepared.\n\n" + "The total amount will be " + str(Macbook_Air))
if order == "iPhone 13":
print("Alright " + name + ", your " + order + " will be prepared.\n\n" + "The total amount will be " + str(iPhone_13))
if order == "iPhone 14, Macbook Air":
print("Alright " + name + ", your " + order + " will be prepared.\n\n" + "The total amount will be " + str(a))
This could be a simple solution, I left you some comments inside the code:
# you can use a dictionary to store the value of each product
products = {"iPhone_14": 10000, "Macbook_Air": 14000, "iPhone_13": 8000}
# this list will contain the keys of the products you want to add to cart
cart = []
print("Here our list of products {}, what do you want to buy?\nEnter 'stop' when you're done\n".format(list(products.keys())))
stop = False
while not stop:
order = input("Insert a product:")
if order == "stop":
# if the user want to stop entering products, can type "stop" instead of a product
stop = True
elif order in products:
cart.append(order)
else:
# if the product entered is not among the products dictionary keys
print("Product {} is not available".format(order))
print("\nThis is your cart:")
total = 0
for elem in cart:
print("Product {} ({}$)".format(elem, products[elem]))
total += products[elem]
print("Your total is {}$".format(total))
Example:
Here our list of products ['iPhone_14', 'Macbook_Air', 'iPhone_13'], what do you want to buy?
Enter 'stop' when you're done
Insert a product:Macbook_Air
Insert a product:iPhone_14
Insert a product:stop
This is your cart:
Product Macbook_Air (14000$)
Product iPhone_14 (10000$)
Your total is 24000$
I'm not sure if there is actually an error here, but I (out of curiosity) created a program that calculated how many people across ~241 generations had... let's say intimate relations before just one person in Generation Z was born, and then following that how many people had intimate relations before the whole population of Generation Z was born.
Prerequisites: There are 72.1 million people in Gen Z, and one Generation lasts 25 years. All relationships are monogamous. Each couple has one child.
import time
#I made this program out of pure curiousity (I'm not lewd, I promise) and I found it pretty interesting.
#Bunny art
print(" z")
print(" z")
print(" z")
print("(\(\ ")
print("(– -)")
print("(‘)(’)")
#Variable Declarations
generationLength = 25
totalYears = 6026
numberOfGenerations = totalYears / generationLength
numberOfCalculations = 0
numberOfPeople = 1
numberOfPeopleOnEarth = 7750000000
numberOfPeopleInThisGeneration = 72100000
def howManyPeopleHadSexBeforeICameIntoExistence():
#Mathematics
numberOfCalculations = 0
while (numberOfCalculations < numberOfGenerations):
numberOfPeople = numberOfGenerations * 2
numberOfCalculations = numberOfCalculations + 1
#Output
time.sleep(2)
print("\nCalculating pointless knowledge...")
time.sleep(2)
print("At least " + str(round(numberOfPeople)) + " people in had sex before one person in Generation Z was born.")
#Mathematics
total = round(numberOfPeople * numberOfPeopleInThisGeneration)
#Output
time.sleep(2)
print("\nCalculating extra trivia...")
time.sleep(2)
print("At least " + str(total) + " had sex before every person in Generation Z was born.")
howManyPeopleHadSexBeforeICameIntoExistence()
import time
# I made this program out of pure curiousity (I'm lewd, I promise) and I found it pretty interesting.
# Bunny art
print(" z")
print(" z")
print(" z")
print("(\(\ ")
print("(– -)")
print("(‘)(’)")
# Variable Declarations
generationLength = 25
totalYears = 6026
numberOfGenerations = totalYears / generationLength
numberOfPeopleOnEarth = 7750000000
numberOfPeopleInThisGeneration = 72100000
percentage_of_current_generation = numberOfPeopleInThisGeneration/numberOfPeopleOnEarth
max_age = 100
def howManyPeopleHadSexBeforeICameIntoExistence():
numberOfPeople = numberOfPeopleInThisGeneration * (2 ** numberOfGenerations) - numberOfPeopleInThisGeneration
# Output
time.sleep(2)
print("\nCalculating pointless knowledge...")
time.sleep(2)
print("At least " + str(round(numberOfPeople)) + " people in history had sex before one person in Generation Z was born.")
# Mathematics
total_alive = round(numberOfPeopleInThisGeneration * (2 ** (max_age/generationLength)) - 1)
# Output
time.sleep(2)
print("\nCalculating extra trivia...")
time.sleep(2)
print("At least " + str(total_alive) + " people currently alive had sex before every person in Generation Z was born.")
howManyPeopleHadSexBeforeICameIntoExistence()
sorry I am new to coding so I apologise if this is an amateur question. An exercise has asked that I create code that calculates the 4% interest on an investment for 1,2 and 3 years. I have duplicated a lot of code and would like to know how I could do it differently: in a more condensed way.
For example, is it possible to convert every year in one like such as this float(year1, year2, year3) as appose to having multiple lines of code?
startingBalance = input("Please enter your starting bank balance: ")
startingBalance = int(startingBalance)
year1 = (startingBalance * 1.04)
year2 = (year1 * 1.04)
year3 = (year2 * 1.04)
year1 = "{0:.2f}".format(year1)
year2 = "{0:.2f}".format(year2)
year3 = "{0:.2f}".format(year3)
print("Starting Balance: " + str(startingBalance) + "\n" + "Year 1 Balance: " + year1 + "\n" + "Year 2 Balance: " + year2 + "\n" + "Year 3 Balance: " + year3)
answer=str(input("would you like to withdraw your profits? Y/N: "))
if answer in ['Y', 'y']:
startingBalance = float(startingBalance)
year1 = float(year1)
year2 = float(year2)
year3 = float(year3)
year1Profit = year1 - startingBalance
year1Profit = "{0:.2f}".format(year1Profit)
year2Profit = year2 - startingBalance
year2Profit = "{0:.2f}".format(year2Profit)
year3Profit = year3 - startingBalance
year3Profit = "{0:.2f}".format(year3Profit)
str(year3Profit)
print("Year | Balance | Profit " + "\n" + "Year 1 " + str(year1) + " " + year1Profit + "\n" + "Year 2 " + str(year2) + " " + year2Profit + "\n" + "Year 3 " + str(year3) + " " + year3Profit)
elif answer in ['N', 'n']:
print("Goodbye")
else:
print("Invalid Entry")
Technically this is one line:
year1, year2, year3 = float(year1), float(year2), float(year3)
But I think it would be clearer if you didn't change the type of your variables after initialisation. You can keep them as floats all the time change your print line to:
print("Starting Balance: " + str(startingBalance) + "\n" + "Year 1 Balance: " + "{0:.2f}".format(year1) + "\n" + "Year 2 Balance: " + "{0:.2f}".format(year2) + "\n" + "Year 3 Balance: " + "{0:.2f}".format(year3))
This saves you from converting to string and back again.
This question might be more appropriate in Code Review but:
year1 = "{0:.2f}".format(year1)
Can be replaced by:
year1 = round(year1, 2)
You use .format and print("foo" + bar) in the same code I recommend using one type:
F-strings if Python3.6 or above
print(f"Starting Balance: {startingBalance}\nYear 1 Balance: {year1}\nYear 2 Balance: {year2}\nYear 3 Balance: {year3}")
.format if Python2 or 3 < 3.6
print("Starting Balance: {}\nYear 1 Balance: {}\nYear 2 Balance: {}\nYear 3 Balance: {}".format(startingBalance, year1, year2, year3))
No need to put str() here :
answer=str(input("would you like to withdraw your profits? Y/N: "))
The input() always returns a string.
Use "\t" when you want (i'm guessing) tabulations instead of a bunch of spaces (ugly):
print("Year | Balance | Profit " + "\n" + "Year 1 " + str(year1) + " " + year1Profit + "\n" + "Year 2 " + str(year2) + " " + year2Profit + "\n" + "Year 3 " + str(year3) + " " + year3Profit)
Same thing here use f-strings or .format to format your string.
To avoid writing the same code, you can create a function to compute the final balance and the profit. Then you can use the others answers to know how to format your variable and return them
def compute_year(starting_balance, number_of_year):
return (startingBalance * 1.04 ** number_of_year, startingBalance * 1.04 ** number_of_year - startingBalance)
year1, year1Profit = compute_year(startingBalance, 1)
year2, year2Profit = compute_year(startingBalance, 2)
year3, year3Profit = compute_year(startingBalance, 3)
Yes, it is very much possible!
When you find yourself writing repeating lines of code, try using functions!
In that way you only have to define an expression once!
example:
year1 = (startingBalance * 1.04)
year2 = (year1 * 1.04)
year3 = (year2 * 1.04)
Can be change to
def interest(balance):
return balance * 1.04
year1 = interest(startingBalance)
year2 = interest(year1)
But this still seems repetitive, right?
Now try using a for-loop aswell:
current_balance = startingBalance
for year in range(4):
current_balance = interest(current_balance)
print(current_balance)
Now in each loop, you can print the value of the new balance!
Finally add in the line printg for a pretty output, and you could get something like this:
def interest(balance, years):
return balance * (1.04 ** years)
def print_gains(balance, year):
header = 'Year | Balance | Profit '
print(header)
print('-' * len(header))
for year in range(1 + year):
new_balance = interest(balance, year)
print('%5d| %10.2f | %10.2f' % (year, new_balance, new_balance - balance))
print()
def main():
print_gains(10000, 5)
main()
resulting in the following output:
Year | Balance | Profit
-----------------------------
0| 10000.00 | 0.00
1| 10400.00 | 400.00
2| 10816.00 | 816.00
3| 11248.64 | 1248.64
4| 11698.59 | 1698.59
5| 12166.53 | 2166.53
I hope this helps you!
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.
This program is supposed to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company. When I try to run it, it shows a SyntaxError, and I'm not sure why. Here's my code:
def ccb(balance, annualInterestRate, monthlyPaymentRate):
monthlyInterestRate = annualInterestRate / 12.0
month = 0
for calc in range(12):
minMonthlyPaymentRate = balance * monthlyPaymentRate
unpaidBalance = balance - minMonthlyPaymentRate
interest = monthlyInterestRate * unpaidBalance
print ("Month | Balance | Unpaid Balance | Interest")
print (month + " | " + round(balance) + " | " + round(unpaidBalance) + " | " + Interest)
balance = unpaidBalance + Interest
month += 1
print ("Remaining balance: " + round(balance))
A few things (though none appear to throw SyntaxError - seconding Andrew in the comments, if it's a SyntaxError - share the full message):
1) You can't implicitly make an integer a string, you need to cast it. Ex:
str(round(balance))
instead of
round(balance)
2) 'Interest' is never defined, but 'interest' is.
With those fixed, it runs fine.
Also, this might be relevant ;)