Can't use randint() directly in the .format() string? - python

Complete beginner here.
I'm making a short game where one of the two players is randomly chosen to start the game:
from random import randint
player1 = input("First player, enter your name: ")
player2 = input("Second player, enter your name: ")
print("{randint(0,1)} will go first".format(name1, name2))
I want randint() to choose either player1 or player2, but I'm getting a TypeError. If I were to put either 0 or 1 into the {} instead of randint(0, 1) it works fine. Why doesn't this work? What other options are there besides an if/elif statement?

use randint(0,1) as an index to get the player name
players=[player1,player2]
print("{} will go first".format(players[randint(0,1)])

That isn't quite how the string format method works, the numbers you pass in like {0} and {1} serve as indices in the things you pass into the string in the .format(0th item here, 1st item here...etc.) call. So if you want your random integer to show up you should do something like:
print("{0} will go first".format(randint(0,1)))

Related

Add more values in a list at once in Python

I'm a beginner in Python and I'm trying to solve this problem.
I'm trying to write a code where you can put your name and the amount that you want to donate.
The thing is, deppending on the amount of the donation you can have more chances to be the winner.
Eg. If you donate $10 (1 chance), $20(2 chances), $30(3 chances).
My biggest problem is because I can't figure out how to solve this problem when the person insert $30 its name goes to the list 3 times and so on. I tried to use "for..inrange():" but without any sucess. Can someone explain me how to do this?
from random import shuffle
from random import choice
list = []
while True:
name = str(input('Write your name: '))
donation = float(input('Enter the amount you want to donate.: $ '))
list.append(name)
print('You donated $ {}. Thank you {} for you donation!'.format(donation, name))
print('=-'*25)
print('[1] YES')
print('[2] NO')
answer = int(input('Would you like to make another donation? '))
if answer == 1:
continue
else:
shuffle(list)
winner = choice(list)
break
print('The winner was: {}' .format(winner))
First do not use the name of a built-in type as a (meaningless) variable name. Change list to entry_list.
For the particular problem
compute the quantity of chances;
make a list of the person's name that many times;
extend the entry list with that list of repeated name.
Code:
entry_list = []
while ...
...
chances = int(donation) // 10
entry_list.extend( [name] * chances )
An alternative to adding another loop with additional control flow, you can use list.extend() with a list expression:
num_chances = donation // 10
chances = [name] * num_chances
all_chances.extend(chances)
Note that list is a built-in python identifier, and it's not a good idea to overwrite it. I've used all_chances instead.
Rather than adding extra names to the list to represent the higher chance, you could use the donations as weights in the random.choices function:
from random import choices
names, donations = [], []
while True:
names.append(input('Write your name: '))
donations.append(float(input('Enter the amount you want to donate.: $')))
print(f'You donated ${donations[-1]}. Thank you {names[-1]} for your donation!')
print('=-'*25)
print('[1] YES')
print('[2] NO')
if input('Would you like to make another donation? ') != '1':
break
winner = choices(names, donations)[0]
print(f'The winner was: {winner}')
This allows for non-integer donations to be counted fairly -- e.g. if Bob donates $0.25 and Fred donates $0.50, the drawing will still work in a reasonable way. It also allows very large donations to be handled without tanking the performance of the program -- if you have one list entry per dollar donated, what happens if Elon donates $20B and Jeff donates $30B? (The answer is that your fan spins really fast for a while and then the program crashes because you can't create a list with 50 billion elements -- but this is not a problem if you simply have a list of two elements with large int values.)
Note that shuffle is not necessary if you're using random.choices (or random.choice for that matter) because those functions will already make a random selection from the list.
You can use a for loop to append the name to the list more than one time :
for i in range(donation//10):
list.append(name)
This code should do the job. Please follow good naming conventions as pointed out by others. I have changed the list variable to donations as it is forbidden to use keywords as variables.
I have included the name in donations int(name) // 10 times using the extend function as pointed out by others. You may change the number of times as you wish.
from random import shuffle
from random import choice
donations = []
makeDonation = True
winner = "Unknown"
while makeDonation:
name = str(input('Write your name: '))
donation = float(input('Enter the amount you want to donate.: $ '))
donations.extend([name for i in range ( int(donation) // 10)])
print('You donated $ {}. Thank you {} for you donation!'.format(donation, name))
print('=-'*25)
print('[1] YES')
print('[2] NO')
answer = int(input('Would you like to make another donation? '))
if answer == 2:
makeDonation = False
shuffle(donations)
winner = choice(donations)
print('The winner was: {}' .format(winner))

How do I randomly select a variable from a list, and then re assign it to another variable?

I want to make a mastermind game im sure you all know what it is, some kind of GCSE style python number guessing game. it should ask you for a number, select a number and then tell you if you guessed any correctly but im having trouble assigning that randomly selected number to "x" perhaps.
I am pretty new to python as you can see.
numberseasy = ['1244', '1354', '2355', '2366', '2609', '0010', '1234', '8873', '7775', '2512', '0293', '9463', '9901',
'6272', '0629']
numbershard = ['25356', '86025', '67390', '96873', '01255', '77654', '96756', '88742', '09564', '12345', '19455',
'35656', '20967', '32570']
print("welcome to mastermind!")
gamemode = input("please select gamemode: easy, hard")
if gamemode == "easy":
(random.choice(numberseasy)) = x
print("easy was selected")
print("im thinking of a number, try to guess a one digit integer each time to work out the number im thinking of i")
print("will tell you if you have one correct")
first = input("please enter a number")
Variable assignments go from left to right. You just need x = random.choice(numberseasy).
You should be using a .lower() to the input string for text. This would allow the text to be entered in any capital letters.
As mentioned with blorgon's answer, you must have the variables on the left-hand side and the input on the right. In python, it is right to left such as cake = True or food = "cake".
numberseasy = ['1244', '1354', '2355', '2366', '2609', '0010', '1234', '8873', '7775', '2512', '0293', '9463', '9901',
'6272', '0629']
numbershard = ['25356', '86025', '67390', '96873', '01255', '77654', '96756', '88742', '09564', '12345', '19455',
'35656', '20967', '32570']
print("welcome to mastermind!")
gamemode = input("please select gamemode: easy, hard")
if gamemode.lower() == "easy":
x = random.choice(numberseasy)
print("easy was selected")
print("im thinking of a number, try to guess a one digit integer each time to work out the number im thinking of i")
print("will tell you if you have one correct")
first = input("please enter a number")

Why code not working for configuring while loop

Why my code not working
a “game” where, through input, enter the number of players who will play the game, how to make so many inputs (for player nicknames) be displayed, how many players are playing? and how to do something to add all the nicknames to the array later?
For example: the host introduced what 5 people play, how to output 5 inputs and then add all the nicknames to the array?
print("Add players!")
plam = int(input("How many players will be? \n"))
playersNames = []
i = len(playersNames)
while i < plam:
writePlayerName = input("Write player's nickname: " + Fore.GREEN)
print(Fore.WHITE)
playersNames.append(writePlayerName)
print(playersNames)
break;
Problem statement
player names can be entered endlessly, but I here restricted that there will be 5 players
You can use a for loop:
for i in range(plam):
writePlayerName = input("Write player's nickname: " + Fore.GREEN)
print(Fore.WHITE)
playersNames.append(writePlayerName)
print(playersNames)
Your break; statement is ending the while loop. You can remove the while loop and it should function as as you meant it to.
Your code is working, but it is not doing what you want to do, because you missed some logical steps:
You only update i once outside the loop.
len function will not make i magically track the length of playerNames it will only put current length when called in to i which is 0, because you call len when playerNames is empty.
You call break in the loop without condition, so your loop will always exit after the first time.
While there are several ways to write this code, and Andrea Pollini gave a good, clean example, here is the minimum fix to your code to do what you want:
print("Add players!")
plam = int(input("How many players will be? \n"))
playersNames = []
while i < plam:
writePlayerName = input("Write player's nickname: " + Fore.GREEN)
print(Fore.WHITE)
playersNames.append(writePlayerName)
print(playersNames)
i = len(playersNames)
Note, that all I did was to move the len call in to the loop, to where the break used to be.
Try this one
print("Add players!")
plam = int(input("How many players will be? \n"))
playersNames = []
i = len(playersNames)
for i in range(plam):
writePlayerName = input("Write player's nickname: " + Fore.GREEN)
print(Fore.WHITE)
playersNames.append(writePlayerName)
print(playersNames)
output
Add players!
How many players will be?
3
Write player's nickname: jhon
['jhon']
Write player's nickname: smith
['jhon', 'smith']
Write player's nickname: roky
['jhon', 'smith', 'roky']

Why when I use two functions in a program only one works

Im doing a simple code jam for school and my question is why when I use two functions in a program only one works or it doesn't work at all. one_player_# is the name of my function. I want to use if- statement to call the functions for the user to choose a game-mode. My game modes is one player and two player. So I made the code for the game a function so I can make it possible for the user to choose a game mode through the if -statement but when you choose a game-mode it doesn't work. Is what im trying to do not possible? Hope that makes sense plz explain what i'm dong wrong thanks.
# choose your game mode
op = input("Choose gamemode - Two player = 2 One player = 1 : ")
if op == 2 :
print (two_player_op())
if op == 1:
print(one_player_op())
#One player Function
def one_player_op():
# I put game code for 1st play here
#Two player function
def two_player_op():
# I put game code for two player here
#code ends
I expect for it to allow the user to choose a game-mode and run it rather than giving me a blank response
Your script is reading from top to bottom.
First define the functions, and then call them. Also, use "int" before input.
#One player Function
def one_player_op():
# I put game code for 1st play here
#Two player function
def two_player_op():
# I put game code for two player here
#code endsenter code here
# choose your game mode
op = int(input("Choose gamemode - Two player = 2 One player = 1 : "))
if op == 2:
print (two_player_op())
if op == 1:
print(one_player_op())
You need to make sure you are comparing an int to another int if you want to get a True result. Keep in mind the types of data you are manipulating. Also in python, you must define functions before code that runs them. Not code that defines them, but the code that is actually executing the function.
So in your case:
#One player Function
def one_player_op():
# I put game code for 1st play here
#Two player function
def two_player_op():
# I put game code for two player here
# choose your game mode
op = int(input("Choose gamemode - Two player = 2 One player = 1 : "))
if op == 2 :
print (two_player_op())
if op == 1:
print(one_player_op())
#code ends
Incorporating the comment, if you want to make it clear that only one game mode is to run, for code readability purposes, and to make sure any future additional conditional options you might add do what you intend them to do you can write the conditionals as:
if op == 2 :
print (two_player_op())
elif op == 1:
print(one_player_op())
#code ends
You need to handle other options added by user and not only (1 or 2)
# choose your game mode
op = input("Choose gamemode - Two player = 2 One player = 1 : ")
try:
user_input = int(op)
except ValueError:
# handles characters added in input e.g "one", "play"
print("Please enter values between 1 or 2 only ")
if user_input == 2 :
print (two_player_op())
elif user_input== 1:
print(one_player_op())
else:
print("Please enter values between 1 or 2 only ")
#One player Function
def one_player_op():
# I put game code for 1st play here
#Two player function
def two_player_op():
# I put game code for two player here
#code ends
Need to convert input string to int.
op = int(input("........'))

How to make random decisions on variables of variables?

So we have a school project to make a program that asks the user whether to pick a random card from a 52 deck or simulate a coin toss - heads or tails. I've got a beta version working but I'm looking into how to make the program more efficient. Basically, the program sets the tuples 'card' and 'coin' to all the possible types, so for coin, heads and tails, and card, the 52 different cards.
The following part of the program sets the variable 'choice' to either card or coin
while choice!='card' and choice!='coin':
choice=input("Pick a card or toss a coin (card/coin)?: ")
if choice!="card" and choice!="coin":
print("Please enter either 'card' or 'coin'...")
time.sleep(2)
Next I want to be able to return a value from either tuple depending on the value of 'choice' without using and if statement, something along the following:
print("The ",choice," picked at random is... ",random.choice("Either card, or coin"),"!")
How would I do this? Thanks, Brandon.
Full program:
#importing modules used in program
import time
import random
#creating duples for possible cards and coins
cards=["Ace of spades","King of spades","Queen of spades","Jack of spades","10 of spades","9 of spades","8 of spades","7 of spades","6 of spades","5 of spades","4 of spades","3 of spades","2 of spades","Ace of diamonds","King of diamonds","Queen of diamonds","Jack of diamonds","10 of diamonds","9 of diamonds","8 of diamonds","7 of diamonds","6 of diamonds","5 of diamonds","4 of diamonds","3 of diamonds","2 of diamonds","Ace of clubs","King of clubs","Queen of clubs","Jack of clubs","10 of clubs","9 of clubs","8 of clubs","7 of clubs","6 of clubs","5 of clubs","4 of clubs","3 of clubs","2 of clubs","Ace of hearts","King of hearts","Queen of hearts","Jack of hearts","10 of hearts","9 of hearts","8 of hearts","7 of hearts","6 of hearts","5 of hearts","4 of hearts","3 of hearts","2 of hearts"]
coin=["Heads","Tails"]
#setting variable 'repeat' to 'y' to start the mainloop of the program
repeat="y"
while repeat=="y":
#blanking the repeat and choice variables so they can be reset later
repeat=""
choice=""
#won't allow the user to continue until either 'card' or 'coin' is entered
while choice!='card' and choice!='coin':
choice=input("Pick a card or toss a coin (card/coin)?: ")
if choice!="card" and choice!="coin":
print("Please enter either 'card' or 'coin'...")
time.sleep(2)
print("The ",choice," picked at random is... ",random.choice(card),"!")
#won't allow the user to continue until either 'y' or 'n' is entered
while repeat!="y" and repeat!="n":
repeat=input("Go again..? (y/n): ")
if repeat!="y" and repeat!="n":
print("Please enter either 'y' for yes or 'n' for no...")
time.sleep(2)
#ending of the program
print("Goodbye!")
time.sleep(2)
The easiest way to accomplish this is to have a dictionary of tuples:
items = { 'coin': coin,
'card': cards }
Then, after choice has been set properly by your while loop, use the word provided by the user as the key to select from the dictionary the correct list, which can then be passed to random.choice:
print("The ", choice, " picked at random is ...", random.choice(items[choice]))
I'm for sure if this is what you're asking, but if the tuple you're talking about is this ('coin', 'card'), then you can do the following:
import random
test = ('coin', 'card')
test[random.randint(0, 1)]
That will randomly select one of the two choices.

Categories