Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've started to learn python only a day ago, seems to be easy, but still have some questions :)
how to write a script which have to check necessary input of raw_input?
I mean, the script must stop if a user have not entered any case and just hit enter on raw_input...
ans = raw_input('Enter: ')
if not ans:
print "You entered nothing!"
else:
print "You entered something!"
If the user hits enter, ans will be ''. and '' is considered False, thus as the condition is True (not False), the if block will run.
If you wish to continually ask the user for an input, you can use a while-loop:
ans = ''
while not ans: # While the input given is an empty string
ans = raw_input('Enter: ')
raw_input() return empty string ('') if user just hit enter.
If the prompt argument is present, it is written to standard output
without a trailing newline. The function then reads a line from input,
converts it to a string (stripping a trailing newline), and returns
that. When EOF is read, EOFError is raised.
if raw_input() == '':
break # or return
if not raw_input():
break # or return
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
Sorry, this is probably obvious to veterans out there but I simply want to print ("Please only write in lowercase") if there are any uppercase letter in the inputted string
i've done:
if string.islower == false
print ("Please only write in lowercase")
But is shows an error :/
File "main.py", line 14
if phrase.islower() == False
^
SyntaxError: invalid syntax
Thank you
Check out the built in string function str.islower()
Edit: You're so close! You actually unintentionally referenced the actual function. Just execute it. :) Also, you were missing the manditory : colon after your conditional.
if not phrase.islower():
print("Please only write in lowercase")
If your goal is to stop the execution of a program while running a script/program you can also check this way:
#with throwing an exception during the execution of a script:
_input = 'This is Your input'
if not _input.islower():
raise Exception('Program Execution Stopped! Please write in lower case only!')
Just in case, be aware that you can create your own Exception like this:
_input = 'This is Your input'
class UpperCaseException(Exception):
pass
if not _input.islower():
raise UpperCaseException('Program Execution Stopped! Please write in lower case only!')
In Python, islower() is a built-in method used for string handling.
The islower() methods returns “True” if all characters in the string are lowercase, Otherwise, It returns “False”.
My guess is that you should just force lowercase vice checking for an error.
.lower()
that said if you want to check if the input is lower
var = raw_input("Please write in only lowercase : ")
if var.islower() :
print("yup that is lowercase")
else :
print("That is not lowercase")
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
How can we store the output of 'type' function in a variable ?
next = raw_input('> ')
type = type(next)
if type == 'int':
val = int(next)
else:
print "Type a number!"
Syntax Error at line 4....?
There are several ways of doing what you want. Note that defining a type variable to mask the type function is not good practice! (and next either BTW :))
n = raw_input('> ') # (or input in python 3)
try:
val = int(n)
except ValueError:
print("Type a number!")
or
n = raw_input('> ') # (or input in python 3)
if n.isdigit():
val = int(n)
else:
print("Type a number!")
Note: as some comment indicated, that in python 2, it was possible to get what you wanted by just using
n = input("> ")
but very ill adviced since you have to control what n is really, not python 3 portable, and has huge security issues:
Ex: in python 2 on windows, try that:
import os
n = input("> ")
and type os.system("notepad")
you'll get a nice notepad windows !! You see that it is really not recommended to use input (imagine I type os.system("del <root of your system>")) ...
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So whilst programming part of my homework, I decided to include validation within my program. However whilst adding in validation using the .isalpha() command, when having a sentence with letters in it, I get the error message for when typing in numbers. Sorry, cant display all of my program but i have included a test bed of code I programmed to test whether the .isalpha() command works, for validating whether only alphabetic letters are entered. Test data entered = one of several testing examples
word = input("enter a word")
if word.isalpha():
print("Word accepted")
else:
print("Invalid letters only")
If you enter more than one word, there are non-alpha characters in your input (spaces in the case of the input "testing example one of several"). Those cause isalpha to fail.
Also, your error message is misleading - a single non-alpha character is enough to trigger the error, not "invalid letters only".
In [1]: "Hello".isalpha()
Out[1]: True
In [2]: "Hello Hello".isalpha()
Out[2]: False
In [3]: "Lotsoflettersandonedigit1".isalpha()
Out[3]: False
If you want to allow spaces in your input as well (but no punctuation or digits or other non-letter characters), you could do
if all(s.isalpha() for s in word.split()):
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Its been a while since I've written code, so I'm trying to get back into it again, but I'm having trouble with some of my code.
I wanted to write a simple program that takes a user's input and checks to see if it is all letters with no spaces, and has a length less than 12. I keep getting an "Invalid syntax" error on line 17 whenever I run the code, pointing to the colon after the if statement that checks if the username is just letters and less than 12 characters. I know that means there's an error on the line before that, but where?
#import the os module
import os
#Declare Message
print "Welcome to Userspace - Your One-Stop Destination to Greatness!" + "\n" + "Please enter your username below." \
+ "\n" + "\n" + "Username must be at least 12 characters long, with no spaces or symbols." + "\n" + "\n"
#uinput stands for user's input
uinput = raw_input("Enter a Username: ")
#check_valid checks to see if arguement meets requirements
def check_valid(usrnameinput):
if (usrnameinput != usrnameinput.isalpha()) or (len(usrnameinput) >= 12):
os.system('cls')
print "Invalid Username"
return False
else:
os.system('cls')
print "Welcome, %s!" % (usrnameinput)
return True
#Asks for username and checks if its valid
print uinput
check_valid(uinput)
#Checks input to check_valid is correct, and if it is not, then ask for new username input and checks it again
while check_valid(uinput):
return True
break
else:
print uinput
check_valid(uinput)
print "We hope you enjoy your stay here at Userspace!"
UPDATE - I played around with the code a little bit more, and the only thing I changed was the while conditional to an if:
print uinput
check_valid(uinput)
#Checks input to check_valid is correct, and if it is not, then ask for new username input and checks it again
if check_valid(uinput):
print uinput
check_valid(uinput)
print "We hope you enjoy your stay here at Userspace!"
I ran this code, but got this error instead:
File "Refresher In Python.py", line 39
return True
SyntaxError: 'return' outside function
Sorry for being such a noob. Also just joined Stack Overflow today.
I believe this is what you want. I suggest splitting it into two functions, your check_valid() and a general main() function.
def check_valid(usrnameinput):
if (not usrnameinput.isalpha()) or (len(usrnameinput) >= 12):
print("Invalid name")
return False
else:
print("Welcome!")
return True
def main():
uinput = raw_input("Enter a Username: ")
while not check_valid(uinput): #Repeatedly asks user for name.
uinput = raw_input("Enter a Username: ")
main()
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to figure out how I can catch empty user input using a try and except.
If you had this for example:
try:
#user input here. integer input
except ValueError:
#print statement saying empty string.
Although I also need to catch another value error to make sure they entered an integer and not a character or string how could I use an if and elif setup in order to figure out if it is an empty string or str instead of int
If you literally want to raise an exception only on the empty string, you'll need to do that manually:
try:
user_input = input() # raw_input in Python 2.x
if not user_input:
raise ValueError('empty string')
except ValueError as e:
print(e)
But that "integer input" part of the comment makes me think what you really want is to raise an exception on anything other than an integer, including but not limited to the empty string.
If so, open up your interactive interpreter and see what happens when you type things like int('2'), int('abc'), int(''), etc., and the answer should be pretty obvious.
But then how do you distinguish an empty string from something different? Simple: Just do the user_input = input() before the try, and check whether user_input is empty within the except. (You put if statements inside except handlers all the time in real code, e.g., to distinguish an OSError with an EINTR errno from one with a different errno.)
try:
input = raw_input('input: ')
if int(input):
......
except ValueError:
if not input:
raise ValueError('empty string')
else:
raise ValueError('not int')
try this, both empty string and non-int can be detected. Next time, be specific of the question.