What am I doing wrong here? Try and Except in Python - python

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.

Related

Checking input for the whole exact string in a list

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()

Simple Python 3 email/password storage

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.

How to compare input and list content (and handle wrong inputs)

This piece of code will ask for input, compare input with content of lists and, if input and content match, return input.
If input is not in list user will be asked again for input.
def get_input(tested_list):
corect_input = False
while not corect_input:
try:
# we are comparing input to list of lists content
my_input = str.lower((input("Enter here: ")))
for line in a_list:
if my_input == line[2].lower():
return my_input
except ValueError:
print("????")
else:
corect_input = False
Now questions (I'm very beginner. Try-Except-Else is all very new for me) :
Is there any reason here to include 'except' line? Since input is converted to string, I can't see way to input anything what will cause any error.
What kind of error shall I use after 'except'.
How shall I write this piece of code to be better / cleaner/ more pythonic? :) .
thank you
First issue to note is that a_list in your function should be replaced by tested_list. a_list has not been defined and will cause an error.
There are at least 2 possible errors you can face:
AttributeError, if the 2nd index of a sublist in tested_list is not a string, e.g. if it is an integer.
IndexError, if the 2nd index of a sublist in tested_list does not exist, e.g. if the sublist is of length 2.
However, to make your try / except clause useful in this context, you need to define it within the for loop. Below is an example.
def get_input(tested_list):
correct_input = False
while not correct_input:
my_input = str.lower((input("Enter here: ")))
for line in tested_list:
try:
if my_input == line[2].lower():
return my_input
except (AttributeError, IndexError):
print("An error has occurred")
else:
correct_input = False

There's an issue with Input in my Python code

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.

Check the type of user input against known type

I have a situation.
I am using wx.textctrl where user needs only to enter a number (positive integers only).
I want to check what the user has entered .
If he has entered a string , i want to do something like this:
if type(user_input) == str:
# do something
Or
if type(user_input) != int:
# do something
Actual program looks like
ROW = self.Rownum.GetValue()
I want to check the type of this ROW against string or integer.
Or best will be , if I can force the textctrl box only to accept integers within a range
suppose 1 to 10000 for example.
wxPython has Validators for this sort of thing. See http://wiki.wxpython.org/Validator%20for%20Object%20Attributes or wx.TextCtrl and wx.Validator
You could try parsing the user input and then except any errors that turn up.
try:
user_input = int(user_input)
except ValueError:
pass
if type(user_input) == str:
do something

Categories