Related Tutorials

9.Python Intro - User Input

By: Carlo Sarli

Posted: February 10, 2021 in (Python) (Intro)

Tech Used:

  1. Python3.x

Reading Time: 1 minutes

Placeholder image

User Input

With Python it is possible to get user input in a variety of ways.

In this example we will write a little command line program to get input from a user.

We also have a little exercise at the end that should help you put together all the concepts explored in the python intro series

# USER INPUT -------------
import sys 

print('What is your name?')
 
# Stores everything typed up until ENTER
name = sys.stdin.readline()
 
print('Hello', name)


# game time 

def add_two(a: int, b: int):
    return a+b

while True:
    print('first number please')
    a: int = int(sys.stdin.readline())
    print('second number please')
    b: int = int(sys.stdin.readline())
    result: int = add_two(a, b)
    print('result: '  f'{result}')
    print('press q to quit or any other key to continue')
    c: str = sys.stdin.readline().rstrip()
    if c == 'q':
        break
    else: 
        continue


# exercise time baby
#this program is fun but has many flaws
# first what if the user inputs something that is not a number?
# can you fix it?
# what if the user would like to input 3 or 4 numbers?
# can you do that?
# can you extend our little calculator to do divisions too?
# have fun