How do I capitalize input? - python

The following code, is the one I want it to be capitalized. Meaning once the user inputs their answer to the licence plate, I want it to be outputted in capitals:
ask2 = ""
plate = ""
if int(ask) == 1:
stop = False
time.sleep(0.5)
print("========================================================================")
while not stop:
ask2 = input("Please enter it in such form (XX00XXX): ").lower()
valid = re.compile("[a-z][a-z]\d\d[a-z][a-z][a-z]\Z")
# b will start and end the program, meaning no more than 3-4 letters will be used.
# The code which tells the user to enter the right format (keeps looping)
# User can exit the loop by typing 'exit'
# This is the default exit_message
exit_message = "Verification Failed!"
while (not valid.match(ask2)) and (ask2 != 'exit'):
time.sleep(0.5)
print("========================================================================\n", exit_message,
sep="")
print("You can exit the validation by typing 'exit'.")
time.sleep(0.5)
print("========================================================================")
time.sleep(0.5)
ask2 = input("Or stick to the rules, and enter it in such form (XX00XXX): ").lower()
if ask2 == 'exit':
exit_message = "Verification Stopped!"
stop = True
break
I already have constructed a code to make it capitalized, this is it; however I have no idea where to put it:
var = input("no caps: ")
def isvalid(s):
for i in s:
if i in "ABC...XYZ":
return False
return True
while not isvalid(var):
def isvalid(s):
for i in s:
if i in "ABC...XYZ":
return False
return True
Thank you for the help.

Simply use the upper() method.
>>> "hello".upper()
'HELLO'

Related

Is it possible for me to check if something is printed to the terminal

I'm making hangman, and I want to check that if "Yay you solved the puzzle" is printed then the function returns ""
def hangman(word):
tries = 8
user = ""
for i in range(tries):
user_input = input("Guess the word?:" )
if user_input in word:
user += user_input
if user == word:
print("Yay, you solved the puzzle")
break
else:
print("Thats correct, keep going")
tries += 1
elif user_input not in word:
print("Oops that's wrong")
#Here I want to check whether "Yay, you solved the puzzle" is printed, then subsequently return ""
print(hangman("salsa"))
Why not just do an empty return after user == word:
def hangman(word):
tries = 8
user = ""
for i in range(tries):
user_input = input("Guess the word?:" )
if user_input in word:
user += user_input
if user == word:
print("Yay, you solved the puzzle")
return
else:
print("Thats correct, keep going")
tries += 1
elif user_input not in word:
print("Oops that's wrong")
I will leave this answer up as it solves OP's question about wanting a way to return if if user == word is satisfied, but it is definitely worth noting the discussion in the comments which points out that returning None will probably cause issues later on and returning True would be better

How to send a break statement from a function to a while loop?

I am trying to repeatedly ask the user to enter a string. If that string is "bye", the program should return "Bye" and terminate.
I can't figure out how to have the decide function tell the while loop that it's time to terminate.
def decide(greeting):
if greeting == "hi":
return "Hello"
elif greeting == "bye":
return "Bye"
x = input("Insert here: ")
while True:
print(decide(x))
x = input("Insert here: ")
EDIT: People in the comments are saying to use a conditional in the while loop for checking the returned value. I cannot do that because in reality the returned value "Bye" is stored in a local variable. Those two functions are inside a class in reality and I'd prefer to keep the while loop short on conditionals.
You can try this:
def decide(greeting):
if greeting == "hi":
return "Hello"
elif greeting == "bye":
return "Bye"
x = input("Insert here: ")
while True:
n = (decide(x))
print(n)
if(n == "Bye"):
break
x = input("Insert here: ")
You can do your printing in your function and check its output in the while loop:
def decide(greeting):
if greeting == "bye":
print("Bye")
return False # only break on "bye";
elif greeting == "hi":
print("Hello")
return True
while True:
x = input("Insert here: ")
if not decide(x):
break
EDIT based on clarified question (no printing inside your function). Your function can have more than one output, for example:
def decide(greeting):
if greeting == "bye":
return "Bye", False # return reply and status;
elif greeting == "hi":
return "Hello", True
else:
return greeting, True # default case;
while True:
x = input("Insert here: ")
reply, status = decide(x)
print(reply)
if not status:
break

How can i check if an inputted variable either starts with "Q" or it is a number

