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
Related
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 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.
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.).
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.
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