Home > database >  If user adds "m" or "h" to input, print "mins" or "hours"
If user adds "m" or "h" to input, print "mins" or "hours"

Time:05-13

I'm wanting to print "mins" if the user inputs a number with "m" after; and "hours" if user inputs number with "h" after.

My code:

import pyautogui
xtime = (input("Enter time (add: m for mins, or h for hrs): "))

if xtime   "m":
    print("mins")
elif xtime   "h":
    print("hours")

I don't know how to do this, I'm just guessing, could someone please help me? Thanks.

CodePudding user response:

The problem of your code is that what you're doing is adding a "m" if the string xtime is not null.

You should use str.endswith Python built-in function:

xtime = (input("Enter time (add: m for mins, or h for hrs): "))

if xtime.endswith('m'):
    print("mins")
elif xtime.endswith('h'):
    print("hours")

CodePudding user response:

You mean something like that:

user_entry = input("Enter time (add: m for mins, or h for hrs): ")

if user_entry == "m":
    print("mins")
elif user_entry == "h":
    print("hours")
else:
    print("Wrong entry, try again!")

Or:

user_entry = input("Enter time (add: m for mins, or h for hrs): ")

if user_entry.startswith("m"):
    print("mins")
elif user_entry.startswith("h"):
    print("hours")
else:
    print("Wrong entry, try again!")

Last edit:

user_entry = input("Enter time (add: m for mins, or h for hrs): ")

if user_entry.endswith("m"):
    print("mins")
elif user_entry.endswith("h"):
    print("hours")
else:
    print("Wrong entry, try again!")
  • Related