There's an issue with Input in my Python code - python

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.

Related

Is it possible to create an input with an editable default value?

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

check the user input type using python and streamlit

I want to check the user input if its numeric or string.
The problem is that the if statement always take the user input as string even if the input is numeric its converted by default into a string.
How to fix this problem ?
all_columns = df.columns.tolist()
st_input_update = st.number_input if is_numeric_dtype(all_columns) else st.text_input
with col1_search:
regular_search_term=st_input_update("Enter Search Term")
The argument to is_numeric_dtype() should either be a type or a pandas array. You gave it a list of column names, which is neither.
Use df.dtypes to get an array of datatypes.
st_input_update = st.number_input if is_numeric_dtype(df.dtypes) else st.text_input
user_input = input("Enter something:")
try:
x = int(user_input)
print("Is a number")
except ValueError:
print("That's not an int!")

User input into a string Python 2.7

I'm trying to enter user input into a string in two places in python 2.7.12
I want it to look something like this
import os
1 = input()
2 = input()
print os.listdir("/home/test/1/2")
I know you can use .format() to input into string but the only way I know how to do it is
print os.listdir("/home/test/{0}".format(1))
but I couldn't figure out how to enter a second input into the string.
sorry for any confusion, I'm kinda new to Stack Overflow. If you have any questions please ask.
import os
segment1 = input()
segment2 = input()
print os.listdir("/home/test/{}/{}".format(segment1, segment2))
1 and 2 are not legal variable names, so 1 = input() will cause an error.
You can use as many variables as you want in your format string; just pass them as additional parameters to .format(...). In the format string, you can use {0}, {1}, etc., or you can just use {} positionally. (The first {} refers to the first parameter, the second {} to the second parameter, etc.).

What am I doing wrong here? Try and Except in 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.

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