I am writing a program in python3 to keep score of N number of players and am having trouble getting the score to be input correctly from each player. the code in bold is where I am having an issue. The loop closes after I enter the score for the first contestant and i for some reason equals 3 instead of increasing from 0 to 1. I would like 'i' to update as the loop continues so that the code to get scores continues until each player has been scored.
I don't know how to get the result I want. Am I using the wrong loop statement?
I have tried while, if and for statements.
I just started coding Tuesday so any help is greatly appreciated.
import csv
from array import *
names = []
con = int(input("Number of Contestants: "))
maxSurfers = con #number of surfers
while len(names) < maxSurfers:
name = input(" Enter your Name: ")
names.append(name)
print("Contestants")
print(names)
else:
print("Thank You for Participating!\n")
print("Sign up is now closed")
**score = array('f', [])
i = 0
n = int(input("Number of Waves for "+names[i]+": "))
while i != n:
x=float(input("Enter score for each wave: "))
score.append(x)
i = i + 1
print(i)
print("Winner being decided.")**
outputs:
Number of Contestants: 2
Enter your Name: frank
Contestants
['frank']
Enter your Name: bart
Contestants
['frank', 'bart']
Thank You for Participating!
Sign up is now closed
Number of Waves for frank: 3
Enter score for each wave: 9.6
Enter score for each wave: 7.8
Enter score for each wave: 7.2
3
Winner being decided.
The issue is that you have a loop for each wave but not an outer loop for each name. You also only have one score list so if you did have an outer loop you'd just have a score list with a bunch of numbers and no way to connect them to each player. You should look into python dictionaries they will likely make your life a lot easier. Also when you want a python loop for a range of numbers the standard way is with something like for counter in range(10): which counts from 0 to 9.
try something like:
scores = {}
for name in names:
numWaves = int(input("Number of Waves for "+name+": "))
newScores = []
for i in range(numWaves):
newScores.append(float(input("Enter score for each wave: ")))
scores[name] = newScores
Related
I am trying to learn python since 2 days now and I am challenging myself with this little python projects from this website: https://www.upgrad.com/blog/python-projects-ideas-topics-beginners/#1_Mad_Libs_Generator
I am at the second game now (number guessing game).
The instruction is as follows:
'''Make a program in which the computer randomly chooses a number between 1 to 10, 1 to 100, or
any range. Then give users a hint to guess the number. Every time the user guesses wrong,
he gets another clue, and his score gets reduced. The clue can be multiples, divisible,
greater or smaller, or a combination of all.
You will also need functions to compare the inputted number with the guessed number, to compute
the difference between the two, and to check whether an actual number was inputted or not in this python project.'''
import random
print("Welcome to the number game. A random number will be generated and you can guess which one it is.")
print("You got three tries.")
number = random.randint(1, 99)
guess = "" # var to store users guess
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != number and not out_of_guesses:
if guess_count < guess_limit:
guess = int(input("Enter a guess: "))
guess_count += 1
if guess < number:
print("Your guess is too small. Try again.")
elif guess > number:
print("Your guess is too high. Try again.")
else:
out_of_guesses = True
if out_of_guesses:
print("You are out of guesses. You loose!")
else:
print("Your guess is correct. You Won!")
The output looks like this:
Welcome to the number game. A random number will be generated and you can guess which one it is.
You got three tries.
Enter a guess: 78
Your guess is too high. Try again.
Enter a guess: 28
Your guess is too small. Try again.
Enter a guess: 29
**Your guess is too small. Try again.**
You are out of guesses. You loose!
My problem is the line marked in strong. Actually, after the user entered the third try and did not guess the correct answer, I don't want the line "your guess is too ..." to be displayed. However, before the user is out of tries, I do want it to be displayed.
Do you got any hints on how to adjust the code?
Also, I did understand the concept of try and except, but don't really know where exactly to add it to make the game more "smooth" with regard to entering a wrong input type.
Kind Regards
Given the current code structure, you can avoid printing the hints on the last guess by adding an additional check in the guess and number comparison.
Regarding exception handling, the crash points of the program involve the comparison between user input and the number. Adding exception handling around the integer conversion of user input seems appropriate. Doing this before incrementing guess_count and a continue to allow for another user input will allow the game to run for 3 valid inputs.
The _ variable being used to refer to the exception is a 'throwaway' variable - this is just a conventional name. In an interpreted session, however, _ would store the return value of the previously executed statement.
import random
print("Welcome to the number game. A random number will be generated and you can guess which one it is.")
print("You got three tries.")
number = random.randint(1, 99)
guess = "" # var to store users guess
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != number and not out_of_guesses:
if guess_count < guess_limit:
try:
guess = int(input("Enter a guess: "))
except ValueError as _:
print('Wrong input type')
continue
guess_count += 1
if guess < number and guess_count != guess_limit:
print("Your guess is too small. Try again.")
elif guess > number and guess_count != guess_limit:
print("Your guess is too high. Try again.")
else:
out_of_guesses = True
if out_of_guesses:
print("You are out of guesses. You lose!")
else:
print("Your guess is correct. You Won!")
The program will ask for the number of grade scores to average, it will then loop to accept the given number of grade scores. Once all scores are entered, the program will average the grades by adding up all the grade scores and dividing by the number of scores entered (Note: You will need to add up the grades as you are looping to enter them.) Once the average is calculated, the program will see what letter grade should be assigned to the average based on
the scale provided below.
can someone help me create a loop with an accumulator? This is what I have done so far:
Num = int(input("Enter the number of scores: "))
score = int(input("Enter a score: "))
Average = (score/Num)
if (Average >= 93):
print("A")
elif(Average >= 85):
print("B")
elif(Average >= 77):
print("C")
elif(Average >= 69):
print("D")
elif(Average <= 68):
print("F")
I am assuming you write your code in python based on the syntax you give. You could try to make a pseudo code for it first before you actually implementing it.
declaring totalScore = 0
declaring average = 0
declaring score
# input number of lesson will be counted to enter the score
input numOfLesson
# Looping to enter the score of each student to list
for i in range(numOfLesson):
input score
total = total + score
# you got the total score, and what you have to do is to divide it with numOfLesson
# to get the average
average = total / numOfLesson
now you know the step by step on how to do it, what you have to do is to convert it to the code
I am new to ruby and have this program that takes in a number of names and sorting them into pairs of two, and throwing the odd person in a random group. Sometimes it works perfect, sometimes it throws the extra person into an array of their own, and im not sure why. I know there is a cleaner way to do this but Im just trying to understand how the code works. For example it should return "Apple" "Banana" "Orange" as ["Banana", "Orange", "Apple"] and will most of the time, but sometimes it give me ["Banana","Orange",] ["Apple"] Any advice?
def randomArray
classNames = []
puts "Please enter a list of names to sort"
while true
input = gets.chomp
break if input.empty?
classNames << input
end
classRandom = classNames.shuffle
splitNames = classRandom.each_slice(2).to_a
arrayPos = 0
splitNames.length.times do
if splitNames[arrayPos].length == 2
arrayPos+=1
else splitNames[arrayPos].length == 1
splitNames.sample << splitNames[arrayPos].pop
arrayPos+=1
end
end
x = 0
splitNames.length.times do
break if splitNames[x].empty?
puts "Group number #{x+1} is #{splitNames[x]}"
x+=1
end
end
randomArray
Your problem is this: splitNames.sample << splitNames[arrayPos].pop
sample can return any element of the array, including the element that has the odd person you're trying to assign! So if it samples that person, it removes them from their group of 1 and then adds them right back in.
To fix it, take advantage of the fact that either all groups will be pairs, or the last group will have a single person. Don't iterate over the array, just check splitNames[-1]. If they are alone, add them to splitNames[0...-1].sample.
I'm working on an exercise in Swift 3 Playground.
I have an array called sums with a bunch of numbers in. I want to cycle through each of the array items and print 'The sum is: x' but I'm getting a generic error with the print command.
var i = 0
repeat {
print ("the sum is: \(sums[i])")
i = i + 1
} while i <= sums.count
Does anyone know what I'm doing wrong?
It must be done in a repeat loop as that's what the exercise is asking for.
sums.count will give you the size of the array.
Arrays are 0-indexed in Swift. You're accessing out of the array range.
Check for sums.count - 1 or:
var i = 0
repeat {
print ("the sum is: \(sums[i])")
i = i + 1
} while i < sums.count
I have InputBox asking user to input 5 numbers then trying to add each number to the array size 5. But I am getting error. The loop is adding numbers to the array Can anyone help?
You are aware that split makes the array.
Message is your array not arraynums.
Your for loop is 0 to 5 which is 6.
Read documentation, e.g. Split Function
Dim i
Dim arrayNums
Dim message
Dim userInput
message = InputBox("Please Enter 5 numbers!")
arrayNums = Split( message)
For i=0 To ubound(arrayNums)
msgbox(arrayNums(i))
Next
You're on the right track. You can just Split the results and that will create an array. Then, you can test the UBound() of the array to see if you have your 5 numbers.
Here's a loop that continues until 5 numbers are entered:
Do
a = Split(InputBox("Please enter 5 numbers, separated by spaces:"))
Loop Until UBound(a) = 4
' Now, a(0) through a(4) are your 5 numbers.
Of course, you'll probably also want to validate the 5 entries to ensure they're actually numbers. The IsNumeric() function can help.