I am very newbie to programming and stack overflow. I choose python as my first language. Today as I was writing some code to refresh and to improve my skills I wrote a little program. But with complete errors.
Here is the Program
a = [1 , 2, 3]
def list_append():
numbers = int(raw_input("Enter the number please"))
a.append(numbers)
print a
def average(list):
for marks in list:
print marks
total = float(sum(list))
total = total / len(list)
print ("Your total average is : %d" %total )
def loop():
add_numbers = raw_input("Do you want to add another number")
if add_numbers == ("y"):
return list_append()
else:
return average()
while True:
loop()
print average(a)
Basically the function of this program is to ask user for the input of the number. Then append to the list and then show the average which is an easy one.
But I want the program to stop after the first input and ask user if they want to give another input ?
Can't understand where is the problem. ** I am not asking for the direct solution. I would rather want an explanation than the solution itself.**
Following is missing in your code:
Need to break any loop, your while loop in going into infinite loop.
while True:
loop()
2. Handle exception during type casting.
numbers = int(raw_input("Enter the number please"))
Create user enter number list in loop function and pass to list_append function to add numbers.
Also return from the loop function to pass argument into average function.
code:
def list_append(numbers):
while 1:
try:
no = int(raw_input("Enter the number please:"))
numbers.append(no)
break
except ValueError:
print "Enter only number."
return list(numbers)
def average(number_list):
avg = float(sum(number_list))/ len(number_list)
return avg
def loop():
numbers = []
while 1:
add_numbers = raw_input("you want to add number in list(Y):")
if add_numbers.lower()== ("y"):
numbers = list_append(numbers)
else:
return list(numbers)
numbers = loop()
avg = average(numbers)
print "User enter numbers:", numbers
print "average value of all enter numbers:", avg
output:
vivek#vivek:~/Desktop/stackoverflow$ python 17.py
you want to add number in list(Y):y
Enter the number please:10
you want to add number in list(Y):y
Enter the number please:e
Enter only number.
Enter the number please:20
you want to add number in list(Y):Y
Enter the number please:30
you want to add number in list(Y):n
User enter numbers: [10, 20, 30]
average value of all enters numbers: 20.0
vivek#vivek:~/Desktop/stackoverflow$
do not use variable names which are already define by python
e.g. list
>>> list
<type 'list'>
>>> list([1,2,3])
[1, 2, 3]
>>> list = [2]
>>> list([1,2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>>
a = []
def average(list):
total = float(sum(list))
total = total / len(list)
print ("Your total average is : %d" %total )
while True:
numbers = raw_input("Enter the number please or 'q' to quit : ")
if numbers == "q":
average(a)
break
else:
a.append(int(numbers))
Hope this helps
Related
I want to make an calculator for average but i'm facing some issues. I want the numbers entered by the users come as a print statement but it is just throwing the last entered value.Here is my code.
numlist = list()
while True:
inp = input(f"Enter a number, (Enter done to begin calculation): ")
if inp == 'done':
break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print(f"The Entered numbers are: ", inp)
print(f"average is = ", average)
Solution
we can print the list
numlist = list()
while True:
inp = input(f"Enter a number, (Enter done to begin calculation): ")
if inp == 'done':
break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print(f"The Entered numbers are: {numlist}")
print(f"average is = ", average)
As I understand, you want to print all the user inputs, however, as I see in your code, you are printing just a value but not the storing list, try to change your code to print(f"The Entered numbers are: ", numlist)
You are telling the user that their entered numbers are the last thing they typed in input, which will always be "done" because that is what breaks out of the loop. If you want to print the entered numbers; print numlist instead of inp.
I need to modify my program so it includes a prime read with a loop. the document is saying for my getNumber function it should ask the user only to input a number between 2 and 30, the getScores function should ask the user to input a number between 0 and 100. it they don't get a number between that it should tell them re enter a number. I don't get any errors when running the program but not sure what I am missing in order to make sure its running properly to include the re enter a number part. here is the code:
# main
def main():
endProgram = 'no'
print
while endProgram == 'no':
totalScores = 0
averageScores = 0
number = 0
number = getNumber(number)
totalScores = getScores(totalScores, number)
averageScores = getAverage(totalScores, averageScores, number)
printAverage(averageScores)
endProgram = input('Do you want to end the program? yes or no ')
while not (endProgram != 'yes' or endProgram != 'no'):
print('Enter yes or no ')
endProgram = input('Do you want to end the program? (yes or no )')
# this function will determine how many students took the test
def getNumber(number):
number = int(input('How many students took the test: '))
return number
while number < 2 or number > 30:
print('Please enter a number between 2 and 30')
number = int(input('How many students took the test: '))
# this function will get the total scores
def getScores(totalScores, number):
for counter in range(0, number):
score = int(input('Enter their score: '))
return totalScores
while score < 0 or score > 100:
print('Please enter a number between 0 and 100')
score = int(input('Enter their score: '))
return score
# this function will calculate the average
def getAverage(totalScores, averageScores, number):
averageScores = totalScores / number
return averageScores
# this function will display the average
def printAverage(averageScores):
print ('The average test score is: ', averageScores)
# calls main
main()
First suggestion is to change this:
number = int(input('How many students took the test: '))
reason is that, as it is written, this takes the user input and implicitly assumes that it can be cast to an int. What happens if the user enters "hello, world!" as input? It is necessary to take the user input first as a string, and check if it would be valid to convert it:
number = input("enter a number:")
if number.isdecimal():
number = int(number)
Next, the function as a whole has some structural problems:
def getNumber(number):
number = int(input('How many students took the test: '))
return number
while number < 2 or number > 30:
print('Please enter a number between 2 and 30')
number = int(input('How many students took the test: '))
number is passed in as an argument to getNumber. Then the name number is reassigned to the result of reading the user input, and returned... Make sure you understand what the return statement does: once the control flow reaches a return statement, that function terminates, and it sends that value back to the caller. So your while loop never runs.
Maybe this would work better:
def getNumber():
while number := input("enter a number"):
if number.isdecimal() and int(number) in range(0, 31):
return int(number)
print('Please enter a number between 2 and 30')
If the given number is less than the 2, it asks to reenter the number by using recursion.
I've first given 2 and then after recursion, I gave 3, but the output is still 2.
How to output 3?
def inexpno():
exp = int(input("Enter the Experiment n.o : ")) # Takes a exp number
if exp<=2: # Enter your completed experiment here
print("It is completed Correction for both Record and Observation\n\n")
print("Do you want to select another experiment")
we = input("")
if we == "yes" or we == "YES":
inexpno() # TO CHANGE
else:
exit()
return exp
print(inexpno())
Currently you don't save the return value from inexpno() in the recursive call on line 8. You simply need to save it as exp:
exp = inexpno()
Just change your recursive line to
return inexpno()
I'm very new to programming, just started working my way through a Python course. I've been looking through the course material and online to see if there's something I missed but can't really find anything.
My assignment is to make a chatbot that takes input and summarizes the input but also calculates the average. It should take all the input until the user writes "Done" and then terminate and print the results.
When I try to run this:
total = 0
amount = 0
average = 0
inp = input("Enter your number and press enter for each number. When you are finished write, Done:")
while inp:
inp = input("Enter your numbers and press enter for each number. When you are finished write, Done:")
amount += 1
numbers = inp
total + int(numbers)
average = total / amount
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
I get this error:
Traceback (most recent call last):
File "ex.py", line 46, in <module>
total + int(numbers)
ValueError: invalid literal for int() with base 10: 'Done'
From searching around the forums I've gathered that I need to convert str to int or something along those lines? If there are other stuff that need to be fixed, please let me know!
It seems that the problem is that when the user types "Done" then the line
int(numbers) is trying to convert "Done" into an integer which just won't work. A solution for this is to move your conditional
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
higher up, right below the "inp = " assignment. This will avoid that ValueError. Also add a break statement so it breaks out of that while loop as soon as someone types "Done"
And finally I think you are missing an = sign when adding to total variable.
I think this is what you want:
while inp:
inp = input("Enter your numbers and press enter for each number. When you are finished write, Done:")
if inp == "Done":
print("the sum is {0} and the average is {1}.". format(total, average))
break
amount += 1
numbers = inp
total += int(numbers)
average = total / amount
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!!!!