Giannis
Giannis

Reputation: 33

Input from keyboard the <enter>

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)

Upvotes: 0

Views: 112

Answers (2)

TheoretiCAL
TheoretiCAL

Reputation: 20561

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.

Upvotes: 1

Jacques de Hooge
Jacques de Hooge

Reputation: 6990

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

Upvotes: 0

Related Questions