I'm doing a small program that has the job of a school's subjects and marks management.
HOW IT WORKS
I've created 4 variables: a dictionary, an initialized empty string(for subjects) and two initialized empty integers(one for the marks, the other one for the subjects number). The program asks the user to input the numbers of subjects to work with. After that, it enters in a for loop that repeats itself in the range of the subjects number. And it works fine. Now the problem comes when the user inputs a mark over the range specified. Let's suppose we have a school and the marks we can input are between 1 and 10. The user can't write 11,12 and so on..
CODE
pagella = {}
materia = ""
voti = 0
length = 0
print("Insert the number of subjects, the subjects and the marks-")
num = int(input("Number of subjects: "))
length = len(pagella)
length = num
for i in range(length):
materia = input("Subject: ")
voto = eval(input("Mark: "))
if(voto > 10):
print("Number between 1 and 10")
else:
pagella[materia] = voto
print(pagella)
As you can see, there's the for loop that asks the user to input the subjects and the marks in the range of num(the number of subjects). If I try to input 12 on a mark, the program tells me to input a mark between 1 and 10 so it repeat again the cycle from the beginning. But the problem is that in this case, if I want to have 3 subjects with 3 marks (that means 3 iterations), one is lost because of the wrong mark, so I will not have 3 subjects and marks to input correctly, but only 2.
I hope I've explained correctly everything and someone can help me!
Thanks in advice
I suggest you the following solution that handles also the cases of non-numeric values as input for marks:
pagella = {}
materia = ""
length = 0
print("Insert the number of subjects, the subjects and the marks-")
num = int(input("Number of subjects: "))
length = num
for i in range(num):
# Ask for subject
materia = input("Subject: ")
# Ask for mark until the input is correct
voto = None
while (voto is None):
try:
voto = int(input("Mark: "))
if (voto > 10):
print("Number between 1 and 10")
voto = None
except:
print("Pleaser enter an integer")
# Store in dictionary pagella (if mark is correct)
pagella[materia] = voto
print(pagella)
Related
I'm new to python and I really need some help, the question is a program asks the user to enter a name and number of choices. If the number of choices is less than 10, then display their name as much as that number. If not, display the message “Number entered more than 10” five times.
How to display the else condition "Number entered more than 10” five times?
name = input('What is your name: ')
number = int(input('Enter a number: '))
for i in range(number):
if (number > 0) and (number <= 10):
print(name)
else:
print("Number entered more than 10")
Just use separate for loops in different conditions:
name = input('What is your name: ')
number = int(input('Enter a number: '))
if number > 0 and number <= 10:
for i in range(number):
print(name)
else:
for i in range(5):
print("Number entered more than 10")
You can use the for loop:
for i in range(10):
print("Message")
This one prints "Message" 10 times. I leave the rest as an exercise :)
I have just added what is needed to your attempt. See below
# read your inputs
name = input('What is your name: ')
number = int(input('Enter a number: '))
if 0<number<=10:
# if in range, print it that many times
print("\n".join([name]*number))
else:
# if not print 5 times
print("\n".join(["Number entered more than 10"]*5))
You could try:
else:
print("Number entered more than 10" * 5)
or, if you'd like to have prints in separate lines:
else:
print("Number entered more than 10\n" * 5)
the \n stands for new line to be added after every line.
This is the output of the code I am trying to write. I have seen this done for C++, but not python with a dictionary. The key here is the dictionary is not optional. I need to use it to fulfill the assignment.
ID Candidate Votes Received % of Total Vote
1 Johnson 5000 55.55
2 Miller 4000 44.44
Total 9000
and the winner is Johnson!
I need to use a dictionary and a loop to create this. However, I am stuck on 3 points.
1.The percent- current code returns the percent before it has the whole total ex: first candidate always has 100%.
2. Declare a winner- code finds the max votes and returns the number value but I need it to return the name.
3. How to format the dictionary values so it lines up under the header. I don't think is possible, but it must be a requirement to use a dictionary for a reason. I am thinking I need to make a copy of the dictionary and format that?
Here is what I have so far:
totalVotes=[]
dct = {}
i = 1
while(True):
name = input('Please enter a name: ')
if name == '':
break
votes = input('Please enter vote total for canidate: ')
totalVotes.append(votes)
totalVotesInt= map(int, totalVotes)
total = sum(totalVotesInt)
dct[i] = {name,votes,int(votes)/total*100}
i += 1
header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print(header)
print("\n".join("{}\t{}".format(key, value) for key, value in dct.items()))
print('Total '+str(total))
print('The Winner of the Election is '+max(totalVotes))
Which returns:
Please enter a name: Smith
Please enter vote total for canidate: 100
Please enter a name: Frieda
Please enter vote total for canidate: 200
Please enter a name: West
Please enter vote total for canidate: 10
Please enter a name:
ID Name Votes % of Total Vote
1 {'Smith', '100', 100.0}
2 {'Frieda', 66.66666666666666, '200'}
3 {3.225806451612903, '10', 'West'}
Total 310
The Winner of the Election is 200
You add the number of each candidates votes at the same time you calculate the percent vote for each candidate. You need to find the total votes first, then divide each candidates votes by the total
You are returning the max of a list of integers. Obviously you aren't going to get a string. You need some way to connect the number votes with the candidate.
Don't bother. You can try to figure out how many tabs you need to get the whole thing lined up, but from experience, it is basically impossible. You could separate them with commas and open it in excel as a csv, or you could just make the user figure out what number goes with what.
The other answer uses data tables, so I will take another, more vanilla and cool approach to getting what you want.
class candidate():
def __init__(self, name, votes):
self.name = name
self.votes = int(votes)
def percentvotes(self, total):
self.percent = self.votes/total
def printself(self, i):
print('{}\t{}\t\t{}\t\t{}'.format(i, self.name, self.votes, self.percent))
def getinput():
inp = input('Please enter your candidates name and votes')
return inp
candidates = []
inp = getinput()
s = 0
while inp != '':
s+=1
candidates.append(candidate(*inp.split(" ")))
inp = getinput()
for c in candidates:
c.percentvotes(s)
candidates.sort(key = lambda x:-x.percent)
print('ID\tname\t\tvotes\t\tpercentage')
for i, c in enumerate(candidates):
c.printself(i+1)
I have added very little changes to your code to make it work:
I have mentioned the changes as comments in the code.
Edit: It's more efficient to use objects for each candidate if you require scaling in the future.
totalVotes=[]
dct = {}
i = 1
while(True):
name = input('Please enter a name: ')
if name == '':
break
votes = input('Please enter vote total for canidate: ')
totalVotes.append(votes)
totalVotesInt= map(int, totalVotes)
total = sum(totalVotesInt)
# I change it to a list so it's much easier to append to it later
dct[i] = list((name,int(votes)))
i += 1
# I calculate the total percent of votes in the end and append to the candidate
maxVal = 0
for i in range(1, len(dct) + 1):
if dct[i][1] > maxVal:
maxInd = i
dct[i].append(int((dct[i][len(dct[i]) - 1]) / total * 100))
header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print(dct)
print(header)
print("\n".join("{}\t{}".format(key, value) for key, value in dct.items()))
print('Total '+str(total))
print('The Winner of the Election is '+ dct[maxInd][0]))
I believe that this is the solution you are looking for. Just change the input statements in case you are using Python 2.x. Using Dataframe, the output will be exactly how you wanted.
import pandas as pd
import numpy as np
df = pd.DataFrame(columns=["Candidate", "Votes Received","Percentage of total votes"])
names=list()
votes=list()
while True:
name = str(input("Enter Name of Candidate."))
if name=='':
break
else:
vote = int(input("Enter the number of votes obtained."))
names.append(name)
votes.append(vote)
s=sum(votes)
xx=(votes.index(max(votes)))
myArray = np.array(votes)
percent = myArray/s*100
for i in range(len(names)):
df1 = pd.DataFrame(data=[[names[i],votes[i],percent[i]]],columns=["Candidate", "Votes Received","Percentage of total votes"])
df = pd.concat([df,df1], axis=0)
df.index = range(len(df.index))
print (df)
print ("Total votes = ",s)
print ("The man who won is ",names[xx])
I have to use the append method to get info from the user however I am only suppose to take 10 lines from the user and not suppose to ask them if they have another set of information to enter. Can anyone tell me how to stop a list_append without asking the user to stop it?
The following is my code in python.
#set limit
num_grades = 10
def main():
#making of the list
grades = [0] * num_grades
#hold the index
index = 0
#ask the user for the info
print('Please enter the final grades for 10 students: ')
#put the info into the list with a loop
while index < num_grades:
grade = input('Enter a grade: ')
grades.append(grade)
main()
Your given code is missing only one thing: you forgot to increment the index each time through the loop.
Do this better with a for loop:
for index in range(num_grades):
grade = input('Enter a grade: ')
grades.append(grade)
Your issue is that you are forgetting to increment index inside the while loop you have created, and hence it is always zero.
Just adding a index += 1 line inside the loop will fix your issue.
As stated by #Prune, a for loop would be much more suitable in this situation.
This kind of thing is easily handled by for loops. Here is your code edited:
num_grades = 10
def main():
#making of the list
grades = []
#ask the user for the info
print('Please enter the final grades for 10 students: ')
#put the info into the list with a loop
for i in range(num_grades):
grade = input('Enter a grade: ')
grades.append(grade)
main()
As #Wintro has mentioned, the issue was that you forgot to increment the index inside the while loop.
So the working solution looks as follows:
num_grades = 10
def main():
#making of the list
grades = [0] * num_grades
#hold the index
index = 0
#ask the user for the info
print('Please enter the final grades for 10 students: ')
#put the info into the list with a loop
while index < num_grades:
grade = input('Enter a grade: ')
grades.append(grade)
index += 1
main()
Whenever i run my program is print the number 10 randomly and i don't know where its coming from. Anyone help me out?
def main():
phoneNumber=int(input("Enter a 10 digit unformatted telephone number in the format ##########: "))
tempNumber = []
phoneNumber = str(phoneNumber)
length = len(phoneNumber)
index=0
print(length)
if (length ==10):
print("The unformatted number is: ",phoneNumber)
else:
print("The telephone number was NOT entered in unformatted format ##########.")
for num in phoneNumber:
tempNumber.append(num)
tempNumber.insert(0,"(")
tempNumber.insert(4,")")
tempNumber.insert(8,"-")
phoneNumber = ''.join(tempNumber)
print("The formatted number is: ",phoneNumber)
main()
You are printing the length of the input given by user, so that's why 10 is printed out (see statement no. 6 inside main() function).
phoneNumber = str(phoneNumber)
length = len(phoneNumber)
index = 0
print(length) # <--- this statement is printing the length of the input
The following code is my attempt at simulating a lottery.
import random
def lottery(numbers):
lottoNumbers = [randint('0,100') for count in range(3)]
if numbers == lottoNumbers:
print('YOU WIN $10,000')
else:
print('YOU LOSE,DUN DUN DUNNN!')
return numbers
def main():
numbers = int(input('Enter a number: '))
if numbers == lottoNumbers:
numbers = lottery(numbers)
else:
numbers = lottery(numbers)
main()
Hey guys I've gotten this far with the help you've given me. I'm trying to write the code so that 3 lotto numbers at random will be chosen. Then the user must enter 3 of his/her own lotto numbers. If they get all 3 correct then they win the whole prize, if they get the 3 numbers but not in the correct order they win some of the prize. Obviously if they guess all wrong then a print statement would state that. What I'm confused about is how can I write the code so that the user can enter 3 numbers to try matching the random lottery numbers. I also want to print the 3 lottery numbers after the user inputs his/her choices. Any ideas guys?
Thanks for your help everyone.
You seem a bit confused about what the role of the arguments in a function are. You've said that your randm function takes the argument "number", but then you haven't actually used it anywhere. The next time number appears, you've assigned it a completely new value, so any value passed to randm isn't actually being used.
Also, the function is trying to return x, when x hasn't been assigned within the function. Either you already have a global variable called x already defined, in which case the function will just return that variable, or the function will just fail because it can't find the variable x.
Here's a quick example I've done where you pass their three numbers as a list as an argument to the function.
import random
theirNumbers=[5,24,67]
def checkNumbers(theirNumbers):
lottoNumbers = []
for count in range(3)
lottoNumbers.append(random.randint(0,100))
winning = True
for number in theirNumbers:
if not each in lottoNumbers: winning=False
if winning == True: print("Winner!")
There are a few things wrong with your implementation, to name a few:
if you are trying to compare the output of the function randm to x, you will need to include a return value in the function, like so:
def randm():
return return_value
You appear to be printing all the values but not storing them, in the end you will only end up with the final one, you should attempt to store them in a list like so:
list_name = [randint(0,100) for x in range(x)]
This will generate randint(0,100) x times in a list, which will allow you to access all the values later.
To fix up your code as close to what you were attempting as possible I would do:
import random
def randm(user_numbers):
number = []
for count in range(3):
number.append(random.randint(0, 100))
print(number)
return user_numbers == number
if randm(x):
print('WINNER')
If you are looking for a very pythonic way of doing this task,
you might want to try something like this:
from random import randint
def doLotto(numbers):
# make the lotto number list
lottoNumbers = [randint(0,100) for x in range(len(numbers))]
# check to see if the numbers were equal to the lotto numbers
if numbers == lottoNumbers:
print("You are WinRar!")
else:
print("You Lose!")
I'm assuming from your code (the print() specifically) that you are using python 3.x+
Try to post your whole code. Also mind the indentation when posting, there it looks like the definition of your function would be empty.
I'd do it like this:
import random
def lottery():
win = True
for i in range(3):
guess = random.randint(1,100)
if int(raw_input("Please enter a number...")) != guess:
win = False
break
return win
Let so do this in few steps.
First thing you should learn in writing code is to let separate pieces of code( functions or objects) do different jobs.
First lets create function to make lottery:
def makeLottery(slotCount, maxNumber):
return tuple(random.randint(1,maxNumber) for slot in range(slotCount))
Next lets create function to ask user's guess:
def askGuess(slotCount, maxNumber):
print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
while True: #we will ask user until he enter sumething suitable
userInput = raw_input()
try:
numbers = parseGuess(userInput,slotCount,maxNumber)
except ValueError as err:
print("please ensure your are entering integer decimal numbers separated by space")
except GuessError as err:
if err.wrongCount: print("please enter exactly {count} numbers".format(count = slotCount))
if err.notInRange: print("all number must be in range from 1 to {max}".format(max = maxNumber))
return numbers
here we are using another function and custom exception class, lets create them:
def parseGuess(userInput, slotCount,maxNumber):
numbers = tuple(map(int,userInput.split()))
if len(numbers) != slotCount : raise GuessError(wrongCount = True)
for number in numbers:
if not 1 <= number <= maxNumber : raise GuessError(notInRange = True)
return numbers
class GuessError(Exception):
def __init__(self,wrongCount = False, notInRange = False):
super(GuessError,self).__init__()
self.wrongCount = wrongCount
self.notInRange = notInRange
and finally function to check solution and conratulate user if he will win:
def checkGuess(lottery,userGuess):
if lottery == userGuess : print "BINGO!!!!"
else : print "Sorry, you lost"
As you can see many functions here uses common data to work. So it should suggest you to collect whole code in single class, let's do it:
class Lottery(object):
def __init__(self, slotCount, maxNumber):
self.slotCount = slotCount
self.maxNumber = maxNumber
self.lottery = tuple(random.randint(1,maxNumber) for slot in range(slotCount))
def askGuess(self):
print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
while True: #we will ask user until he enter sumething suitable
userInput = raw_input()
try:
numbers = self.parseGuess(userInput)
except ValueError as err:
print("please ensure your are entering integer decimal numbers separated by space")
continue
except GuessError as err:
if err.wrongCount: print("please enter exactly {count} numbers".format(count = self.slotCount))
if err.notInRange: print("all number must be in range from 1 to {max}".format(max = self.maxNumber))
continue
return numbers
def parseGuess(self,userInput):
numbers = tuple(map(int,userInput.split()))
if len(numbers) != self.slotCount : raise GuessError(wrongCount = True)
for number in numbers:
if not 1 <= number <= self.maxNumber : raise GuessError(notInRange = True)
return numbers
def askAndCheck(self):
userGuess = self.askGuess()
if self.lottery == userGuess : print "BINGO!!!!"
else : print "Sorry, you lost"
finally lets check how it works:
>>> lottery = Lottery(3,100)
>>> lottery.askAndCheck()
take a guess, write 3 numbers separated by space from 1 to 100
3
please enter exactly 3 numbers
1 10 1000
all number must be in range from 1 to 100
1 .123 asd
please ensure your are entering integer decimal numbers separated by space
1 2 3
Sorry, you lost
>>> lottery = Lottery(5,1)
>>> lottery.askAndCheck()
take a guess, write 5 numbers separated by space from 1 to 1
1 1 1 1 1
BINGO!!!!