Input from keyboard the <enter> - python

I use Python 3 in Windows. My problem is that I need to find out how can I put in my code the choice that if the user pushes the Enter key the program will continue doing the calculation and when the user types q and pushes the Enter key the program will be terminated.
A simple code is below.
while True:
x = int(input('Give number: '))
y=x*3
print(y)

while True:
user_input = input('Give number: ')
if not user_input.isdigit(): #alternatively if user_input != 'q'
break
x = int(user_input)
y=x*3
print(y)
Assuming you want to calculate while new numbers are entered, the str isdigit function returns True if the string only contains digits. This approach will allow you to handle if the user enters a non-integer like xsd, which will crash the program if you try to cast to int. To only exit if q is entered, you would do if user_input != 'q', but this assumes the user only enters numbers or q.

while True:
s = input('Give number: ')
if s == 'q':
break
y=int(s)*3
print(y)

Related

While loop to append list or break based on value type and user input

I'm trying to write a python program that asks the user to enter an integer or "q" (case-insensitive) to quit that will then take any integers and print the sum of the last 5.
I have created a holding list and some counter and test variables to help with this, but I can't seem to get it to work the way I'd like. I keep getting various errors.
The code I currently have is
my_list = []
quit = 0
i = 0
while quit == 0:
value = eval(input("Please enter an integer or the letter 'q' to quit: ")
if value.isdigit()
my_list.append(value)
i += 1
print(sum(my_list[-1] + my_list[-2] + my_list[-3] + my_list[-4] + my_list[-5]))
if value == q:
quit += 1
elif
print("Your input is not an integer, please try again")
This is returning and error of invalid syntax for the my_list.append(value) line.
What I would like this to do is allow for me to enter any integer, have the loop test if it is an integer, and if so, add it to the holding list and print out the sum of the most recent 5 entries in the list (or all if less than 5). If I enter "q" or "Q" I want the loop to break and the program to end.
There are many errors in your code.
Fixed code:
while quit == False:
value = input("Please enter an integer or the letter 'q' to quit: ")
if value.isdigit():
my_list.append(int(value))
i += 1
print(sum(my_list[-5:]))
elif value == 'q' or value == 'Q':
quit = True
else:
print("Your input is not an integer, please try again")
Notes:
Do not use eval, it can be dangerous. As you check if the value contains digit, you can safely use int to cast the value.
If you want to quit with 'q' or 'Q', you have to check both.
You have to slice your list to avoid exception if your list does not contain at least 5 elements.
You can try if this:
*It is shorter and more readable
my_list = []
while True:
x = input("Please enter an integer or the letter 'q' to quit: ")
if x == 'q':
break
else:
my_list.append(int(x))
output_sum = sum(my_list[-5:])
print(output_sum)
Input
1
2
3
4
5
q
Output
15
You should check that the input contains at least 5 digits. You can do this by first checking the length of the input string then calling isnumeric() on the string.
Then you just need to slice the string (last 5 characters) and sum the individual values as follows:
while (n := input("Please enter an integer of at least 5 digits or 'q' to quit: ").lower()) != 'q':
if len(n) > 4 and n.isnumeric():
print(sum(int(v) for v in n[-5:]))
...or if you want to input numerous values then:
numbers = []
while (n := input("Please enter a number or 'q' to quit: ").lower()) != 'q':
if n.isnumeric():
numbers.append(n)
else:
print(f'{n} is not numeric')
if len(numbers) < 5:
print(f'You only entered {len(numbers)} numbers')
else:
print(sum(int(v) for v in numbers[-5:]))

How to return to menu by a special key?

Is there any simple method to return to menu by entering a special key? If the user made a mistake while entering the input, user can return to main menu by pressing # (a special key) key at the end of the input.
x = input("Enter first number: ")
Here, user enter 5, but want to exit by input #. So, x = 5#
I tried some including this
x=input("Enter first number: ")
print(int(a))
if x == "#":
exit()
Also tries this too
for x in ['0', '0$']:
if '0$' in x:
break
But, unable to handle numbers and string values together.
while True:
x = input()
if x[-1] == '#':
continue
# other stuff
this should work
Try
user_input = input("Enter your favirote deal:")
last_ch = user_input[-1]
if(last_ch == "#"):
continue
else:
//Your Logic
int(x) will not work if it contains characters other than numbers.
use this construction (# will be ignored by converting a string to int)
x=input("Enter first number: ")
print(int(x if "#" not in x else x[:-1])) # minus last if has #
if "#" in x:
exit() # or break or return, depends what you want

How to cleanly ask user for input and allow several types?

So this is a prompt for user input, and it works just fine. I was printing some names and associated (1 based) numbers to the console for the user to choose one. I am also giving the option to quit by entering q.
The condition for the number to be valid is a) it is a number and b) it is smaller or equal than the number of names and greater than 0.
while True:
number = str(input("Enter number, or q to quit. \n"))
if number == "q":
sys.exit()
try:
number = int(number)
except:
continue
if number <= len(list_of_names) and number > 0:
name = list_of_names[number-1]
break
There is no problem with this code, except I find it hard to read, and not very beautiful. Since I am new to python I would like to ask you guys, how would you code this prompt more cleanly? To be more specific: How do I ask the user for input that can be either a string, or an integer?
A bit simpler:
while True:
choice = str(input("Enter number, or q to quit. \n"))
if choice.lower() == "q":
sys.exit()
elif choice.isdigit() and (0 < int(choice) <= len(list_of_names)):
name = list_of_names[int(choice)-1]
break
Just downcase it.
number = str(input("Enter number, or q to quit. \n"))
number = number.lower()
That will make the q lower case so it doesn't matter if they press it with shift if they press something else just make a if statement that sets a while loop true.

How can I terminate a loop when pressing Enter

I want to write a program that repeatedly asks the user to enter an integer or to terminate input by pressing Enter key, and then prints the even integers from those numbers entered.
Now, I am pretty much done with this program, I've mentioned the code I've come up with below. I am facing only one problem: how can I terminate the program when the users presses the Enter key?
def evenMem(aList):
mnew = []
for i in aList:
if (i % 2) == 0:
mnew.append(i)
return mnew
def main():
m = []
while True:
n = int(input('Enter a number: '))
m.append(n)
print(evenMem(m))
main()
In case you're using Python 3.x, make the while loop look like this:
while True:
line = input('Enter a number: ')
if not line:
break
n = int(line)
m.append(n)
You might want to surround the conversion to int with a try-catch to handle the case where the user enters something which is not parseable as an int.
With Python 2.x, the input() function will raise an exception if the input is empty (or EOF), so you could do this instead:
while True:
try:
n = int(input('Enter a number: '))
except:
break
m.append(n)

How to allow strings in a float input?

So I'm asking my user to input a number(float)
num=float(input("Please enter a number"))
but I'm also asking the user to enter the value "q" to quit
and since this variable can only take in floats, the program is not letting the user enter the string ("q"), is it possible to do this?
Expect a string and parse it has as a float only if it is not equal to q.
temp = input("Please enter a number")
if not temp == "q":
num = float(temp)
You're trying to automatically cast your input to a float. If you don't want to do this in all cases you should add some if/else logic in here:
input_string = input("Please enter a number")
if not input_string == 'q':
num = float(intput_string)
Or, to be a bit more pythonic you should do a try/except strategy:
input_string = input("Please enter a number")
try:
num = float(input_string)
except ValueError:
if input_string == 'q':
# However you exit
The second is technically more pythonic according to the EAFP principle (https://docs.python.org/2/glossary.html)

Categories