I insert 'Sharon' as my input but it still keeps printing "Not in alphabets". What should I do to print("In alphabets") while my input is in alphabets?
While the statement of the while loop is satisfied, the code in the while loop keeps running.
With your code is like you are saying to the computer:
While the name variable value is not equal to the Boolean value True, if name is composed of alphabet elements, or is not equal to the Boolean value False, if name is not composed of alphabet elements, keep printing "Not in alphabets".
As you can understand, a strings variable value can never be equal to a Boolean value, thus the while loop never ends.
You need an if else, not a while.
if name.isalpha() != False:
print( "Not in alphabets")
else:
print("In alphabets")
ALSO: Post written code inside ` and not as image!
Perhaps you want to do this? I
name = input("Enter your name")
if name.isalpha():
print("All chars are alphabetic")
else:
print("Not all charts are alphabetic")
Related
So I'm creating a simple program to check the input for words contained in the list. I have something like this...
def function():
list = ["hell", "yeah"]
check_input = input("Sentence to check: ")
check_input.split()
check = any(item in check_input for item in list)
if check is True:
print("List word found!")
else:
print("Clean!")
The problem is I want it to check the input for the exact same string from the list. Not if the input contains just a part of it.
Basically: I want it so if the user types "hello world" into the input, check would return as false and print clean because "hello" isn't "hell".
I guess I need to use something different than any() function, but I can't come up with anything that would solve this.
Any ideas?
Your code is slightly wrong due to which it is not working correctly.
Replace check_input.split() with check_input=check_input.split()
Or use check_input = input("Sentence to check: ").split()
This would probably be my first code and I'm so happy that I applied the knowledge I obtained from watching youtube videos and It does make sense to me why and how they work!
However, I want to make the program below a little more complex. Currently the program asks the user to make a choice, and then to enter a related username or email. E.g. if the choice was 1, it'd ask for the "Main Email", and then it prints the password for that email/user account.
But I have a problem: I don't know how to check if the email/username is correct. The program should only print the password if a correct email is provided. And I'd also like it to not require the numerical choice, but only ask for the email, and from that decide what password is the email for.
I was thinking of doing if-else statements but I can only do them with integers and floats? Or else I'm just not researching enough, so here I am asking first.
print ("Select the password you would wanna know from the email")
print ("1. Main Email")
print ("2. Your steam account steam guard")
while True:
choice = input ("Enter your choice (1/2/): ")
if choice in ("1",):
email1 = input("Enter your password in your main email: ")
if choice in ("2"):
email2 = input("Enter your steamguard: ")
if choice == "1":
print( "The password is *myemailpassword*")
if choice == "2":
print ("Your steam guard password is *steamguardpassword*")
I was thinking of doing if else statements but I can only do them with integers and floats?
Not at all. If statements actually take anything that is truthy or falsy, not only ints nor floats, and you can use the comparison operator == to compare two strings, the result being True if they are equal in value, and otherwise False.
In your code, you're already using the in operator to work with tuples, so even in your own code you don't believe the statement about if working only on integers and floats! The in operator works - in your case - on a (string, list) pair of arguments, and the == operator works - in your case - on a (string, string) pair.
You're not using integers nor floats anywhere in your code!
"1" is not an integer. It's a string that contains a decimal numeral. Thus, "1" + "2" results in "12", not 3, and "1" + 2 throws TypeError: can only concatenate str (not "int") to str. With actual integers, 1 + 2 is 3 (note: no quotes!).
What you perhaps want can be written as:
passwords = {
"email1#example.com": ["email password", "password1"],
"email2#example.com": ["steamguard password", "password2"]
}
print("Empty input ends the program.")
while True:
choice = input("Enter email or username: ").strip()
if not choice:
break
if choice in passwords:
what, password = passwords[choice]
print("Your", what, "is", password)
else:
print("Invalid entry. Try again.")
print("Goodbye.")
I've used a dictionary to hold the data - this is called data-driven design. It helps decouple the code from the data it operates on. It's easy to think of the passwords as a "table" or "dictionary" where you look things up!
The string.strip() method removes any leading and trailing whitespace in the string.
The not operator treats its argument as either falsy or truthy. In Python, many non-boolean expressions can be falsy - e.g. the integer 0, the boolean False, or an empty string "". Thus, not choice means "when choice is falsy", or, here: "when choice is empty".
The "double" assignment what, password = ... is a destructuring assignment: it takes whatever's on the right side of =, breaks it up into two parts, and assigns the first part to what, and the second part to password. That way the ["what", "password"] list looked up in the dictionary has its structure removed, and its contents extracted into named variables.
So I'm writing a program (A sort of "custom if statement") that checks if your input is true or false. This is the script I have right now:
v=line[3:] # Remove "if " from the line, so you only have the question and the consequence
i=v.split(': ') # Make a list with the first item being the question and the second item being the consequence.
for r in i:
if r==i[1]: # Check which item in the list is the question and which is the consequence
c=r
question=i[0]
consequences=c.split(' | ')
for x in consequences:
self.consequences+=f'\n{x}' # Create a variable with all of the consequences, each in one line
Answer=False # reate the Answer variable with the default value False
def checkVal(question):
global Answer
if question:
b=open('if.BaRT','w+')
b.write(self.consequences)
b.close()
self.run('if.BaRT')
os.remove('if.BaRT')
else:
pass # Check if the question is true or false
if Answer==True:
print("True!")
else:
print("False!") # Finally check if the question is true or not and if it is, print "True!" and if it's not, print "False!"
I'm expecting this to work, but then when i input something that's true, for example: __name__=="__main__", so my input looks like this:
if __name__=="__main__": print("Hello!")
this is the output:
False!
How do I fix this so it prints it accurately?
Edit: consequences added
I have replaced your exec with eval to get rid of your global variable (still not good coding practise, but if this is what you need...). Also, the for is not needed.
PS: the variables i, v and c should have better names.
line='if __name__=="__main__": print("Hello!")'
v=line[3:] # Remove "if " from the line, so you only have the question and the consequence
i=v.split(': ') # Make a list with the first item being the question and the second item being the consequence.
c=i[1]
question=i[0]
consequences=c.split(' | ')
_consequences=''
for x in consequences:
_consequences+=f'\n{x}'
Answer=eval(f"{question}") # Check if the question is true or false
if Answer==True:
exec( _consequences)
print("True!")
else:
print("False!") # Finally check if the question is true or not and if it is, print "True!" and if it's not, print "False!"
Please read my code for better understanding of my question. I'm creating a to do list in python. In the while loop where there's try and except, I want to set the user input type as string. And if the user types in an integer I want to print out the message in the "except" block. But it doesn't execute the ValueError if the I type in an integer when I run the code.
Here's the code:
to_do_list = []
print("""
Hello! Welcome to your notes app.
Type 'SHOW' to show your list so far
Type 'DONE' when you'v finished your to do list
""")
#let user show their list
def show_list():
print("Here is your list so far: {}. Continue adding below!".format(", ".join(to_do_list)))
#append new items to the list
def add_to_list(user_input):
to_do_list.append(user_input)
print("Added {} to the list. {} items so far".format(user_input.upper(), len(to_do_list)))
#display the list
def display_list():
print("Here's your list: {}".format(to_do_list))
print("Enter items to your list below")
while True:
#HERE'S WHERE THE PROBLEM IS!
#check if input is valid
try:
user_input = str(input(">"))
except ValueError:
print("Strings only!")
else:
#if user wants to show list
if user_input == "SHOW":
show_list()
continue
#if user wants to end the list
elif user_input == "DONE":
new_input = input("Are you sure you want to quit? y/n ")
if new_input == "y":
break
else:
continue
#append items to the list
add_to_list(user_input)
display_list()
input returns a string. See the docs for the input function. Casting the result of this function to a string won't do anything.
You could use isdecimal to check if the string is a numeric.
if user_input.isdecimal():
print("Strings only!")
This would fit in nicely with your existing else clause.
Two problems with your assumptions:
Calling str on an integer will not raise a ValueError because every integer can be represented as a string.
Everything coming back from input (on Python 3 anyway, which it looks like you're using) is already a string. Casting a string to a string will definitely not throw an error.
You might want to use isdigit if you want to throw out all-numeric input.
There seems to be some confusion in the comments over the word 'all-numeric'. I mean a string that is entirely composed of numbers, which was my interpretation of the OP not wanting "integers" on his to-do list. If you want to throw out some broader class of stringified numbers (signed integers, floats, scientific notation), isdigit is not the method for you. :)
In Python, input always returns a string. For example:
>>> input('>')
>4
'4'
So str won't throw a ValueError in this case--it's already a string.
If you really want to check and make sure the user didn't enter just numbers you probably want to check to see if your input is all digits, and then error out.
Here's my code:
def add_goose_group():
goose_group_name = input('Insert the name of the raft ')
goose_group_name = str(goose_group_name)
if goose_group_name.isdigit() == False and (' ' in goose_group_name) == False:
return goose_group_name
else:
add_goose_group()
First if criterion checks if the input has only numbers in it, the second one checks if there are any spaces in it. When I try this code, then it checks correctly if the input falls into these criterions or not but in the return part of the code(atleast i think that's where the problem is) gives back nothing. When another function adds goose_group_name to the dictionary's key position, it prints out None.
Why does it not save the input taken from the user and put it into the key position?
A recursive call works like any other function call: you call add_goose_group to handle the case where the input was invalid, but then you don't actually do anything with the result. You reach the end of the current function call (the fact that the function you're currently in is also add_goose_group does not matter here), and implicitly return None, just like any other time you reach the end of a function in Python without explicitly returning.
However, you should not be using recursion for this - do a loop instead.
Why does it not save the input taken from the user and put it into the key position?
Where exactly do you have an object that would store this input?
Perhaps you need something like this:
def add_goose_group():
while True:
goose_group_name = input('Insert the name of the raft ')
goose_group_name = str(goose_group_name)
if goose_group_name.isdigit() == False and (' ' in goose_group_name) == False:
return goose_group_name
dct = {}
dct['user_input'] = add_goose_group()
print(dct) # outputs {"user_input": "name of inputted raft"}
add_goose_group() will loop forever until the user enters valid input (not a digit, and no spaces), and save this input into your dct object.