Discover Python and Patterns (2): Basic interaction

Published November 14, 2019
Advertisement

In the first post, we saw how to install an IDE and how to display a message; it is time to add some interaction with the player.

Wait for a key

Create a new python program and type the following line:


input("Press Enter to continue...")

If you run the program, you get the following result in spyder:

Spyder basic interaction

In the spyder console, we find the same line starting with “In [1]:”, and the message “Press Enter to continue…”:


In [1]: runfile('C:/dev/press_enter.py', wdir='C:/dev')

Press Enter to continue...

There is no line starting with “In [2]:” as before: it means that the console is waiting for user input. Click on the console window to get the focus, and then press Enter:

Spyder basic interaction

Now the program is over, and the line starting with “In [2]:” is visible:


In [1]: runfile('C:/dev/press_enter.py', wdir='C:/dev')

Press Enter to continue...

In [2]:

The input() function

As for the print() function, the input() function can have one argument: the message to display. It also has a return value: the message typed by the user. If you run the following program:


name = input("Enter your name: ")
print("Your name is",name)

and if you type your name in the Spyder console, then you get a result like:


In [1]: runfile('C:/dev/enter_name.py', wdir='C:/dev')

Enter your name: phylyp
Your name is phylyp

In [2]: 

We store the return value of the input() function in the variable name. Then, we print the message “Your name is” followed by the content of the variable name (with one space in between).

Note that, if we type this:


print("Your name is","name")

We get the following result:


Your name is name

Since quotes surround name, Python does not analyze it and just copy it. If we remove the quotes (as before), we see the content of the variable name.

Format strings

There are many...

Continue reading on https://learngameprog.com...

0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Advertisement