I have a programming homework assignment. Everything went smoothly until I reached a problem using Try/Except. If I type a valid datetime, the program will take it and it will move on, but if I use a valid datetime format, the exception won't react.
Here is my code:
import datetime
import csv
def get_stock_name(prompt,mode):
while True:
try:
return open(input(prompt) + ".csv")
except FileNotFoundError:
print("File not found. Please try again.")
except IOError:
print("There was an IOError opening the file. Please try again.")
def get_stock_date(prompt):
while True:
try:
return (input(prompt))
except TypeError:
print("Try again.")
except ValueError:
print("Try again.")
def get_stock_purchased(prompt):
while True:
try:
return (input(prompt))
except ValueError:
print("Try again.")
except TypeError:
print("try again.")
stock_name = get_stock_name("Enter the name of the file ==> ", "w")
stock_date = datetime.datetime.strptime(get_stock_date("Enter the stock purchase date ==> " , "%m/%d/%Y"))
stock_sold = datetime.datetime.strptime(get_stock_date("Enter the date you sold the stock ==>" , "%m/%d/%Y"))
stock_purchased = get_stock_purchased("How many stocks were purchased on start date ==>")
To clarify Tigerhawk's initial comment: in order for the try-catch to handle TypeError or ValueError, you need to cast the input to datetime in the try statement.
import datetime
def get_stock_date(prompt):
while True:
try:
return datetime.datetime.strptime(input(prompt), "%m/%d/%Y")
except (ValueError, TypeError):
print("Try again.")
stock_date = get_stock_date("Enter the stock purchase date ==> ")
Additionally, your initial post had strange indentation that made it look like you were making a recursive call to get_stock_date, which caused confusion.
Lastly, you will need to use raw_input if you're using Python 2.
You currently have a loop that will immediately end the function and return a string in any situation I can think of off the top of my head, exceptions that (as just mentioned) I don't think will happen, a call to strptime with the wrong number of arguments, and a recursive call to your function with the wrong number of arguments. And you never save or return a meaningful value. Maybe the recursive call just has wrong indentation? Anyway, you'll have to completely restructure your code, as most of it makes little sense:
import datetime
def get_stock_date(prompt):
while True:
d = input(prompt)
try:
d = datetime.datetime.strptime(d, "%m/%d/%Y")
except (ValueError, TypeError):
print("Try again.")
else:
return d
stock_date = get_stock_date("Enter the stock purchase date ==> ")
I think this is what you are looking for:
def get_stock_date(prompt):
try:
stock_date = datetime.datetime.strptime(prompt, "%m/%d/%Y")
return(stock_date)
except:
print("Try Again.")
prompt = input("Enter the stock purchase date ==> ")
get_stock_date(prompt)
get_stock_date(input("Enter the stock purchase date ==> " ))
Related
I have succesfully made a function that asks the user for a valid time by importing the module Datetime. If the user doesn't enter a valid time the question will be asked until he/she does.
But the problem is that im currently running a zoo, who has open between 08:00 - 22:00. How do I extend my code so the user only can enter a valid time between that timeperiod? Help would be appreciated.
Code:
def input_time():
while True:
try:
time = input("What time do you plan to be here? (HH:MM): ")
pattern_time = ('%H:%M')
time = datetime.strptime(time, pattern_time)
except ValueError:
print("Not a valid time,try again")
continue
else:
break
return time
time = input_time()
Sorry no one has answered this. The time_struct provides member fields that you can test:
while True:
try:
t = input("What time do you plan to be here? (HH:MM): ")
pattern_time = ('%H:%M')
t = time.strptime(t, pattern_time)
if not (8 <= t.tm_hour <= 22):
print("The zoo is only open from 8:00 to 22:00")
continue
except ValueError:
print("Not a valid time, try again")
continue
else:
break
return t
Also, be careful with variable names.
How can I optimize this code for large amount of input? Out of 5, 3 test case are failing because code is taking too long to execute.
n = int(input())
phonebook=dict([map(str,raw_input().split()) for x in range(n)])
while True:
try:
name = raw_input()
except EOFError as e:
break
if name not in phonebook.keys():
print("Not found")
else:
print(name +"="+phonebook[name])
You can turn the phonebook's keys into a set, sets are faster at lookup than lists
last 4 line in one
print(name +"="+phonebook[name]) if phonebook.get(name) else print("Not found")
This line is probably taking too much time:
if name not in phonebook.keys():
Because you are going over all the keys in the dictionary and compare it with input. You can use in keyword to check if a key exists directly without iterating over keys
n = int(input())
phonebook=dict([map(str,raw_input().split()) for x in range(n)])
while True:
try:
name = raw_input()
except EOFError as e:
break
if name not in phonebook:
print("Not found")
else:
print(name +"="+phonebook[name])
Or you can use exception handling on key error like so, it is better practice:
n = int(input())
phonebook=dict([map(str,raw_input().split()) for x in range(n)])
while True:
try:
name = raw_input()
print(name +"="+phonebook[name])
except EOFError as e:
break
except KeyError as e:
print ("Not found")
here is my code for retrieving the user input:
def inputQ1():
while True:
try:
Q1A = int(input("Rate your exercise today on scale 1-100: "))
except ValueError:
print("invalid value")
continue
else:
return Q1A
and my code for recording the input into a list:
ansQ1 = []
ansQ1.append(inputQ1())
print(ansQ1)
how do I now ask for this user input again, just once per day?
You can use datetime.datetime.now():
from datetime import datetime
def inputQ1():
while True:
try:
Q1A = int(input("Rate your exercise today on scale 1-100: "))
except ValueError:
print("invalid value")
continue
else:
return Q1A
dates = []
ansQ1 = []
while True:
today = datetime.now().strftime("%Y-%m-%d")
if today not in dates:
ansQ1.append(inputQ1())
dates.append(today)
print(ansQ1)
Where datetime.now().strftime("%Y-%m-%d") returns the current date in the from of 2020-05-21.
One thing to note, it isn't a very good practice to rely on try - except to convert an input into an int. Instead, use the str.isdigit() method:
def inputQ1():
while True:
Q1A = input("Rate your exercise today on scale 1-100: ")
if Q1A.isdigit():
return int(Q1A)
print("invalid value")
Hi guys I was working on a shoppinglist-creator code but at the end I faced with a surprise.
My code:
import time
import math
import random
dict_of_lists={}
def addlist():
while True:
try:
listname=str(raw_input("=>Name of the list:\n"))
dict_of_lists[listname]={}
break
except ValueError:
print "=>Please enter a valid name.\n"
print "=>You added a new list named %s.\n" % (listname)
def printlists():
for lists in dict_of_lists:
return "-"+lists
def addproduct():
while True:
try:
reachlistname=input("=>Name of the list you want to add a product,Available lists are these:\n %s \nPlease enter one:\n" % (printlists()))
break
except ValueError:
print "=>Please enter a valid list name.\n"
while True:
try:
productname=raw_input("=>Name of the product:\n")
break
except ValueError:
print "=>Please enter a valid name.\n"
while True:
try:
productprice=input("=>Price of the product:\n")
if isinstance(float(productprice),float):
break
except ValueError:
print "=>Please enter a valid number.\n"
while True:
try:
productcount=input("=>Amount of the product:\n")
if isinstance(int(productcount),int):
break
except ValueError:
print "=>Please enter a valid number.\n"
dict_of_lists[reachlistname][productname]={"price":productprice,"count":productcount}
dict_of_lists[reachlistname]={productname:{"price":productprice,"count":productcount}}
allevents="1-Add a list"+" 2-Add a product to a list"
def eventtochoose():
while True:
try:
event=raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
if not isinstance(int(event),int):
print "\n=>Please enter a number.\n"
else:
if event==1:
addlist()
break
elif event==2:
addproduct()
break
except ValueError:
print "\n=>Please enter a valid input.\n "
while True:
print "%s" % ("\n"*100)
eventtochoose()
So, the problem is (I suggest you run the code) it says "=>What would you like to do? Here are the all things you can do:
1-Add a list 2-Add a product to a list
Please enter the number before the thing you want to do:" and when i put an answer it simply doesn't call the fucntion.
If I put 1 It should have called the fucntion addlist but I think it doesn't. There is nothing to explain I think just look at the code and find the problem if you want to help crocodiles. Thx
When you do int(event), that returns an int if possible, and raises a ValueError if not. So, testing the type of the result doesn't do you any good—if your code gets that far, the type has to be an int.
You already have code to handle the ValueError, so you don't need any other test for the same problem.
Meanwhile, you want to start the number that you got from int(event). That's the thing that can be == 1; the original string '1' will never be == 1.
So:
while True:
try:
event=raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
event = int(event)
if event==1:
addlist()
break
elif event==2:
addproduct()
break
except ValueError:
print "\n=>Please enter a valid input.\n "
You are not converting your input to an integer before comparing, so the comparisons are always false:
'1' == 1 # false
Try:
event = raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
try:
event = int(event)
if event == 1:
addlist()
elif event == 2:
addproduct()
break
except ValueError:
print('Please enter a valid input')
I would like to have the user input a date, something like:
date = input('Date (m/dd/yyyy): ')
and then make sure that the input is a valid date. I don't really care that much about the date format.
Thanks for any input.
You can use the time module's strptime() function:
import time
date = input('Date (mm/dd/yyyy): ')
try:
valid_date = time.strptime(date, '%m/%d/%Y')
except ValueError:
print('Invalid date!')
Note that in Python 2.x you'll need to use raw_input instead of input.
def validDate(y, m, d):
Result = True
try:
d = datetime.date(int(y), int(m), int(d))
except ValueError, e:
Result = False
return Result
and in the program use the function defined previously:
if not validDate(year_file, month_file, day_file):
return 0
Max S.,
Thanks for the code. Here is how I implemented it:
while True:
date = input('Date (m/dd/yyyy): ')
try:
date = time.strptime(date, '%m/%d/%Y')
break
except ValueError:
print('Invalid date!')
continue