ABeast103
ABeast103

Reputation: 5

How can I put two arguments in one string for a input function in python?

I am pretty new to python and am trying to create a small game just to help develop my skills, but I ran in to one code line I just can't figure out.

r = str(input("Player 1 please enter a integer between 1 and 10: "))

I have another line that goes earlier and asks the player for a name.

name = input('Player 1 what is your name? ')

but I want it so that instead of it saying

r = str(input("Player 1 please enter a integer between 1 and 10: "))

that it says the name of the player I got from the input earlier on in the code? How can I do this?

Upvotes: 0

Views: 143

Answers (4)

Ahmed Abdelkafi
Ahmed Abdelkafi

Reputation: 477

I strongly suggest that you use (according to PEP-3101) :

r = str(input('{} please enter a integer between 1 and 10: '.format(name)))

Instead of using the modulo operator (%) like :

r = str(input("%s please enter a integer between 1 and 10: " % name))

Upvotes: 1

Joshua Stokes
Joshua Stokes

Reputation: 57

You can also do this since you are working with integers:

However, this solution will only work in Python 2

player_name = raw_input("What is your name")
r = int(input("%s Enter a number:" % player_name))

Upvotes: 1

DurgaDatta
DurgaDatta

Reputation: 4170

You can use the formated string:

r = str(input("%s please enter a integer between 1 and 10: " % player_name))

input expects a string. So, first you construct a approprate string and then pass it. Simplified example of %

"%s is good" % "he" # transforms to "he is good"

% It is a sort of substitution operation with type checking, eg.%s specifies string type.

Upvotes: 1

merlin2011
merlin2011

Reputation: 75545

You can use string formatting for this.

r = str(input("%s please enter a integer between 1 and 10: " % name))

Upvotes: 1

Related Questions