Customised data range - python-3.x

I'm new to python and looking for some help to create a function which allows the user to input a customized date range. I have printed my efforts thus far, but can't seem to get it working.
def customised_range():
'''Allows the user to create a customised date range'''
print("{:=^40}".format("Date Menu"))
start = input("Please enter a start date (DD-MM-YYYY): ")
base = date.datetime.strptime(start, "%02d-%02d-%04d")
if base > date.datetime.now():
print("Invalid input(Future Date entered)! Please try again.")
customised_range()
end_date = input("Please enter an end date (DD-MM-YYYY): "
end = data.datetime.strptime(end_date, "%02d-%02d-%04d")
if end > date.datetime.now() or end < base:
print("Invalid input, Please try again!")
customised_range()

Related

Python Error message for entering a number instead of a letter

I just started my programming education with python in school. One of the programs I started with simply asks you your name and then repeats it back to you. I'd like some help with getting an error message to show up if you put in a number rather than letters.
This is what I have:
while True:
name = input("What is your full name? ")
try:
n = str(name)
except ValueError:
print("Please enter your name in letters, not", repr(name))
continue
else:
break
print(name)
You can check the name if only contains letters by using string.isalpha()
in your case you name it n so n.isalpha() will return True or False
for more information:
How can I check if a string only contains letters in Python?

Time cannot be set in the past condition Python

What I need to do.
I need this program to not allow a user to input a date that's in the past. when I try it as it currently is i get the following error message. TypeError: '<' not supported between instances of 'datetime.datetime' and 'str'.
from datetime import datetime
from datetime import date
def addNewItems():
end = 4
while end == 4:
ToDoList = [ ]
Name = input("Enter the name of your task")
dateIn = input("Enter the task completion date. yyyy/mm/dd HH:MM:SS")
date = datetime.strptime(dateIn, "%Y/%m/%d %H:%M:%S")
now = datetime.now()
now_ = now.strftime("%d/%m/%Y %H:%M:%S")
if date < now_:
print("Time entered is in the past! Select options again")
continue
if Name in ToDoList:
print("Task already exists! Select options again")
continue
if date < now_ and Name not in ToDoList:
ToDoList.append(Name, date)
print("Task Added Sucessfully")
break
You actually need two datetime objects to use the < comparison directly.
You just need to compare date with now, intead of date with now_ in order to do what you want.
And just an advice. You're importing date from datetime library, so you should avoid creating variables with the same name if you intend calling the original date somewhere else in your code

How can I replace a line with user input?

I need to do this prompts in a function. Can someone please help me? I just don't understand how. I'm just a beginner.
This should be written in a function.
Prompt for two line numbers, one is the starting line of text to copy, and the second is the end line of the text to copy. Slice this part of the list, and add it to the end of the list as a single string.Check that the line numbers entered are valid. If they are invalid, ask for a line numbers again.
Prompt for a line number and then replace that line with a new one from the user. Check that the line number entered is valid. If it is invalid, ask for a line number again
Here's a skeleton to get you started. Use the input builtin function to get user input and check if they are valid in a while loop
def isValid(start, end):
# Check if your start and end numbers are value here
return start <= end
def getUserInput():
start = 0
end = -1
while True:
start = input("Enter starting line number: ")
end = input("Enter ending line number: ")
if not isValid(start, end):
print("Invalid input, try again")
else:
break
## Do what you want with the list here
return start, end

If statements with true or false in python 3.7.1 Tanner Short

my name is Tanner Short.
I'm a beginning developer, and have recently started to use python.
For a simple project I wanted to create a basic calculator, but I wanted to be creative and add some if statements and such. Here is my code.
name = input("Please enter your name: ")
age = input("Please enter your age: ")
Yes = True
No = False
print("Hello " + name + "!" " You are "+age+ " years old!" )
welcome_question = input("Would you like to go to the calculator? ")
if Yes:
print("Moving on..")
else:
print("Thank you for your time!")
So when I ran the file, it was supposed to ask for your name, age, then ask if you'd like to go to the calculator.
But the if statement isn't working. When I type Yes, it works, then when I type No, it outputs what was supposed to happen if you said yes.
Sorry if this made no sense! I a beginner and just need a little help. Thank you.
You are comparing the wrong values. What you want to do is, you want to compare user's input with Yes. If the user enters Yes then if should work, otherwise else should work.
So, basically, you need to compare welcome_question with "Yes" or "No". The Line 3 and 4 from your code are not required as per. And yes, your indentation is also broken.
name = input("Please enter your name: ")
age = input("Please enter your age: ")
print("Hello " + name + "!" " You are "+age+ " years old!" )
welcome_question = input("Would you like to go to the calculator? ")
if welcome_question == "Yes":
print("Moving on..")
else:
print("Thank you for your time!")
I hope it works. Cheers!

Python: String similar to everything

I need to use string (or int, bool, etc.) which will be same as everything. So this code:
user_input = input()
if user_input in *magic_string_same_as_everything*:
return True
should return True everythine, no matter what will user type into console.
Thanks for your help
Edit:
I see, that I've asked verry badly.
I'm trying to get 3 user input in this for cycle:
user_input = ["", "", ""] # Name, class, difficulty
allowed_input = ["", ["mage", "hunter"], ["e", "m", "h"]]
difficulty = {"e": 1, "m": 2, "h": 3}
message = ["Please enter your heroic name",
"Choose character (mage/hunter)",
"Tell me how difficult your journey should be? (e / m / h)"]
print("Welcome to Dungeons and Pythons\n" + 31 * "_")
for i in range(3):
while True:
print(message[i], end=": ")
user_input[i] = input()
if user_input[i] in allowed_input[i]:
break
Choose of name is without restrictions.
I hope, that now my question makes a sense.
You could just get rid of the if-statement and return True without the check or (if you really want to use the if-statement) you type if(True) and it will always be true.
You want True for non empty string?
Just use user_input as bool.
user_input = input()
if user_input:
return True
In your question Name is special case, just check it like this and for the rest of input you can use range(1,3).
Alternatively switch to using regular expressions
allowed_input = ["\A\S+", "\A(mage|hunter)\Z", "\A[emh]\Z"]
for i in range(3):
while True:
print(message[i], end=": ")
user_input[i] = input()
if re.match(allowed_input[i], user_input[i]) :
break
Initial response
This one liner should work.
If user inputs anything, it counts as an input & prints 'True', but if user just hits 'Enter' without typing anything, it returns 'No input'
print ("True" if input("Type something:") else 'No input')
After your edited question
To achieve what you want, you can define a function that checks for the user input values & corrects them if incorrect.
import re
# for user input, a single line of code is sufficient
# Below code takes 3 inputs from user and saves them as a list. Second and third inputs are converted to lowercase to allow case insensitivity
user_input = [str(input("Welcome to Dungeons & Pythons!\n\nPlease enter username: ")), str(input("Choose character (mage/hunter): ").lower()), str(input("Choose difficulty (e/m/h):").lower())]
print (user_input) # Optional check
def input_check(user_input):
if user_input[0] != '':
print ("Your username is: ", user_input[0])
else:
user_input[0] = str(input("No username entered, please enter a valid username: "))
if re.search('mage|hunter', user_input[1]):
print ("Your character is a : ", user_input[1])
else:
user_input[1] = str(input("Incorrect character entered, please enter a valid character (mage/hunter): ").lower())
if re.search('e|m|h',user_input[2]):
print ("You have selected difficulty level {}".format('easy' if user_input[2]=='e' else 'medium' if user_input[2]=='m' else 'hard'))
else:
user_input[2] = str(input("Incorrect difficulty level selected, please choose from 'e/m/h': "))
return (user_input)
check = input_check(user_input)
print (check) # Optional check
In each of the if-else statements, the function checks each element and if no input/ incorrect input (spelling mistakes, etc.) are found, it asks the user to correct them & finally returns the updated list.
Test Output
With correct entries
[Out]: Welcome to Dungeons & Pythons!
Please enter username: dfhj4
Choose character (mage/hunter): mage
Choose difficulty (e/m/h):h
['dfhj4', 'mage', 'h']
Your username is: dfhj4
Your character is a : mage
You have selected difficulty level hard
['dfhj4', 'mage', 'h']
With incorrect entries
[Out]: Welcome to Dungeons & Pythons!
Please enter username:
Choose character (mage/hunter): sniper
Choose difficulty (e/m/h):d
['', 'sniper', 'd']
No username entered, please enter a valid username: fhk3
Incorrect character entered, please enter a valid character (mage/hunter): Hunter
Incorrect difficulty level selected, please choose from 'e/m/h': m
['fhk3', 'hunter', 'm']

Resources