I am making a life counter for MTG I would like to ask the user for the life total and their name. Then use both in the program. I have a running and functional program that uses declared values for the healt count for player 1 and 2 and label and text for the players
p1hc = 20
p2hc = 20
I tested setting the values with the "input" function and printing the numbers in a different window to make sure
p1healthc = input (' What is the starting life count? ')
p2healthc = input (' What is the starting life count? ')
print (p1healthc)
print (p1healthc)
When I added the code to my running and working program with
### Declare global health count values for player 1 and player 2 variables
p1healthc = input (' What is the starting life count? ')
p2healthc = input (' What is the starting life count? ')
p1hc = p1healthc
p2hc = p2healthc
It would ask for the and set the values in the SHELL window and not start the program window after.
Related
I am making a word guesser for discord, and I have stumbled upon a problem I can not figure out. Full code here.
I have a keyword, a counter, and a wordhelp list. I am calling a function every x seconds, which will add a letter to the wordhelp list, from the keyword, based on the counter.
My question is: How can I start with the wordhelp list being dots for len(keyword), and then replace each dot with it's corresponding letter in the function.
I have tried something like this: wordhelp[counter] = keyword[counter] but that gives me this list assignment index out of range, because there is no dots in the wordhelp list to be replaced.
def __init__(self, bot):
self.bot.counter = 0
self.bot.keyword = ""
self.bot.wordhelp = []
# Called every 60 seconds
#tasks.loop(seconds=60)
async def loop_update(self):
# Add the new letter to the wordhelp list
self.bot.wordhelp[self.bot.counter] = self.bot.keyword[self.bot.counter]
# Edit the ini variable embed to show new keyword letter
await self.bot.ini.edit(embed=discord.Embed(title="Guessing game started!", description=f"Find the keyword starting with:\n`{''.join(self.bot.wordhelp)}`"))
self.bot.counter += 1
Instead of keeping an explicit list of dots, you can just keep a count of how many letters you want to 'reveal', and then create the display dynamically based on that. Something like this:
def hidden_word(word, reveal=0):
hidden = len(word) - reveal
dots = '.' * hidden
return word[:reveal] + dots
Now you can just feed it the count of how many letters to reveal:
word = 'giraffe'
for i in range(len(word)+1):
print(hidden_word(word, reveal=i))
# Produces:
.......
g......
gi.....
gir....
gira...
giraf..
giraff.
giraffe
I have just started learning python and i have been given an assignment to create a list of players and stats using different loops.
I cant work out how to create a function that searches the player list and gives an output of the players name and the players stat.
Here is the assignment:
Create an empty list called players
Use two input() statements inside a for loop to collect the name
and performance of each player (the name will be in the form of a
string and the performance as an integer from 0 – 100.) Add both
pieces of information to the list (so in the first iteration of the
loop players[0] will contain the name of the first player and
players[1] will contain their performance.) You are not required to
validate this data.
Use a while loop to display all the player information in the
following form:
Player : Performance
Use a loop type of your choice to copy the performance values from
the players list and store these items in a new list called results
Write a function that accepts the values “max” or “min” and
returns the maximum or minimum values from the results list
Write a function called find_player() that accepts a player name
and displays their name and performance from the players list, or an
error message if the player is not found.
Here is what I have so far:
print ("Enter 11 Player names and stats")
# Create player list
playerlist = []
# Create results list
results = []
# for loop setting amount of players and collecting input/appending list
for i in range(11):
player = (input("Player name: "))
playerlist.append(player)
stats = int(input("Player stats: "))
playerlist.append(stats)
# While loop printing player list
whileLoop = True
while whileLoop == True:
print (playerlist)
break
# for loop append results list, [start:stop:step]
for i in range(11):
results.append(playerlist[1::2])
break
# max in a custom function
def getMax(results):
results = (playerlist[1::2])
return max(results)
print ("Max Stat",getMax(results))
# custom function to find player
def find_player(playerlist):
list = playerlist
name = str(input("Search keyword: "))
return (name)
for s in list:
if name in str(s):
return (s)
print (find_player(playerlist))
I have tried many different ways to create the find player function without success.
I think I am having problems because my list consists of strings and integers eg. ['john', 6, 'bill', 8]
I would like it to display the player that was searched for and the stats ['John', 6]
Any help would be greatly appreciated.
PS:
I know there is no need for all these loops but that is what the assignment seems to be asking for.
Thank you
I cut down on the fat and made a "dummy list", but your find_player function seems to work well, once you remove the first return statement! Once you return something, the function just ends.
All it needs is to also display the performance like so:
# Create player list
playerlist = ["a", 1, "b", 2, "c", 3]
# custom function to find player
def find_player(playerlist):
name = str(input("Search keyword: "))
searchIndex = 0
for s in playerlist:
try:
if name == str(s):
return ("Player: '%s' with performance %d" % (name, playerlist[searchIndex+1]))
except Exception as e:
print(e)
searchIndex += 1
print (find_player(playerlist))
>>Search keyword: a
>>Player: 'a' with performance 1
I also added a try/except in case something goes wrong.
Also: NEVER USE "LIST" AS A VARIABLE NAME!
Besides, you already have an internal name for it, so why assign it another name. You can just use playerlist inside the function.
Your code didn't work because you typed a key and immediately returned it. In order for the code to work, you must use the key to find the value. In this task, it is in the format of '' key1 ', value1,' key2 ', value2, ...]. In the function, index is a variable that stores the position of the key. And it finds the position of key through loop. It then returns list [index + 1] to return the value corresponding to the key.
playerlist = []
def find_player(playerlist):
list = playerlist
name = str(input("Search keyword: "))
index = 0
for s in list:
if name == str(s):
return ("This keyword's value: %d" % (list[index+1]))
index+=1
print (find_player(playerlist))
I am trying to have Python read through an excel file and find the maximum and minimum temperature for a set of days. The issue I'm having is that the first for loop functions correctly and all the ones after do not.
`weather_data = open("WeatherDataWindows.csv", 'r')
max_temp = 41
for next_line in weather_data:
next_line = next_line.split(',')
if next_line[1].isdigit():
if int(next_line[1]) > max_temp:
max_temp = int(next_line[1])
print("The max temperature is", max_temp, "degrees")
min_temp = 100
for find_min_temp in weather_data:
find_min_temp = find_min_temp.split(',')
if find_min_temp[3].isdigit():
if int(find_min_temp[3]) < min_temp:
min_temp = int(find_min_temp[3])
print("The min temperature is", min_temp, "degrees")`
When I run this code, the maximum temperature is displayed correctly, however, the minimum temperature simply displays '100'. If I delete the max_temp code from the program, the minimum temperature will display correctly. Why is this happening and what can do to fix it?
This is because the position of the read/write pointer within the file points to the end of the file after first for loop.
You can simply write
weather_data.seek(0)
Before second loop
I am having some issues building a histogram.
Here is my code:
distribution = dict()
count = 0
name = input("Enter file:")
handle = open(name)
for line in handle:
line = line.rstrip()
if not line.startswith("From "):
continue
count = count + 1
firstSplit = line.split() # This gets me the line of text
time = firstSplit[5] # This gets me time - ex: 09:11:38
# print(firstSplit[5])
timeSplit = time.split(':')
hr = timeSplit[1] # This gets me hrs - ex: 09
# Gets me the histogram
if hr not in distribution:
distribution[hr[1]] = 1
else:
distribution[hr[1]] = distribution[hr[1]] + 1
print(distribution)
# print(firstSplit[5])
I read the text in, and I split it to get the lines, done by firstSplit. This line of text includes a time stamp. I do a second split to get the time, done by timeSplit.
From here, I try to build the histogram by trying to see if the hour is in the dictionary, if it is, add one, if not, add the hour. But this is where it goes wrong. My output looks like:
Example of Output
Any advise or suggestions would be great!
Seán
You are using an incorrect method to check if the hour is a key in the histogram. Here is the correct way to check:
if not (hr in list(distribution.keys()):
Also, you should be checking if a value is a key, then using the same value as the key that you create / add to. Therefore, the above will now be:
if not (hr[1] in list(distribution.keys()):
These two changes should fix your code and build you a great histogram!
Note: Code is untested
i am using a video with a simple background and prompting an alert text whenever someone passes by.
clear all
myVideoObj = VideoReader('video.avi');
nFrames = myVideoObj.NumberOfFrames;
sound = wavread('somethingwrong.wav');
flag = 1;
% Read one frame at a time.
for i = 2 : nFrames-1
frame1 = read(myVideoObj, i-1); frame2 = read(myVideoObj, i);
diff = abs(rgb2gray(frame1) - rgb2gray(frame2));
if sum(sum(diff)) < 46000
imshow(frame2, [])
drawnow
else
imshow(frame2, [])
text(100, 100, 'Intruder!!!' , 'FontSize',24)
drawnow
end
end
The drawon works. But now im trying to figure out how to do an increment of strings for each person that passes by. How do i start? Thanks in advance
Are you trying to make it so the text increments a counter each time it detects an intruder (so this is included in the "Intruder!!!" message)? If so, you should be able to accomplish this as follows:
You can make a string variable and a counter:
message_string = 'Intruder #';
count = 1;
and then each time you find a new person, you would set a new message string:
total_message = strcat(message_string, num2str(count));
which would be sent to the text function:
text(100, 100, total_message, 'FontSize', 24)
then increment the count.
If this is not an answer to your question, please clarify what you mean by doing an increment of strings for each person that passes by.