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']
Related
I am making a program like a family feud where the user needs to guess a right answer according to the topic he chose. How can I get the specific word if he inputted only 1 word?
from nltk.corpus.reader import WordListCorpusReader
import os
again = True
print("GUESSING GAME")
print(reader.words('D:/VB/topic1.txt'))
while again:
num = int(input("PICK A NUMBER FOR THE TOPIC [1-3]: "))
if num == 1:
print("1. Name something people are afraid of. ")
print("======================================")
print("You need to guess 10 right answers in order to win. ")
reader = WordListCorpusReader('D:/VB/topic1.txt', ['topic1.txt'])
for i in range(0,10):
element = (input(str(i + 1) + ". "))
topic1.txt file:
Spiders
Heights
Other people
Dying
The dark
Ghosts
Snakes
The IRS
Being alone
Their boss or getting fired
For example, the user guessed: Dark. In my file, the answer is the "The Dark". How can I declare it as a right answer without including the "The". Another example would be "Their boss", I want to make the guess right if the user only input "Boss"
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))
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")
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)))
I am currently writing a code for my GCSE coursework and I am kind of stuck with my for loop which also contains an if-else statement.
I have done a code similar to this earlier in the program and it works perfectly fine but for some reason this part doesn't and I was wondering if someone could help me.
What I am trying to do is make a quiz type program and the part that I need help with is choosing the subject that the user wants to do.
The user has to type in their preferred subject but if they type the subject in wrong, or type in something invalid, then the program should allow the user to type it in again.
So far, if you type in a subject correctly the first time, the program will proceed to the next stage.
However, if you type it incorrectly the first time, it will ask the user to try again. But if you type it in correctly the second time, it will again ask the user to try again. Instead of having the program make the user type the subject again, even though it should've been valid the when they typed it in correctly, I want the program to proceed to the next stage.
Available subjects:
subjects = []
algebra = ("algebra")
computing = ("computing")
subjects.append(algebra)
subjects.append(computing)
Part that I need help with:
with open("student_file.csv", "a+") as studentfile:
studentfileReader = csv.reader(studentfile, delimiter = ',')
studentfileWriter = csv.writer(studentfile, delimiter = ',')
print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
ChosenSubject.lower()
for i in range(2):
if ChosenSubject in subjects:
print("\n")
break
else:
print("\nPlease try again.")
ChosenSubject == input("What subject would you like to do?")
ChosenSubject.lower()
if ChosenSubject in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
In the else block, perhaps you'd want to replace the '==' with '='.
Also do you want to give the user just two tries or keep asking them until they answer correctly? (The latter is what I inferred from your question, for that I'd recommend using continue)
The for loop just iterates over a collection of objects. Consider a list my_list = ['a', 'b', 'c']. On each iteration over my_list using for loop, it fetches one of the elements in order without repetition. range(2) is equivalent to [0, 1].
Try this:
print("Available subjects:\n-Algebra\n-Computing\n")
for i in range(2):
# `i` is 0 on first iteration and 1 on second. We are not using `i` anywhere since all we want is to loop :)
chosen_subject = input("What subject would you like to do? ")
if chosen_subject.lower() in subjects:
print("\n")
break
if chosen_subject.lower() in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
This is not an optimal solution, but since your learning I will try to keep it as close as your solution. Your problem is that calling ChosenSubject.lower() does not change the actual value in ChosenSubject.
Here is a working example:
print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
subjects = ["algebra", "computing"]
for i in range(2):
if ChosenSubject.lower() in subjects:
print("\n")
break
else:
print("\nPlease try again.")
ChosenSubject = input("What subject would you like to do?") #not '=='
if ChosenSubject.lower() in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
This from the doc:
This method returns a copy of the string in which all case-based
characters have been lowercased.