How do I show a suffix to user input in Python? - python

I want a percentage sign to display after the users enters their number. Thanks
percent_tip = float(input(" Please Enter the percent of the tip:")("%"))
For example, before the user types anything they should see:
Please Enter the percent of the tip:
Once they begin typing the number 20 they should see:
Please Enter the percent of the tip: 20
After they hit <Enter> they should see:
Please Enter the percent of the tip: 20%

Please try this if this is what you are asking for:
import sys
import time
percent_tip = ""
while percent_tip in "123456789": # This part checks with the "if" statement, if its not a integer then it returns
percent_tip = input("Please Enter the % of the tip: ")
if percent_tip in "123456789":
print(str(percent_tip) + " %") # Prints the number and the percentage symbol
sys.exit() #stops the shell
else:
time.sleep(.100) #Shell waits then goes back in the while loop (unless its controlled by the "while" and "if")
Please do not try to harden yourself with a code that you don't know how to do it.

If you are on Windows, you will have the msvcrt module available. It provides, among others, the getwche() function, giving you the key pressed. This allows you to act on individual characters, and then print the % at the end (if you play around a bit more, you can probably also get it to appear while typing).
Example:
def get_chars():
chars = []
new = msvcrt.getwche()
while new != '\r': # returns \r on <RETURN> press
# you probably want to do some input validation here
chars.append(new)
new = msvcrt.getwche() # get the next one
print(end='%', flush=True)
return ''.join(chars) # this returns a str, you might want to directly get an int
Also, you will probably want to add input validation inside to make sure the input is only numbers.

Related

python 3 input without newline

