I'm new to python and I was trying to create an error handling for multiple users input. I made the code as the following.
`
#load and filter dataset
import pandas as pd
CITY_DATA = {'Chicago' : 'chicago.csv',
'New York City':'new_york_city.csv',
'Washington':'washington.csv'}
#filtering dataset
def get_filters ():
city_options = ['Chicago','New York City','Washington'.title()]
month_options = ['January','February','March','April','May','June','July','August','September','November','December','all'.title()]
day_options = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday','all']
while True:
city = input('\nInsert name of the city to analyze! (Chicago, New York City, Washington)\n'.title())
if city in city_options :
break
else:
print('Your choice is not available. Please try again')
while True:
month = input('\nInsert month to filter by or "all" to apply no month filter! (January, February, etc.)\n'.title())
if month in month_options :
break
else:
print('Your choice is not available. Please try again')
while True:
day = input('\nInsert day of the week to filter by or "all" to apply no day filter! (Monday, Tuesday, etc.)\n'.title())
if day in day_options :
break
else:
print('Your choice is not available. Please try again')
return city, month, day
But I believe there is a simpler way for this or maybe create a function? Any help would be greatly appreciated!
You can use the try/except statements and loop once for all of three inputs instead of looping again and again. Here is what I came up with. If it doesn't help, happy to delete it.
def get_filters():
city_options, month_options, day_options = ['Chicago','New York City','Washington'.title()], ['January','February','March','April','May','June','July','August','September','November','December','all'.title()], ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday','all'.title()]
while True:
try:
city = city_options.index(input('\nInsert name of the city to analyze! (Chicago, New York City, Washington)\n'.title()))
month = month_options.index(input('\nInsert month to filter by or "all" to apply no month filter! (January, February, etc.)\n'.title()))
day = day_options.index(input('\nInsert day of the week to filter by or "all" to apply no day filter! (Monday, Tuesday, etc.)\n'.title()))
return city_options[city], month_options[month], day_options[day]
except ValueError:
print ("Your previous choice is not available. Please try again")
print (get_filters())
A little refactored version of your solution. Not sure whether this is of huge help.
def get_valid_input(input_msg, options):
while True:
entered_value = input(input_msg)
if entered_value in options:
break
else:
print('Your choice is not available. Please try again')
continue
def get_filters():
city_options = ['Chicago', 'New York City', 'Washington'.title()]
month_options = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'November',
'December', 'all'.title()]
day_options = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'all']
city_input_msg = 'Insert name of the city to analyze! (Chicago, New York City, Washington): '
get_valid_input(city_input_msg, city_options)
month_input_msg = 'Insert month to filter by or "all" to apply no month filter! (January, February, etc.): '
get_valid_input(month_input_msg, month_options)
day_input_msg = 'Insert day of the week to filter by or "all" to apply no day filter! (Monday, Tuesday, etc.): '
get_valid_input(day_input_msg, day_options)
return city, month, day
Related
I am trying to run the following code:
import time
import pandas as pd
import numpy as np
CITY_DATA = {'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv'}
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
while True:
city = input('Which city you would like to explore : "chicago" , "new york city" , or "washington" :' )
if city not in ('chicago', 'new york city', 'washington'):
print(" You entered wrong choice , please try again")
continue
else:
break
# get user input for month (all, january, february, ... , june)
while True:
month = input('Enter "all" for all data or chose a month : "january" , "february" , "march", "april" , "may" or "june " :')
if month not in ("all", "january", "february", "march", "april", "may", "june"):
print(" You entered wrong choice , please try again")
continue
else:
break
# get user input for day of week (all, monday, tuesday, ... sunday)
while True:
day = input('Enter "all" for all days or chose a day : "saturday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday": ')
if day not in ("all","saturday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday"):
print(" You entered wrong choice , please try again")
continue
else:
break
print('-'*60)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df = pd.read_csv(CITY_DATA[city])
# convert the Start Time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# extract month , day of week , and hour from Start Time to new columns
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.day_name
df['hour'] = df['Start Time'].dt.hour
# filter by month if applicable
if month != 'all':
# use the index of the month_list to get the corresponding int
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
# filter by month to create the new dataframe
df = df[df['month'] == month]
# filter by day of week if applicable
if day != 'all':
# filter by day of week to create the new dataframe
df = df[df['day_of_week'] == day.title()]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# display the most common month
popular_month = df['month'].mode()[0]
print('\n The most popular month is : \n', popular_month)
# display the most common day of week
popular_day = df['day_of_week'].mode()[0]
print('\n The most popular day of the week is : \n', str(popular_day))
# display the most common start hour
popular_hour = df['hour'].mode()[0]
print('\n The most popular hour of the day is :\n ', popular_hour)
print("\nThis took %s seconds.\n" % (time.time() - start_time))
print('-'*60)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# display most commonly used start station
start_station = df['Start Station'].value_counts().idxmax()
print('\n The most commonly used start station is : \n', start_station)
# display most commonly used end station
end_station = df['End Station'].value_counts().idxmax()
print('\nThe most commonly used end station is: \n', end_station)
# display most frequent combination of start station and end station trip
combination = df.groupby(['Start Station','End Station']).value_counts().idxmax()
print('\nThe most frequent combination of start station and end station are: \n', combination)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
start_time = time.time()
travel_time = sum(df['Trip Duration'])
print('Total travel time:', travel_time / 86400, " Days")
# display total travel time
total_time = sum(df['Trip Duration'])
print('\nThe total travel time is {} seconds: \n', total_time)
# display mean travel time
mean_time = df['Trip Duration'].mean()
print('\n The average travel time is \n', mean_time)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# TO DO: Display counts of user types
user_types = df['User Type'].value_counts()
#print(user_types)
print('User Types:\n', user_types)
# TO DO: Display counts of gender
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
and I am receiving the following errors , can someone assist please
the errors:
> Traceback (most recent call last):
File "C:\Users\DELL\PycharmProjects\Professional\venv\Lib\site-packages\pandas\core\indexes\range.py", line 391, in get_loc
return self._range.index(new_key)
^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: 0 is not in range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\DELL\PycharmProjects\Professional\Bikeshare.py", line 203, in <module>
main()
File "C:\Users\DELL\PycharmProjects\Professional\Bikeshare.py", line 192, in main
time_stats(df)
File "C:\Users\DELL\PycharmProjects\Professional\Bikeshare.py", line 100, in time_stats
popular_month = df['month'].mode()[0]
~~~~~~~~~~~~~~~~~~^^^
File "C:\Users\DELL\PycharmProjects\Professional\venv\Lib\site-packages\pandas\core\series.py", line 981, in __getitem__
Calculating The Most Frequent Times of Travel...
return self._get_value(key)
^^^^^^^^^^^^^^^^^^^^
File "C:\Users\DELL\PycharmProjects\Professional\venv\Lib\site-packages\pandas\core\series.py", line 1089, in _get_value
loc = self.index.get_loc(label)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\DELL\PycharmProjects\Professional\venv\Lib\site-packages\pandas\core\indexes\range.py", line 393, in get_loc
raise KeyError(key) from err
KeyError: 0
I am expecting to filter pandas DataFrame to return month, day of week, and hour to perform some statistics.
KeyError means that the key isn't valid, because it doesn't exist. In this case, one reason to get KeyError when trying to get first mode is when column 'month' in dataframe is empty, and therefore mode() returns an empty collection, so you get KeyError: 0 when trying to get its first element.
To avoid this, you could replace:
popular_month = df['month'].mode()[0]
With:
try:
# try to get first mode of column 'month'
popular_month = df['month'].mode()[0]
except KeyError:
# if there's no data on column 'month'
popular_month = "unknown"
Because if there's no data on 'month' column, there's no point in trying to get its mode.
More about handling exceptions: https://docs.python.org/3/tutorial/errors.html#handling-exceptions
Also when I tried to ( not use the filters) by choosing " all " in the second and 3rd input, I get the following result:
Calculating The Most Frequent Times of Travel...
The most popular month is :
6
The most popular day of the week is :
<bound method PandasDelegate._add_delegate_accessors.._create_delegator_method..f of <pandas.core.indexes.accessors.DatetimeProperties object at 0x0000022B7CD5E890>>
The most popular hour of the day is :
17
This took 0.0260775089263916 seconds.
Calculating The Most Popular Stations and Trip...
The most commonly used start station is :
Streeter Dr & Grand Ave
The most commonly used end station is:
Streeter Dr & Grand Ave
The most frequent combination of start station and end station are:
('2112 W Peterson Ave', '2112 W Peterson Ave', 1064651, Timestamp('2017-06-02 07:59:13'), '2017-06-02 08:25:42', 1589, 'Subscriber', 'Female', 1963.0, 6, <bound method PandasDelegate._add_delegate_accessors.._create_delegator_method..f of <pandas.core.indexes.accessors.DatetimeProperties object at 0x0000022B7CD5E890>>, 7)
This took 2.1254045963287354 seconds.
Total travel time: 3250.8308680555556 Days
The total travel time is {} seconds:
280871787
The average travel time is
936.23929
This took 0.06502270698547363 seconds.
Calculating User Stats...
User Types:
Subscriber 238889
Customer 61110
Dependent 1
Name: User Type, dtype: int64
This took 0.022009611129760742 seconds.
Would you like to restart? Enter yes or no.
Right now I am working on a file where it lets you customise a password. Each section lets you choose between a name, number, and more with a certain amount of sections. I can't figure out how to place the code that generates each section in the num_of_pass for loop without repeating the text
'What would you like in section #' + str(current_section) + '? (name, number, letter, symbol, year, day, month) '
each time it gives a new password. How could I make this work?
names = ['Tim', 'Alex', 'Thomas', 'Katrina', 'Joshua', 'James', 'John', 'Emily', 'Mary', 'Patricia', 'Jennifer',
'Linda', 'Elizabeth', 'Robert', 'Michael', 'William', 'David', 'Richard', 'Ashley', 'Damon', 'Max']
options = ['name', 'number', 'letter', 'symbol', 'year', 'day', 'month']
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
sections = input('How many sections would you like? ')
num_of_pass = input('How many passwords would you like? ')
current_section = 1
for num in range(int(sections)):
section_type = input('What would you like in section #' + str(current_section) + '? (name, number, letter, symbol, year, day, month) ')
if section_type == 'name':
section = random.choice(names)
elif section_type == 'number':
section = str(random.randint(1, 9))
elif section_type == 'letter':
section = random.choice(string.ascii_letters)
elif section_type == 'symbol':
section = str(random.choice(string.punctuation))
elif section_type == 'year':
section = str(random.randint(1000, 2020))
elif section_type == 'day':
section = random.choice(days)
elif section_type == 'month':
section = random.choice(months)
password = password + section
current_section += 1
print(password)
password = ''
I think you can simply put the input statement outside of the loop, or there's a work around it - put it in a condition:
for num in range(int(sections)):
if count == 0:
section_type = input('What would you like in section #' + str(current_section) + '? (name, number, letter, symbol, year, day, month) ')
count += 1
if section_type == 'name':
section = random.choice(names)
Why give this error while writing to csv file ???
When I user csv.writer at that time code run perfectly but can not get header give me some suggestion and solution for this
AttributeError: 'list' object has no attribute 'keys'
import random
import csv
BloodGroup = ['A+', 'A-', 'B+', 'B-', 'O+', 'O-', 'AB+', 'AB-']
City = ['Ahmedabad', 'Gandhinagar', 'Vadodara', 'Rajkot', 'Surat']
Month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
ForWhat = ['anemia','cancer','hemophilia','kidney disease','liver disease','severe infection','sickle cell disease','thrombocytopenia']
bloodgroup = random.choice(BloodGroup)
city = random.choice(City)
if city == 'Ahmedabad':
area = random.choice(['Gota', 'Maninagar', 'Bopal', 'Satellite', 'Bodakdev', 'Thaltej', 'Chandkheda', 'Prahlad Nagar', 'SG Highway'])
elif city == 'Gandhinagar':
area = random.choice(['Sargaasan', 'Urjanagar', 'Kudasan', 'Zundal', 'Raysan', 'Shantigram'])
elif city == 'Vadodara':
area = random.choice(['Alkapuri', 'Akota', 'Fatehgunj', 'Waghodia'])
elif city == 'Rajkot':
area = random.choice(['Mota Mava', 'Kalawad', 'Bhakti Nagar', 'Madhapar'])
else:
area = random.choice(['Sayan', 'Ghod Dod', 'Pal', 'Vesu'])
bloodquantity = random.randint(0,4)
month = random.choice(Month)
year = random.randint(2015, 2019)
forwhat = random.choice(ForWhat)
personcount = random.randint(0,10)
print(f'{bloodgroup} {city} {area} {bloodquantity} {month} {year} {forwhat} {personcount}')
data = [bloodgroup, city, area, bloodquantity, month, year, forwhat, personcount]
print('Data:',data)
with open('BloodBankDataSet.csv', 'w') as new_file:
fieldname = ['Bloodgroup', 'City', 'Area', 'Bloodquantity', 'Month', 'Year', 'ForWhat', 'PersonCount']
csv_writer = csv.DictWriter(new_file, fieldnames= fieldname)
csv_writer.writeheader()
csv_writer.writerow(data)
DictWriter expects a dictionary as the parameter and you're passing a list.
Consider using this:
csv_writer.writerow({k: v for k,v in zip(fieldname, data)})
I want to run this code but I have some errors and I can't see the problem. The code is below. And do I have to set global list for cities, month and the day?
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
cities = ('Chicago', 'New York', 'Washington')
while True:
city = input('Which of these cities do you want to explore : Chicago, New York or Washington? \n> ').lower()
if city in cities:
break
# get user input for month (all, january, february, ... , june)
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = get_user_input('Now you have to enter a month to get some months result) \n> ', months)
# get user input for day of week (all, monday, tuesday, ... sunday)
days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' ]
day = get_user_input('Now you have to enter a month to get some months result) \n> ', days)
print('-'*40)
return city, month, day
If I understood you correctly I think this is what you have to do:
CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
cities = ('Chicago', 'New York', 'Washington')
while True:
city = input('Which of these cities do you want to explore : Chicago, New York or Washington? \n> ').capitalize() #was lower()
if city in cities:
break
# get user input for month (all, january, february, ... , june)
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = input('Now you have to enter a month to get some months result \n> {} \n> '.format(months))
# get user input for day of week (all, monday, tuesday, ... sunday)
days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
day = input('Now you have to enter a dau to get some days result \n> {} \n> '.format(days))
print('-'*40)
if month == '' and day == '':
return city, months, days
elif month == '' and day != '':
return city, months, day
elif month != '' and day == '':
return city, month, days
else:
return city, month, day
city, month, day = get_filters()
print(city, month, day)
A couple of things to note:
The input of the city was set to '.lower()' while the list of cities contained capitilized letters. So I changed it to capitilize().
Also you wanted it to return every day and month if the user didn't specify any input. Therefore I added a simple if-test at the end to check for that. Furthermore I used the '-format()' to display the different options the user has on the input. Hope everything is clear!
Using .lower() is fine, but you should change your cities list and your `CITY_DATA`` dict to match the names (so New York City --: new york).
CITY_DATA = { 'chicago': 'chicago.csv', 'new york': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
cities = ('chicago', 'new york', 'washington')
while True:
city = raw_input('Which of these cities do you want to explore : Chicago, New York or Washington? \n> ').lower()
if city in cities:
break
# get user input for month (all, january, february, ... , june)
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = raw_input('Now you have to enter a month to get some months result \n> {} \n>'.format(months)).lower()
# get user input for day of week (all, monday, tuesday, ... sunday)
days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
day = raw_input('Now you have to enter a day to get some days result \n> {} \n>'.format(days)).lower()
print('-'*40)
if month == '' and day == '':
return city, months, days
elif month == '' and day != '':
return city, months, day
elif month != '' and day == '':
return city, month, days
else:
return city, month, day
city, month, day = get_filters()
print(city, month, day)
If you are using Python 2.7, you should use raw_input() instead of input().
I have started leaning python programming.I am making the project given to me. when ever i give input it says invalid option. i am not able to solve the problem .i don't know were i am going wrong. i have tried every thing that i know. please help !
my output
python bikeshare.py
Hello! Let's explore some US bikeshare data!
Please enter the number of which city you would like to explore:
1 Chicago, 2 New York City, 3 Washington
1
Invalid choice...
Please enter the number of which city you would like to explore:
1 Chicago, 2 New York City, 3 Washington
thank you for the help
import time
import pandas as pd
import numpy as np
CHICAGO = 'Chicago'
NYC = 'New York City'
WASHINGTON = 'Washington'
CITY_DATA = { CHICAGO: 'chicago.csv',
NYC: 'new_york_city.csv',
WASHINGTON: 'washington.csv' }
DAYS_OF_WEEK = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday']
MONTHS_OF_YEAR = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December']
HOURS = [
'12 AM'
'1 AM',
'2 AM',
'3 AM',
'4 AM',
'5 AM',
'6 AM',
'7 AM',
'8 AM',
'9 AM',
'10 AM',
'11 AM',
'12 PM',
'1 PM',
'2 PM',
'3 PM',
'4 PM',
'5 PM',
'6 PM',
'7 PM',
'8 PM',
'9 PM',
'10 PM',
'11 PM'
]
MINUTE_SEC = 60
HOUR_SEC = 60 * MINUTE_SEC
DAY_SEC = 24 * HOUR_SEC
WEEK_SEC = 7 * DAY_SEC
# print(CITY_DATA)
START_TIME = 'Start Time'
END_TIME = 'End Time'
BIRTH_YEAR = 'Birth Year'
START_STATION = 'Start Station'
END_STATION = 'End Station'
TRIP_DURATION = 'Trip Duration'
GENDER = 'Gender'
# Added columns
START_MONTH = 'Start Month'
START_DAY_OF_WEEK = 'Start Day of Week'
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(int) month - name of the month to filter by, or "all" to apply no month filter
(int) day - name of the day of week to filter by, or "all" to apply no day filter
"""
invalid_choice = "Invalid choice..."
ALL = 'all'
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
while True:
print("Please enter the number of which city you would like to explore: ")
print("1 Chicago, 2 New York City, 3 Washington")
location = input(">")
if location == '1':
city = CHICAGO
print("You chose Chicago")
break
elif location == '2':
city = NYC
print("You chose New York City")
break
elif location == '3':
city = WASHINGTON
print("You chose Washington")
break
else:
print(invalid_choice)
while True:
get_city = input('\nHello! Let\'s explore some US bikeshare data!\n'
'Would you like to see data for Chicago, New York, or Washington?\n')
if get_city.lower() in ('chicago', 'new york', 'washington'):
if get_city.lower() == 'chicago':
city_filename = chicago
elif get_city.lower() == 'new york':
city_filename = new_york_city
elif get_city.lower() == 'washington':
city_filename = washington
break
print('Enter a valid city name provided in the options')
while True:
print("Please enter the number of the (start) month you would like to explore or \"{}\": ".format(ALL))
print("1 January ... 6 June")
m = input(">")
if m == ALL:
month = None
break
try:
month = int(m)
except ValueError:
print(invalid_choice)
continue
else:
if month >= 1 and month<=6:
print("You chose " + MONTHS_OF_YEAR[month-1])
break
elif month <= 12:
print("Only January to June are in this dataset")
print(invalid_choice)
continue
else:
print(invalid_choice)
continue
# get user input for day of week (all, monday, tuesday, ... sunday)
while True:
print("Please enter the number of the (start) day of the week that you would like to explore or \"{}\": ".format(ALL))
print("1 Monday ... 7 Sunday")
d = input("> ")
if d == ALL:
day = None
break
try:
day = int(d)
except ValueError:
print(invalid_choice)
continue
else:
if day >= 1 and day<=7:
day -= 1
print("You chose " + DAYS_OF_WEEK[day])
break
else:
print(invalid_choice)
continue
print_divider()
return city, month, day
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df, month is None, day is None)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
trip_length_time_of_day_correlation(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
print("Bye!")
break
if __name__ == "__main__":
main()
The code worked with me... How are you running it?
Your comparison is looking for the number as a string. If you use the standard input (eg, running in a terminal), then it will read it in as a string. But, if you pass in an integer somehow, then it won't match.
neil~$ python stack.py
Hello! Let's explore some US bikeshare data!
Please enter the number of which city you would like to explore:
1 Chicago, 2 New York City, 3 Washington
1
You chose Chicago
Hello! Let's explore some US bikeshare data!
Would you like to see data for Chicago, New York, or Washington?