Using enter in an if statement - python-3.x

Again = str(input("\nPlay again?\n"))
if Again == "yes" or Again == "Yes":
In this code I want to add the enter button as another input possibility but I am unsure of how to accomplish this.

You should check for an empty string, see code below:
Again = str(input("\nPlay again?\n"))
if Again == "yes" or Again == "Yes" or Again == '':
and you could also do something like that which will provide flexibility:
Again = str(input("\nPlay again?\n"))
possible_values = {'y','yes',''}
if Again.lower() in possible_values:
Behind the scene here is what happens when you're using input:
If the prompt argument is present, it is written to standard output
without a trailing newline. The function then reads a line from input,
converts it to a string (stripping a trailing newline), and returns
that.
So when a user will only press enter, it will result in an empty string which we can compare using this ''.

Related

How do I change the key to confirm/submit the input() function?

I am making a typeracer sort of game as a final assignment for school and I want to have it so that every time the user presses "space" the input() function would be submitted.
For example, if I were to regularly use the input() function I would need to press "enter" for the input to submit. However, I want it so that if I were to press space instead of enter the function would still submit.
If anyone knows a way around this please help.
I used the getch module to do this.
def takeInput():
word = ''
userInp = ''
# this loop ends when the user presses space indicating a new word
while userInp != " ":
if userInp == backSpace(): # I created a whole new backspace function for this
word = word[:-1]
print('\r' + ' '*25)
print('\033[F\r'+ word, end="") # goes up one line then proceeds
else:
word += userInp
word = word.strip()
userInp = g.getche()
# erases final output
print("\r", end="")
sys.stdout.write("\033[K")
return word
With the getch module you can use getch.getche() to act as the input function. You save the users input to a variable until they press whichever key you want then save that elsewhere. So eg,
while inp != 'd':
inp = getch.getche() # this displays the input
btw, getch is not in the standard library so do 'pip install getch' into the console to use it.

handling string input without ' '

Trying to print after string as input incorrectly e.g. without quotations ''
while True:
t=eval(input("number "))
if isinstance(t, str):
print("bad")
if TypeError: #trying to detect strings not input in ' ' format
print("bad")
the expected result would be to print "bad" when 'string' or string is input in the console.
However, when inputing a string without quotations my code breaks. Not sure how to detect for inputs without quotations.
It appears that you want to consume a number from command line and you are trying to check if instead you received a string.
eval() will evaluate its arguments as if it was some recognized python code, simply speaking. See documentation. If you pass string, eval is trying to evaluate string, which isn't really python code. So, an error is thrown. If you pass 'string', eval believes it is a quoted string.
What you probably need is this:
while True:
t = input("number ")
try:
my_value = int(t)
except:
if t == 'quit':
break
else:
print('I didnt receive a string. Please try again');
continue
print('Great! Received a number')
That way, you ask for information from the user. You will get a string. Then, you try to convert it to an integer. If that fails, you can check if the user provided quit. If so, stop the program. If not, tell the user you got a string and you want a number.
If you got a number, great, you can proceed further.

Python: String similar to everything