I am new to coding. And I would like to know if there's a way for input function to not print newline character after the value is entered. Something like print function's argument end. Is there any way?
Well, you can't make input() trigger by anything besides 'Enter' hit (other way may be using sys.stdin and retrieving character one-by-one until you receive some stop marker, but it's difficult both for programmer and for user, I suppose). As a workaround I can the suggest the following: if you can know the length of line written before + length of user input, then you can use some system codes to move cursor back to the end of previous line, discarding the printed newline:
print("This is first line.")
prompt = "Enter second: "
ans = input(prompt)
print(f"\033[A\033[{len(prompt)+len(ans)}C And the third.")
\033[A moves cursor one line up and \033[<N>C moves cursor N symbols right. The example code produces the following output:
This is first line.
Enter second: USER INPUT HERE And the third.
Also note that the newline character is not printed by your program, it's entered by user.
name=input('Enter your name : ')
print('hello',name,end='')
I know about the end function which is abov

Error Shows up when I press the Enter Key-- How can I ignore the enter key and then keep inputting?

In this code I'm inputting as many integers as I want, and then pressing the enter key twice to end the program and get the Maximum Value of all the integers I just input. However, if my first input is the enter key, an error shows up. How do I fix this error (using while and if)so that the code will ignore it and let me keep inputting numbers? Thank you everyone.
print("Please put in some integers and hit the enter key twice to finish:")
s = input()
first = True
while s != "":
lst = s.split()
for x in lst:
if first:
maxV = int(x)
first = False
else:
if maxV < int(x):
maxV = int(x)
s = input()
print(maxV)
Before anything else, a word on input() and the Enter key! Pressing enter is just the way you tell input() that you’re done writing whatever text you want. When that happens, input() grabs the content of the line and sends it as a string to your program.
Therefore, saying that your program crashes if your first input is the enter key isn’t really accurate. The important part is that you wrote nothing before hitting enter, not the act of hitting enter itself. Since you wrote nothing the line is empty, which means input() returns a string containing nothing, an empty string. It’s the empty string, as I will show below, not the innocent enter key, which is at fault here.
Now, let’s take a look at what’s causing the error. You haven’t actually shared the exact error message, but I’m certain that it mentions something about maxV being undefined.
As we just saw, if you don’t write anything when first prompted for input then s is the empty string. As a result, you skip the while loop and land directly on the line print(maxV). Since you didn’t enter the while loop, however, your program has never heard of maxV at that point. When it goes looking for the variable maxV it finds nothing, and sensibly throws an error.
Here is how I would refactor your program:
import math
max_val = - math.inf
prompt_text = 'Enter one or more numbers, or enter nothing to quit: '
curr_line = input(prompt_text).strip()
while curr_line != '':
curr_line_vals = (int(curr_val) for curr_val in curr_line.split())
curr_line_max = max(curr_line_vals)
max_val = max(max_val, curr_line_max)
curr_line = input(prompt_text).strip()
print(f'maximum value: {max_val}')
Do note that the program above does not verify input at all, that's something to keep in mind. max_val has a default value of minus infinity, which means the code won't crash if the user quits without having entered any numbers.
Let me know if you have any questions!

How do I read just part of a string?

For my program I ask the user to input a command. If the user writes: Input filename (filename being any possible name of a file in the computer) I want my program to only read Input so it knows what if statement to use and then open the file that the user wrote.
There is also another part where I have to do a similar task, where the user inputs: score n goals.(n is the top number of players the program has to read from a list) I want the program to differentiate this from 2 other similar tasks (score n misses and score n passes).
I am not sure if I'm approaching this the correct way, but this was my try for the first case I talked about, but it doesn't work.
user_input = input ('File name:')
input_lowered = user_input.lower()
command = input_lowered[0:4]
if command == 'input' :
fp = open ("soccer.part.txt")
else :
user_upper = input ('Input name:')
Thanks in advance for any clue of how I should aim at fixing this!!!
You can do that as follows:
your_string[0:5]
This will get the first five characters of the string as a string.
If you would like to grab a part of the string from the start then you can use:
my_string[:number]
if you would like to grab a part of the string from the end:
my_string[-number:]

Display % after input(...) prompt?

Suppose we are on python3.3 and multi-platform (Linux and WIndow), if I do following:
>>> eval(input("enter a percent from 1-100"))
I get:
enter a percent from 1-100: (Terminal is Waiting for user prompt)
I want it to display:
enter a percent from 1-100: (waiting for user prompt) %
How do I show that % following the parenthesis?
If I understand your question, you want to be able to write a prompt that includes a % sign character, but places the user's cursor to the left of the sign, like this:
Enter a percent from 1-100: %
^ cursor is here
There's not a universal solution to this, since basic text-IO is usually oriented around input and output streams that don't have well defined interactions. There are some approaches that will work in some situations but not others, but I'm not sure of anything that will work everywhere (short of writing a GUI).
One suggestion I have is to include ASCII (and unicode) backspace characters '\b' (or '\x08') in your prompt. On some consoles this will move the cursor to the left one character per backspace. So, the prompt above could be generated by:
input("Enter a percent from 1-100: %\b\b\b\b\b")
This works when I run Python from a windows CMD.exe shell, but not when I run it within IDLE (the '\x08' characters are displayed as a box with a small circle taken out of the middle). It's a bit crude though, as it can't prevent the user from entering more characters than there are spaces before the % (which will be overwritten by the fifth character entered).
Another solution which may be a bit more robust (but not cross-platform, alas) is to use the curses module. I'm not knowledgeable enough about it to suggest code, but it should be possible to make it do what you want (and even control things like preventing the user from entering more than three characters, or moving the % sign to correctly align with values of any length).
One final thing: I strongly suggest that you don't use eval around your input call. If you expect (and require) an integer value, use int(input()). If you might get an integer, but could also get some other kind of value, use multiple lines to test what you got:
def get_val():
str_val = input()
try:
return int(str_val) # handle numbers like 1, 23232, etc.
except ValueError:
pass
try:
return float(str_val) # handles 23.5 and -3e-3 (but beware, also "nan" and "inf")
except ValueError:
pass
try:
return make_some_other_value(str_val) # whatever you want
except ValueError:
pass
return str_val # give up and return the string
Here's an alternative using the getch package. Instead of using input, we'll roll our own.
import string
import sys
try:
from msvcrt import getch
except ImportError:
from getch import getch
def char_valid(char):
"""Do whatever validation you need here."""
return char in string.ascii_letters or char in string.digits
def char_bkspace(char):
"""Matches backspace and delete."""
return char in ['\x08', '\x7f']
message_pre = 'enter a percent from 1-100'
message_post = '%'
user_input = ''
while True:
sys.stdout.write('\r{0} {1} {2}'.format(message_pre, user_input, message_post))
char = getch()
if char_bkspace(char):
user_input = user_input[:-1]
elif char_valid(char):
user_input += char
else:
break
print('\nyour message was', user_input)
This gets user input one character at a time in a while loop using getch. By using sys.stdout.write('\r...') we can avoid newlines and constantly overwrite the previous line.
This has the problem that if you backspace, multiple %'s will be visible because the new line is not entirely overwriting the previous line. This can be fixed by padding the string with spaces.

NameError when printing string's length based on input in python

I'm a complete beginner in Python and I need some 'help' with something which is relatively simple (for a non-beginner).
What I'm trying to make is a quick 'program' which measures the length of a string which has been inputted. Maybe I have not looked hard enough, but I can't seem to find any specific information about this on the interwebs.
Ok, so here is what I have done so far:
print "Please enter a number or word and I will tell you the length of it."
NR = raw_input()
print len(NR)
*NR has no significant meaning, it's just a random variable name
Everything works as expected at first. For example, I enter the word "Hello" and it then replies with "5" or I enter the number 100 and it replies with "3" which is great, but when I attempt to enter another word I get this error:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
hello
NameError: name 'hello' is not defined
However, when I enter another number (after I have already entered one), it just repeats the number which I have entered. For example, when I first enter the number "50" it replies with "2", but when I enter "50" a second time it just repeats the integer to me.
Note:
I think I understand the problem for the first part: It doesn't work more than once because the variable "NR" only counts as the first string which has been inputted. Even if I'm correct, I still don't know a solution to this.
Your program collects exactly one line of input and then finishes. After your program is finished, you are back in whatever environment you used to start your program. If that environment is a python shell, then you should expect that typing 50 will print a 50, and typing hello will print a no-such-variable-name error message.
To get your code to run more than once, put it in a while loop:
while True:
print "Please enter a number or word and I will tell you the length of it."
NR = raw_input()
print len(NR)
Note that raw_input() can print a prompt, so you don't need the print statement:
while True:
NR = raw_input("Please enter a number or word and I will tell you the length of it: ")
print len(NR)
This program fragment will run forever (or, at least until you interrupt it with Control-C).
If you'd like to be able to stop without interrupting the program, try this:
NR = None
while NR != '':
NR = raw_input("Please enter a number or word (or a blank line to exit): ")
print len(NR)
If you'd like to print the prompt once and then the use can enter many strings, try this:
print "Please enter a number or word and I will tell you the length of it."
while True:
NR = raw_input()
print len(NR)

Categories

Resources