I am new so plz help. i am writting a program that adds numbers. it asks for input and until "Q" is inputed it keeps asking for input
def add_num(vari = "" , total = 0):
vari = input("Enter a num or press \"Q\" to stop: ")
while (vari.startswith("Q") and int(vari).isdigit() ) == False:
print("Error")
vari = input("plz enter again: ")
else:
print("Nice")
there are no indentation error. The problem i have is how can i check if it starts with "Q" or it is a number. I think this is the code that has errors
while (vari.startswith("Q") and int(vari).isdigit() ) == False:
vari.isdigit() is enough to check that all characters are digits.
You have a logic error in the while condition: it cannot be that vari.startswith("Q") and at the same time vari.isdigit(), so that would be always false, and comparing that to False would always be true.
Change it to while (vari.startswith("Q") or vari.isdigit()) == False:

How do I display my user's errors?

My user wants to make a password and I'm supposed to be checking if it's valid or not. So far, I have down the code to check if it is valid/not valid. Now, the next step (after determining it is not valid) is to tell the user it is not valid AND why their password is not a valid option.
while True:
pw = input('Enter password to be tested if valid or not: ')
correct_length = False
uc_letter = False
lc_letter = False
no_blanks = True
first_letter = False
if len(pw) >= 8:
correct_length = True
for ch in pw:
if ch.isupper():
uc_letter = True
if ch.islower():
lc_letter = True
if pw.isalnum():
digit = True
if pw[:1].isalpha():
first_letter = True
if not pw.find(' '):
no_blanks = True
if correct_length and uc_letter and lc_letter and digit and first_letter and no_blanks:
valid_pw = True
print('Your password to be tested is valid.')
else:
valid_pw = False
print('Your password to be tested is not valid because:')
print(----------)
#This is the part where I'm suppose to display the errors if the user gets it wrong.
#Initially, in the test for ch. above, I put in an else: with a print statement but because of the for- statement, it prints it out for every single character.
answer = input('Try another password input? y/n ')
if answer == 'y':
answer = True
else:
break
Hm.. I think you can simply put the extra else statement, then raise an error:
if not pw.find(' '):
no_blanks = True
else:
raise ValueError('Invalid input!')
And similarly with your other conditionals.
If you want your loop to keep going, you can just print the message, and then continue:
else:
print("Invalid input! Please re enter it:")
continue
Hope this helps!
You check for all valid conditions. The correct approach is, instead of checking for the condition to be true like this,
if len(pw) >= 8:
correct_length = True
check for
if len(pw) < 8:
correct_length = False
print "Password not lengthy"
This will help identify the error. basically, find what all evaluate to false, so that the user could be pointed out those errors.

Python condition not applying (if/elif)

I have a problem with a condition in my python code.
It's a mathematics application, and here's the part of the code that is not working well:
def askNumber():
"""Asks the number to test"""
a=raw_input("Select the number to test (type 'exit' for leaving):")
if len(a)!=0 and a.lower!="exit":
try:
b= int(a)
processing(b)
except ValueError:
print "Your input is not valid. Please enter a 'number'!"
time.sleep(1)
askNumber()
elif len(a)!=0 and a.lower=="exit":
answer()
else:
print "Your input can't be 'empty'"
time.sleep(1)
askNumber()
So, when in the raw_input for "a" I type "exit", the supposed condition to apply is the elif one but ends up applying the if one, ending up printing "Your input is not valid. Please enter a 'number'!" Sorry, if it's something obvious, I'm a begginer, although I tried to find the mistake several times.
You need to call the .lower() function.
if len(a) != 0 and a.lower() != "exit":
# ...
elif len(a) != 0 and a.lower() == "exit":
There is no real need to test for len(a)!=0, simply test for a itself:
if a and a.lower() != "exit":
# ...
elif a and a.lower() == "exit":
Empty strings evaluate to False in a boolean context.
Your program flow is a bit inside out, may I suggest some improvements?
def askNumber():
"""Asks the number to test"""
while True:
a = raw_input("Select the number to test (type 'exit' for leaving):")
if not a:
print "Your input can't be 'empty'"
continue
if a.lower() == "exit":
answer()
break
try:
b = int(a)
except ValueError:
print "Your input is not valid. Please enter a 'number'!"
continue
processing(b)
Actually, the not a branch can be eliminated as well (empty inputs will be handled in except).
You could change the condition for the following one:
if a and a.lower() !="exit":
# .....
elif a and a.lower() == "exit":
answer()
elif a and not a.isdigit(): print "invalid input"
else:
#.............
Please note that yo don't need len(a) != 0 , just by using a will evaluate if it's empty or not.

Categories