I need to use string (or int, bool, etc.) which will be same as everything. So this code:
user_input = input()
if user_input in *magic_string_same_as_everything*:
return True
should return True everythine, no matter what will user type into console.
Thanks for your help
Edit:
I see, that I've asked verry badly.
I'm trying to get 3 user input in this for cycle:
user_input = ["", "", ""] # Name, class, difficulty
allowed_input = ["", ["mage", "hunter"], ["e", "m", "h"]]
difficulty = {"e": 1, "m": 2, "h": 3}
message = ["Please enter your heroic name",
"Choose character (mage/hunter)",
"Tell me how difficult your journey should be? (e / m / h)"]
print("Welcome to Dungeons and Pythons\n" + 31 * "_")
for i in range(3):
while True:
print(message[i], end=": ")
user_input[i] = input()
if user_input[i] in allowed_input[i]:
break
Choose of name is without restrictions.
I hope, that now my question makes a sense.
You could just get rid of the if-statement and return True without the check or (if you really want to use the if-statement) you type if(True) and it will always be true.
You want True for non empty string?
Just use user_input as bool.
user_input = input()
if user_input:
return True
In your question Name is special case, just check it like this and for the rest of input you can use range(1,3).
Alternatively switch to using regular expressions
allowed_input = ["\A\S+", "\A(mage|hunter)\Z", "\A[emh]\Z"]
for i in range(3):
while True:
print(message[i], end=": ")
user_input[i] = input()
if re.match(allowed_input[i], user_input[i]) :
break
Initial response
This one liner should work.
If user inputs anything, it counts as an input & prints 'True', but if user just hits 'Enter' without typing anything, it returns 'No input'
print ("True" if input("Type something:") else 'No input')
After your edited question
To achieve what you want, you can define a function that checks for the user input values & corrects them if incorrect.
import re
# for user input, a single line of code is sufficient
# Below code takes 3 inputs from user and saves them as a list. Second and third inputs are converted to lowercase to allow case insensitivity
user_input = [str(input("Welcome to Dungeons & Pythons!\n\nPlease enter username: ")), str(input("Choose character (mage/hunter): ").lower()), str(input("Choose difficulty (e/m/h):").lower())]
print (user_input) # Optional check
def input_check(user_input):
if user_input[0] != '':
print ("Your username is: ", user_input[0])
else:
user_input[0] = str(input("No username entered, please enter a valid username: "))
if re.search('mage|hunter', user_input[1]):
print ("Your character is a : ", user_input[1])
else:
user_input[1] = str(input("Incorrect character entered, please enter a valid character (mage/hunter): ").lower())
if re.search('e|m|h',user_input[2]):
print ("You have selected difficulty level {}".format('easy' if user_input[2]=='e' else 'medium' if user_input[2]=='m' else 'hard'))
else:
user_input[2] = str(input("Incorrect difficulty level selected, please choose from 'e/m/h': "))
return (user_input)
check = input_check(user_input)
print (check) # Optional check
In each of the if-else statements, the function checks each element and if no input/ incorrect input (spelling mistakes, etc.) are found, it asks the user to correct them & finally returns the updated list.
Test Output
With correct entries
[Out]: Welcome to Dungeons & Pythons!
Please enter username: dfhj4
Choose character (mage/hunter): mage
Choose difficulty (e/m/h):h
['dfhj4', 'mage', 'h']
Your username is: dfhj4
Your character is a : mage
You have selected difficulty level hard
['dfhj4', 'mage', 'h']
With incorrect entries
[Out]: Welcome to Dungeons & Pythons!
Please enter username:
Choose character (mage/hunter): sniper
Choose difficulty (e/m/h):d
['', 'sniper', 'd']
No username entered, please enter a valid username: fhk3
Incorrect character entered, please enter a valid character (mage/hunter): Hunter
Incorrect difficulty level selected, please choose from 'e/m/h': m
['fhk3', 'hunter', 'm']

Ask for input, stops asking when enter is pressed, then displays an alphabetically sorted list, print each item separately on a diff line

Challenge:
Need to write a program that asks the user to enter some data, for instance the names of their friends. When the user wants to stop providing inputs, he just presses Enter. The program then displays an alphabetically sorted list of the data items entered. Do not just print the list, but print each item separately, on a different line.
y = []
def alfabetisch( element ):
return element
while True:
user_input = input("Prompt: ")
if user_input != "":
y += [user_input]
if user_input == "":
break
for element in y:
y.sort( key= alfabetisch )
print( element )
I've made some changes and it works 'sometimes' now. If I put in the following input at the 'prompt:'
[Great, Amazing, Super, Sweet, Nice] it gives back: [Great, Great, Nice, Super, Sweet] so that is two times 'Great' and leaves out 'Amazing'
But when I give in the following input at the 'prompt:' [Amorf, Bread, Crest, Draft, Edith, Flood] it gives back: [Amorf, Bread, Crest, Draft, Edith, Flood], so with this particular input it does what I wanted it to do.
What am I doing wrong here, can anyone provide some pointers?
The input of a user is a string.
If the user doesn't input anything the output of input() function is '' ( as mentioned in the comments).
If the user inputs more than one item, as you mentioned for instance a list of friend names then iterating over the string will give you all the chars that compose that string.
A more Pythonic way of doing that will be:
user_input = input("Prompt: ")
print('\n'.join(sorted(user_input.split())))

running a while loop in python and functions not defined

Hi I have this code below and I want the while loop to keep on getting an input from the user whenever the user enters an empty value or doesn't input any value, the program should keep on prompting the user to enter at least a single character, but the code seems to run even though I don't enter any value, thus an empty string the code still executes the (function) in the code, and also I get error "Function not defined"
word = ""
while True:
if word != "":
def str_analysis(string):
if string.isdigit():
if int(string) > 99:
print (string,"Is a big number")
else:
print(string,"Small number")
elif string.isalpha():
print(string,"Is all alphabetical characters")
else:
print(string,"is multiple character types")
word = input ("Enter a word or integer:")
break
str_analysis(word)
I don't know what you expect to happen. word is equal to "" so the if block won't run, so the function won't get defined. Next, we ask the user for input and after that break the loop. Then you try and call a function that was never defined.
What you wanna do is put a break at the end of the function and get rid of the existing one.

Resources