running a while loop in python and functions not defined - python-3.x

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.

Related

Word "None" on line below input [duplicate]

This question already has answers here:
Why does my input always display none in python? [closed]
(2 answers)
Closed 23 days ago.
I wrote a simple program to track household items and output to a text file, with a while loop to have it keep running till "exit" is entered. I get the word "None" on the line below the input line when I haven't written it to do so. Here is my code.
HouseHoldItems = open('C:\\_PythonClass\\Assignment03\\HouseHoldItemsAndValue.txt', mode='a')
Items = ''
Value = ''
# while loop to keep program running until user enters "Exit"
while(True):
# Items is the primary variable, determines if user is entering new household item or wants to end the program
Items = input(print("Enter an Item (Or type 'Exit' to quit) : "))
# If statement to determine if user wants to end program
if(Items.lower() == "exit"):
break
# Else statement to write household items to the file, followed by value of items
else:
HouseHoldItems.write(Items + ', ')
Value = input(print("Enter an estimated Value: "))
HouseHoldItems.write(Value + '\n')
HouseHoldItems.close()
Here is a snip of the way the code looks as I input data items. (https://i.stack.imgur.com/CHOWk.png)
Is it part of the while(true) piece that is making it do this? Thanks for the help in advance.
You do not need to use the print function when using the input function.
Use:
Items = input("Enter an Item (Or type 'Exit' to quit) : ")
and:
Value = input("Enter an estimated Value: ")
While we're at it, in test conditions for while and if statements while your code works as is, it is not considered 'pythonic'. The pythonic way is to not use parentheses. ie
While True:
and:
if Items.lower() == "exit":

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.

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

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

Resources