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.
Related
I am a python newbie and currently fiddling with it in various ways.
But I'm kind of stuck at creating an input with editable default value.
For example,
if you run input, there will be default value which you can change or leave it be.
Is it possible to create such input with standard library?
You can test whether the user has inputted anything then if they haven't replace it:
default_val = 'Default answer'
inp = input("Enter a string (default value is: '"+default_val+"'): ")
if not inp:
inp = default_val
print(inp)
This outputs:
Enter a string (default value is: 'Default answer'):
Default answer
or
Enter a string (default value is: 'Default answer'): Different answer
Different answer
default = 'spam'
user_input = input(f"Enter a string (default: {default}):") or default
print(user_input)
output:
Enter a string (default: spam): # user hit Enter
spam
Note, this assumes user input will never be empty string (i.e. empty string is not valid input for your use case).
Using input
default = "foo"
while default != "quit":
default = input(f"Enter a value ({default}): ")
Where you need to click enter each time, and quit by typing quit
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")
My question is this.
How do I make it so users can not make a new user_name John if JOHN or john are already in use.
Can I make user_name.upper() = user_name.lower() or something like that.
These names are been iterated through a loop of current_users. I want the loop to detect current users and disallow the use of a name if it has already been used in its upper() or title() forms.
Edit: If possible could I get the most 'pythonic' way of doing this. Thanks.
You can use a list comprehension if you do not need to loop through the current_users for anything else:
if user_name.lower() in [user.lower() for user in current_users]:
# user_name already taken
This would be the same as doing:
lower_current_users = list()
for user in current_users:
lower_current_users.append(user.lower())
if user_name.lower() in lower_current_users:
# user_name already taken
As you can see, a list comprehension requires fewer lines of code and is very useful for this type of thing.
Alternatively, a normal for loop can be used if you need to check more than one thing:
for user in current_users:
if user_name.lower() == user.lower():
# user_name already taken
You can use a lambda (a small anonymous little function) and make all your whole list lower case, and then compare that the the lower new_name. If it's new, add it, if not, don't.
name_list = ["John", "Sam", "Joe"]
new_name = "jOhN"
if new_name.lower() in [x.lower() for x in name_list]:
print("nope")
else:
print("new name, add it!")
name_list.append(new_name)
print (name_list)
for username in current_user_names:
if ip_username.lower() == username.lower():
Flag = 1
print ‘match found’
else:
Flag = 0
current_user_names.append(username)
Or simply just while you add your usernames add them in lower case.
your_userlist.append(username.lower())
And you can simply use the IN keyword to check
if current_user.lower() IN your_userlist:
Use the code below
existing_users = ["John","tilak","RAMESH","SidDDu"]
while True:
name = raw_input("Enter a name: ")
for i in existing_users:
if name.lower() == i.lower():
print "Name Already exists!Please choose another"
else:
existing_users.append(name)
so I'm a beginner in python and I was trying to get an input function to work. It looks to me like Python isn't taking the data I give it, like it's not reading user input correctly. here is my code:
var = input
input("press ENTER to choose an app")
if var==1:
clock()
elif var==2:
oshelp()
elif var==3:
ebooks()
elif var==4:
what_is_new()
else:
print("Application Not Found.")
right now, the IDLE just prints "Application Not Found" even when i type a valid number and I'm not sure why. can anyone help me with this? (please include examples). Thanks!
Your issue occurs on the first line
var = input
You are setting var equal to the function input, not the returning value.
How you have it, if you were to write x = var("Enter: "), this would do the same as x = input("Enter: ").
You actually need to do var = input("Enter: "), but this will return a value, of type string, so when you compare this value to 1, even if the user enters 1, it will return false, as they are different data types.
You can either cast the input to an integer value, or compare the inputted value to strings.
var = input("Enter: ")
if var == "1":
or
var = int(input("Enter: "))
if var == 1
I would personally use the top one, as the program wouldn't crash if entered a non-int value.
Hope this helps!
The input will be a string and not ints. You can change your conditions from checking var == 1 to var == "1" etc. Or you can create an int from the input, using int(input()). However beware of the case where the input is not convertible to an int in that case an exception will be thrown.
input returns a string, but you're checking it against ints. One way to do this would be to check the input, as explained here. You could also just compare it to strings:
if var == '1':
Or convert the input to an int directly:
var = int(input(...))
Be careful with the last one, as it will fail if the user does not input a valid int.
The python input returns a string and you are comparing ints. If you would like to compare ints, then:
inputInt = int(input("please ENTER"))
or you could use eval
inputInt = eval(input("please ENTER"))
be careful with eval as it can cause problems, but it will handle just numbers and floats for you.
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.