I have created this code to get 3 different options in 3 different places. Its actually a flash card program i hoped to get working but I can't. It goes into a endless loop and i have no idea why. There may also be other problems but i havent got to them yet but please tell me anyway. Keep the sam var names so i can understand easily. I have attached all the code. They is some more but its not been implemented yet.
There is also 3 lists each with 14 items but these won't go into code:
key_words = ['Cellulose', 'Respiration', 'Haemoglobin', 'Ventilation', 'Cartilage', 'Cytoplasm', 'Nucleus', 'Alveoli', 'Amino acids', 'Virus', 'White blood cells', 'Photosynthesis', 'Stomata', 'Vaccine', 'Fibre']
defs = ['Tough substance that makes up the cell walls of green plants', 'A chemical reaction that causes energy to be released from glucose', 'A substance which joins to oxygen and carries it round the body in the blood', 'Breathing', 'Tough, smooth substance covering the ends of bones to protect them', 'Jelly-like part of a cell where chemical reactions happen', 'Controls what happens inside a cell', 'Tiny air sacs in the lungs', 'Produced when proteins are digested', 'The smallest type of microbe', 'Can engulf bacteria or make antibodies', 'The process of turning carbon dioxide, water and light into glucose and oxygen', 'Small holes in the underside of a leaf', 'Dead or inactive forms of a microorganism', 'A nutrient that cannot be digested']
completed = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
thanks
Callum
import random
option1 = random.randint(int(1), int(14))
option2 = random.randint(int(1), int(14))
option3 = random.randint(int(1), int(14))
while option1 == option2 or option1 == option3:
placement1 = random.randint(int(1), int(3))
while option2 == option3:
option2 = random.randint(int(1), int(3))
placement1 = random.randint(int(1), int(3))
placement2 = random.randint(int(1), int(3))
placement3 = random.randint(int(1), int(3))
while placement1 == placement2 or placement1 == placement3:
placement1 = random.randint(int(1), int(3))
while placement2 == placement1 or placement2 == placement3:
placement3 = random.randint(int(1), int(3))
print('What is the correct defenition for', key_words[option3])
place3 = 1
if placement1 == 1:
print('1: ', defs[option1])
elif placement1 == 2:
print('1: ', defs[option2])
elif placement1 == 3:
print('1: ', defs[option3])
place3 = '1'
if placement2 == 1:
print('2: ', defs[option1])
elif placement2 == 2:
print('2: ', defs[option2])
elif placement2 == 3:
print('2: ', defs[option3])
place3 = '2'
if placement3 == 1:
print('3: ', defs[option1])
elif placement3 == 2:
print('3: ', defs[option2])
elif placement3 == 3:
print('3: ', defs[option3])
place3 = '3'
choice = str(input('Enter 1, 2 or 3: '))
if choice == place3:
print('Well done, correct.')
a = completed[option3] + 1
completed[option3] += 1
else:
print('Inccorect. Have another look and we`ll come back later.')
In your first loop:
while option1 == option2 or option1 == option3:
placement1 = random.randint(int(1), int(3))
you never change the value of option1. If the condition is true going into the loop, it will remain true forever. Did you mean to use option1 instead of placement1?
You will never break out of your first loop.
while option1 == option2 or option1 == option3:
placement1 = random.randint(int(1), int(3))
The condition hinges on the values of option1, option2, and option3, which are never adjusted in the body of the loop. If the code enters the loop, it will stay there.
Incidentally, this code has numerous other serious problems and code smells. I don't have time to name them all.
Related
I have a task where I'm supposed to create a ticket where the user first choose which kind of ticket they want and then if they want to add a bag (option 1) or a meal (option 2). The user can also choose to remove a bag (option 3) or a meal (option 4), if they regret their first choice. All the choices are then gonna be printed on a receipt.
My problem is how to store the option that the user choses. I created a while loop that runs until the user want to finalize its ticket. This is my while-loop:
while yourchoice != 5:
if yourchoice == 1:
addonebag = str('1 bag(s) registered')
choiceslist.append(addonebag)
elif yourchoice == 2:
addonemeal = str('1 meal(s) registered')
choiceslist.append(addonemeal)
elif yourchoice == 3:
removebag = str('0 bag(s) registered')
choiceslist.pop(addonebag)
choiceslist.append(removebag)
elif yourchoice == 4:
removemeal = str('0 meal(s) registered')
choiceslist.pop(1,addmeal)
choiceslist.insert(1,removemeal)
else:
print('\n'
'Invalid option. Please try again.')
I want the output to look like this depending on the option the user chose (it can also say 1 bag or 1 meal or both):
Currently you have:
0 bag(s) registered
0 meal(s) registered
The problem is that when I create this list the output is if I chose option 1 in the first loop: ['1 bag(s) registered']
If I then chose option 3 in the next loop, the output is: ['1 bag(s) registered' '0 bag(s) registered'] instead of just ['0 bag(s) registered'].
I've tried to use pop and insert on specific indexes but it doesn't work. Does anyone have any idea of how I can solve this? Thanks!
You can try this, if this works for you.
As you only needs to get the current choice. I don't think you need to
append into the list. You can store the choices for meal and bag separately and in the end you can create a new list by using both choices.
# In the beginning choices should be 0
bag_choice = '0 bag(s) registered'
meal_choice = '0 meal(s) registered'
while yourchoice != 5:
if yourchoice == 1:
bag_choice = '1 bag(s) registered'
elif yourchoice == 2:
bag_choice = '1 meal(s) registered'
elif yourchoice == 3:
bag_choice = '0 bag(s) registered'
elif yourchoice == 4:
meal_choice = '0 meal(s) registered'
else:
print('\n'
'Invalid option. Please try again.')
#creating a list from bag_choice and meal_choice
choice_list = [bag_choice, meal_choice]
print(choice_list)
Thank you for your help! I actually tried another method where I put bag to 1 or 0 depending on the choice and it works!
Now my code looks like this:
def tickettype():
print('Ticket types: \n'
'1. Budget: 500 kr \n'
'2. Economy: 750 kr \n'
'3. VIP: 2000 kr \n')
def options():
print('\nHere are your options: \n'
'1. Add bag (max 1) \n'
'2. Add meal (max 1) \n'
'3. Remove bag \n'
'4. Remove meal \n'
'5. Finalize ticket \n')
tickettype()
tickettype1 = int(input('Choose your ticket type: '))
if tickettype1 == 1:
ticket = 500
elif tickettype1 == 2:
ticket = 750
elif tickettype1 == 3:
ticket = 2000
options()
print('\n'
'Currently you have: \n'
'0 bag(s) registered \n'
'0 meal(s) registered \n')
yourchoice = int(input('Your choice: '))
bag = 0
meal = 0
addbag = 0
addmeal = 0
while yourchoice != 5:
if yourchoice == 1:
bag = 1
bagprice = 200
addbag = str('Bag : 200')
elif yourchoice == 2:
meal = 1
mealprice = 150
addmeal = str('Meal : 150')
elif yourchoice == 3:
bag = 0
elif yourchoice == 4:
meal = 0
else:
print('\n'
'Invalid option. Please try again.')
print('\n'
f'Currently you have: \n{bag} bag(s) registered \n{meal} meal(s) registered')
options()
yourchoice = int(input('Your choice: '))
# When the user press 5:
#EDITED AFTER THIS LINE
#print(f'\nReceipt:\nTicket : {ticket}\n{addbag}\n{addmeal} \nTotal: {ticket+bagprice+mealprice}'
#create a new variable to store Total price, adding mealprice or bagprice only if they are selected else 0 will be added
Total = (mealprice if meal == 1 else 0) + (bagprice if bag == 1 else 0) + ticket
print(f'\nReceipt:\nTicket:{ticket}')
#print bag only if it is selected, bag value will became 1 only if it is selected
if bag == 1:
print(addbag)
# print meal only if it is selected, meal value will became 1 only if it is selected
if meal == 1:
print(addmeal)
# print the Total price
print(f'Total:{Total}')
However, it does not print like I want to. For example if I choose ticket no 1 and to add one bag, the output is:
Receipt:
Ticket : 500
Bag : 200
0
Total: 850
But I only want the total to be 700 and I don't want the "0" on the line after "Bag". It stills adds the meal price to the total price and the "0" comes from the line before the while-loop. I put the meal price and the print string for meal in option 3 so I don't know why it still adds the meal price?
So what I want it to look like in the receipt is:
Receipt:
Ticket : 500
Bag : 200
Total: 700
Any ideas on how I can solve this? :)
So I am making a camel game and I get a weird error that says
"TypeError: '>' not supported between instances of 'tuple' and 'int'"
and I am not sure what this means, I have posted before and I will state this again I am a beginner coder. Thank you to whoever helps here is the code and I will put a comment where the error is that you!
import random
done = False
milesTraveled = 0
thirst = 0
camelTired = 0
nativesDis = -20
canteens = 5
print('''
Welcome to Camel!
You have stolen a camel to make your way across the great Mobi desert.
The natives want their camel back and are chasing you down! Survive your
desert trek and outrun the natives. ''')
while not done:
oasis = (1,21)
if oasis == 4:
print("You found an oasis!")
canteens = 5
thrist = 0
if thirst > 6:
print("You died of thrist!")
spc = input("")
done = True
if thirst > 4:
print("You are thirsty")
#under here
if camelTired > 8:
print("Your camel DIED!")
spc = input("")
done = True
if camelTired > 5:
print("Your camel is getting tired")
if nativesDis == milesTraveled + 20:
print('The natives caught up with you!')
spc=input("")
done = True
if milesTraveled == 200:
print('You Win!')
spc = input("")
done = True
print('''
A. Drink from your canteen.
B. Ahead full speed.
C. Stop and rest.
D. Status check.
Q. Quit ''')
user_choice = input("")
if user_choice.upper() == 'Q':
done = True
elif user_choice.upper() == 'D':
print('''
Miles Traveled: 0
Drinks In Canteen:''',canteens,'''
Thirstyness:''',thirst,'''
The Natives Are 20 Miles Behind You''')
elif user_choice.upper() == 'C':
camelTired = 0
nativesDis = random.randint(7,15)
elif user_choice.upper() == 'B':
milesTraveled = random.randint(10,22)
print("You traveled",milesTraveled,"miles!")
thirst + 1
camelTired = (1,3)
nativesDis = (7,14)
elif user_choice.upper() == 'A':
if canteens > 0:
canteens = canteens - 1
thirst
= 0
You need to take the number out of the tuple and into a variable that is also an integer.
There are multiple integers in your tuple.
You can access them in the following way:
some_tuple_of_integers = (12, 432, 345)
index_zero_integer = some_tuple_of_integers[0]
index_one_integer = some_tuple_of_integers[1]
index_two_integer = some_tuple_of_integers[2]
print(index_zero_integer)
print(index_one_integer)
print(index_two_integer)
Or just straight from the tuple itself without creating a new variable (This can sometimes get unreadable when working with lots of indexes and tuples).
print(some_tuple_of_integers[0])
print(some_tuple_of_integers[1])
print(some_tuple_of_integers[2])
You can then easily compare between other values.
If, for example you have a string from the tuple that you need to compare with another integer, you can change it by doing:
index_two_integer = int(index_two_integer)
Ok I have a feeling that this is a simple simple issue but I have been staring at this code for about 10 hours now.
The issue I am having is in mastermind is that once I get it to recognize that I have the correct colors in the right spot I can get it to display the right spots with X and the wrong spots with O. I need to be able to convert that so instead of X and O I need it to tell the user that he/she has 2 blacks and one white
For example: The secret code is RGYB The user enters RGOY so then Python relays "You have 2 blacks(The R and G spots) and one 1 White (The Y because it's the right color just in the wrong index) As of right now I got it to display X for the right color in the right spot and anything else it is an O
I will post what I have been working with now but today I am at my wit's end
https://pastebin.com/HKK0T7bQ
if correctColor != "XXXX":
for i in range(4):
if guess[i] == tempCode[i]:
correctColor += "X"
if guess[i] != tempCode[i] in tempCode:
correctColor += "O"
print (correctColor + "\n")
if correctColor == "XXXX":
if attempts == 1:
print ("You think you are sweet because you got it right on the first try? Play me again!")
else:
print ("Well done... You needed " + str(attempts) + " attempts to guess.")
game = False
A few comments
X and O
you use X and 0 to denote the success, it will be easier and faster to use a list or tuple or booleans for this, that way you can use sum() to count how many colors and locations were correct. Then whether you represent that with X and O or red and white pins is a matter for later
compartmentalization
Your game logic (guess input, input validation, do you want to continue, etc) is mixed with the comparison logic, so it would be best to separate the different functions of your program into different methods.
This is an fineexample to introduce object oriented programming, but is so simple it doesn't need OO, but it can help. What you need is a method which takes a series of colours and compares it to another series of colours
Standard library
Python has a very extended standard library, so a lot of stuff you want to do probably already exists
Correct colours
to count the number of letters which occur in 2 strings, you can use collections.Counter
guess = "RGOY "
solution = "RGYB"
a = collections.Counter(guess)
b = collections.Counter(solution)
a & b
Counter({'G': 1, 'R': 1, 'Y': 1})
correct_colours = sum((a & b).values())
3
So the user guessed 3 colours correctly
Correct locations
can be solved with an easy list comprehension
[g == s for g, s in zip(guess, solution)]
[True, True, False, False]
sum(g == s for g, s in zip(guess, solution))
2
so the used put 2 colours on the correct location
This is a MasterMind I made in Python. Hope you like it and it helped you! :)
import random
import time
from tkinter import *
def select_level():
global level
level = level_selector.get()
root.destroy()
root = Tk()
level_selector = Scale(root, from_=1, to=3, tickinterval=1)
level_selector.set(0)
level_selector.pack()
Button(root, text="Select a difficulty level", command=select_level).pack()
mainloop()
cpc_1_digit = 0
cpc_2_digit = 0
cpc_3_digit = 0
cpc_4_digit = 0
p_1_digit = 0
p_2_digit = 0
p_3_digit = 0
p_4_digit = 0
correct_correct = 0
correct_wrong = 0
chances = 0
if level == 1:
chances = 15
elif level == 2:
chances = 10
else:
chances = 7
cpc_1_digit = random.randint(0, 9)
while cpc_2_digit == cpc_1_digit or cpc_2_digit == cpc_3_digit or cpc_2_digit ==
cpc_4_digit:
cpc_2_digit = random.randint(0, 9)
while cpc_3_digit == cpc_1_digit or cpc_3_digit == cpc_2_digit or cpc_3_digit ==
cpc_4_digit:
cpc_3_digit = random.randint(0, 9)
while cpc_4_digit == cpc_1_digit or cpc_4_digit == cpc_2_digit or cpc_4_digit ==
cpc_3_digit:
cpc_4_digit = random.randint(0, 9)
while chances > 0:
correct_correct = 0
correct_wrong = 0
answer = input("Enter a four-digit number with different digits (e.g 1476): ")
p_1_digit = int(answer[0])
p_2_digit = int(answer[1])
p_3_digit = int(answer[2])
p_4_digit = int(answer[3])
if p_1_digit == cpc_1_digit:
correct_correct = int(correct_correct) + 1
elif p_1_digit == cpc_2_digit or p_1_digit == cpc_3_digit or p_1_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_2_digit == cpc_2_digit:
correct_correct = correct_correct + 1
elif p_2_digit == cpc_1_digit or p_2_digit == cpc_3_digit or p_2_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_3_digit == cpc_3_digit:
correct_correct = int(correct_correct) + 1
elif p_3_digit == cpc_1_digit or p_3_digit == cpc_2_digit or p_3_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_4_digit == cpc_4_digit:
correct_correct = int(correct_correct) + 1
elif p_4_digit == cpc_1_digit or p_4_digit == cpc_3_digit or p_4_digit ==
cpc_2_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
print("")
if int(correct_correct) == 4:
print("Congratsulations! You found the computer's number!")
break
elif int(correct_wrong) > 0 or int(correct_correct) >= 1 and int(correct_correct)
< 4:
print("You got " + str(correct_correct) + " correct digit(s) in the correct
place, and " + str(correct_wrong) + " correct digit(s) but in wrong place.")
elif int(correct_correct) == 0 and int(correct_wrong) == 0:
print("You didn't guess any number, try again!")
else:
raise Exception("CheckError: line 69, something went wrong with the
comparings.")
exit()
print("")
chances = chances - 1
if chances == 0:
print("You lost... The secret number was " + str(cpc_1_digit) + str(cpc_2_digit)
+ str(cpc_3_digit) + str(cpc_4_digit) + ". Try again by rerunning the program.")
time.sleep(4)
"""read file and store into database"""
f = open('C:\\Users\\user.name\\Desktop\\tunes.txt','r')
artist=[""]
song=[""]
album=[""]
genre=[""]
index=0
for line in f:
if index==0:
artist.append(line)
index=index+1
elif index==1:
song.append(line)
index=index+1
elif index==2:
album.append(line)
index=index+1
elif index==3:
genre.append(line)
index=index+1
elif index==4:
index=0
while 1:
selection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Search\n2.Recommend\n3.Edit\n4.Save\n"))
if selection == 1:
print "You selected Search"
searchselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Display All Songs\n2.Display All Artists\n3.Search By Artist\n4.Display All Genres\n5.Search by Genre\n6.Display All Playlists\n7.Search By Playlist\n"))
if searchselection == 1:
print '[%s]' % ''.join(map(str, song))
elif searchselection == 2:
print '[%s]' % ''.join(map(str, artist))
elif searchselection == 3:
artistsearch = str(raw_input("\nWhat artist are you searching for?\n"))
artist.index(artistsearch)
print value
elif searchselection == 4:
print '[%s]' % ''.join(map(str, genre))
elif searchselection == 5:
print "display"
elif searchselection == 6:
print "display"
elif searchselection == 7:
print "display"
break
elif selection == 2:
print "You selected recommend."
recommendselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Recommend by Song Title\n2.Recommend by Artist Name\n"))
if recommendselection == 1:
songrec = str(raw_input("Please enter the song title\n"))
elif recommendselection == 2:
artistrec = str(raw_input("Please enter the Artist's name\n"))
break
elif selection == 3:
print "You selected edit."
editselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Add a New Song\n2.Create New Playlist\n3.Add a song to a current playlist"))
if editselection == 1:
songadd = str(raw_input("Please enter the EVERYTHING\n"))
elif editselection == 2:
playistcreate = str(raw_input("Please enter the name of the Playlist\n"))
elif editselection == 3:
playlistadd = str(raw_input("Please enter the name of the playlist\n"))
break
elif selection == 4:
print "You selected Save."
f.close()
break
So that is what I have thus far. This is an ongoing python project, and right now I am stumped; I am trying to search by artist like if Justin Timberlake is typed in by the user as "artistsearch" then I want the index to be pulled so that I can match the index in the song list and display that information to the user.
Any help determining why Justin Timberlake is not a value on the list even though the name shows up when I run the display all artists option would be greatly appreciated.
Also being pointed in the right direction for matching list indexes would be great as well. This is an example of the tunes.txt:
Alicia Keys
No One
As I Am
R&B/Soul;Syl tunes
Everything But the Girl
Missing
Amplified Heart
Alternative;Syl tunes
Gathering Field
Lost In America
Lost In America
Rock
Ellie Goulding
Burn
Halcyon
Pop;Road tunes
Justin Timberlake
Mirrors
Mirrors (Radio Edit) - Single
Pop;Syl tunes
I think you should create a specific class for the data you want to store, and then create a list of objects that instantiate such class:
class Song():
"""Class to store the attributes for each song"""
def __init__ (self):
self.artist = ""
self.song = ""
self.album = ""
self.genre = ""
# List to store all the Song objects
songs_list = []
f = open('C:\\Users\\user.name\\Desktop\\tunes.txt','r')
index=0
for line in f:
# Instantiate an empty Song object
s = Song()
if index == 0:
s.artist = line
index=index+1
elif index == 1:
s.song = line
index = index + 1
elif index == 2:
s.album = line
index = index + 1
elif index == 3:
s.genre = line
index = index+1
elif index == 4:
index = 0
songs_list.append(s)
Just started learning Python about two months ago, on and off. Still a beginner, but I come from a solid C background. I might not do things the "Python" way, as C is so heavily ingrained into me, but I got my script working. However, I just added a while loop so that I can run it multiple times and exit on user request. The while loop just exits no matter what the input, though. Pretty sure I have my indentation correct. Here's the whole script (with my API key removed). It's the very outside loop, the while finished == 0:
#!/usr/bin/env python3
import sys
import requests
import json
import time
appid = {'key': 'xxxxxxxxxxxxxxx'}
kingston = {'city': "/Canada/Kingston.json", 'city_str': "Kingston, Ontario"}
ottawa = {'city': "/Canada/Ottawa.json", 'city_str': "Ottawa, Ontario"}
toronto = {'city': "/Canada/Toronto.json", 'city_str': "Toronto, Ontario"}
vancouver = {'city': "/Canada/Vancouver.json", 'city_str': "Vancouver, British Columbia"}
sydney = {'city': "/Australia/Sydney.json", 'city_str': "Sydney, Australia"}
wellington = {'city': "/zmw:00000.1.93436.json", 'city_str': "Wellington, New Zealand"}
london = {'city': "/zmw:00000.1.03772.json", 'city_str': "London, UK"}
bergen = {'city': "/zmw:00000.1.01317.json", 'city_str': "Bergen, Norway"}
def cityquery(query):
searchresult = requests.get("http://autocomplete.wunderground.com/aq", params={'query': query})
results = json.loads(searchresult.text)
for index, x in enumerate(results['RESULTS'], start=1):
print(index, x['name'])
selection = input("Please select a number from the list:")
return {'city': results['RESULTS'][int(selection) - 1]['l'] + ".json", 'city_str': results['RESULTS'][int(selection) - 1]['name']}
def getWeather():
finished = 0
while finished == 0:
selected = 0
print("Please choose a city, or enter s to search by city name:")
print("\t1)", toronto['city_str'])
print("\t2)", sydney['city_str'])
print("\t3)", london['city_str'])
print("\t4)", vancouver['city_str'])
print("\t5)", ottawa['city_str'])
print("\t6)", kingston['city_str'])
print("\t7)", wellington['city_str'])
print("\t8)", bergen['city_str'])
while selected == 0:
citynumber = input("Enter a city number or s: ")
if citynumber == '1':
current_city = toronto
selected = 1
elif citynumber == '2':
current_city = sydney
selected = 1
elif citynumber == '3':
current_city = london
selected = 1
elif citynumber == '4':
current_city = vancouver
selected = 1
elif citynumber == '5':
current_city = ottawa
selected = 1
elif citynumber == '6':
current_city = kingston
selected = 1
elif citynumber == '7':
current_city = wellington
selected = 1
elif citynumber == '8':
current_city = bergen
selected = 1
elif citynumber == 's':
searchterm = input("Please type the first few characters of a city name: ")
current_city = cityquery(searchterm)
selected = 1
else:
print("Invalid entry!")
current_time = time.localtime()
print("The current time is", str('{:02d}'.format(current_time[3])) + ":" + str('{:02d}'.format(current_time[4])) + ":" + str('{:02d}'.format(current_time[5])))
print("Forecast for", current_city['city_str'])
#Current conditions
print("Getting current conditions...")
page = requests.get("http://api.wunderground.com/api/" + str(appid['key']) + "/conditions/q/" + current_city['city'])
values = json.loads(page.text)
# DEBUG print(page.text)
# DEBUG print(current_city)
temp = float(values['current_observation']['temp_c'])
if values['current_observation']['windchill_c'] == 'NA':
temp_wc = temp
else:
temp_wc = float(values['current_observation']['windchill_c'])
print("The temperature in", current_city['city_str'], "is currently", str('{:.2f}'.format(temp)) + "C feeling like", str('{:.2f}'.format(temp_wc)) + "C")
pressure_in = float(values['current_observation']['pressure_in'])
pressure_kp = float(values['current_observation']['pressure_mb']) / 10.0
print("The barometric pressure is", str('{:.2f}'.format(pressure_in)), "inches of mercury or", str('{:.1f}'.format(pressure_kp)), "kilopascals.")
wind_speed = float(values['current_observation']['wind_kph'])
wind_gust = float(values['current_observation']['wind_gust_kph'])
wind_dir = str(values['current_observation']['wind_dir'])
if wind_gust == 0:
print("The wind is", str('{:.2f}'.format(wind_speed)), "km/h from the", wind_dir)
else:
print("The wind is", str('{:.2f}'.format(wind_speed)), "km/h, gusting to", str('{:.2f}'.format(wind_gust)), "km/h from the", wind_dir)
#Forecast
print("Getting forecast...")
page = requests.get("http://api.wunderground.com/api/" + str(appid['key']) + "/forecast/q" + current_city['city'])
values = json.loads(page.text)
for x in [0, 1, 2, 3, 4, 5]:
print("Forecast for", values['forecast']['txt_forecast']['forecastday'][x]['title'], ":", values['forecast']['txt_forecast']['forecastday'][x]['fcttext_metric'])
waiting = 0 # loop until valid input
while waiting == 0:
exit = input("Press x to exit or c to check again...")
if exit == 'x' or 'X':
finished = 1
waiting = 1
elif exit == 'c' or 'C':
finished = 0
waiting = 1
else:
finished = 0
waiting = 0
if __name__ == "__main__":
getWeather()
There is an error in line 110 (if elif block inside while waiting). Correct statement would be:
if exit == 'x' or exit == 'X'
your statement reads if exit == 'x' or 'X' which is incorrect. It is comparing exit to x but not to X. What you want to write is if exit is equal to x or exit is equal to X but you have coded for either exit is equal to x or X is True. Now 'X' is always true and it is independent of your input (because you are not comparing it to any variable) and hence the loop exits irrespective of input. Same mistake is there in elif and else block.
This is very much like C