handling string input without ' ' - python-3.x

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.

Related

How to filter out numbers from an inputted User Name

I am trying to get the user to enter the Name (of their choice) of a building, but the name cannot include any digits from 0 to 9 that's the only restriction. If they include a digit, the program simply tells them the entry is invalid and that they must try again. My issue is I don't think I'm using the loop correctly so it still accepts invalid answers
Here is what I've written:
buildName = (input('Enter the building name: '))
for char in buildName:
if char.isdigit():
break
print('Invalid Entry')
buildName = input('Re-Enter the building name: ')
building.setBuildName(buildName)
I feel like this should be working. But, I am stuck.
To be more specific on the output validity, entries like "C-Building" should work while "123C-Building" should not
The main problem with your code is the break; because of it you are getting out of your loop so the rest of your code is not executed. To fix the problem you could make a new string that will only accepts non-digits. So your "if" would append the non-digits to the new list. By doing That you don't need to ask the user for a new entry because you filtered it form him

How to fix Python dict.get() returns default value after returning key value?

When i try to input e.g. "help move" this code prints the corresponding help message to "move" and the default value. But if I understand dict.get(key[, value]) right, the default value should only come up if the key (e.g. "run" instead of "move") is not in the dictionary.
I've tried to check if my key is a string and has no whitespace. Don't know what / how to check else.
#!/usr/bin/env python3
def show_help(*args):
if not args:
print('This is a simple help text.')
else:
a = args[0][0]
str_move = 'This is special help text.'
help_cmd = {"movement" : str_move, "move" : str_move,
"go" : str_move}
#print(a) # print out the exact string
#print(type(a)) # to make sure "a" is a string (<class 'str'>)
print(help_cmd.get(a), 'Sorry, I cannot help you.')
commands = {"help" : show_help, "h" : show_help}
cmd = input("> ").lower().split(" ") # here comes a small parser for user input
try:
if len(cmd) > 1:
commands[cmd[0]](cmd[1:])
else:
commands[cmd[0]]()
except KeyError:
print("Command unkown.")
I excpect the ouput This is a special help text. if I enter help move, but the actual output is This is special help text. Sorry, I cannot help you with "move"..
The crux of the issue is in this line:
print(help_cmd.get(a), 'Sorry, I cannot help you with "{}".'.format(a))
Your default is outside of the call to get, so it is not acting as a default and is being concatenated. For it to be a default, revise to:
print(help_cmd.get(a, 'Sorry, I cannot help you with "{}".'.format(a)))

Using enter in an if statement

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 ''.

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.

How to store the print of a variable as string in Python?

Suppose I have a variable that is not a string, however, when I print it out it gives a string. For simplicities sake and for giving an example say that the variable is
message = "Hello Python world!"
Although, this is a string (Suppose it is not)
I would like to store a new variable A as the print statment of this message i.e.
A=print(message)
When I code A on the other line or print(A) it does not give me any outcome.
IN: A
Out:
IN: print(A)
Out: None
Can someone help me figure this out?
I'm guessing you're looking for something like this:
var = 123
A = str(var) # A is now '123'
The print() function doesn't return anything; it simply prints to the standard output stream. Internally, though, it converts non-string arguments to strings, as in the example code above.

Resources