You want to know your grade in Computer Science, so write a program
that continuously takes grades between 0 and 100 to standard input
until you input "stop", at which point it should print your average to
standard output.
NOTE: When reading the input, do not display a prompt for the user.
Use the input() function with no prompt string. Here is an example:
grade = input()
grade = input()
count = 0
sum = 0
while grade != "stop":
grade = input()
sum += int(grade)
count += 1
print(sum / count)
Please dont solve it for me, but if you can point out why setting grade as "input()" doesnt work
You input a line as the first operation and then correctly enter the loop only if it isn't "stop".
However, that should then be the value you use for summing rather than immediately asking the user for another value. In your current code, if the user enters "stop", there is no check before attempting to treat it as a number.
So, if you don't want a solution, I'd suggest you stop reading at this point :-)
Couldn't resist, could you? :-)
The solution is to simply move the second input call to the bottom of the loop, not the top. This will do the check on the last thing entered, be that before the loop starts or after the value has been checked and accumulated.
In addition, your print statement is inside the loop where it will print after every entry. It would be better
There's other things you may want to consider as well, such as:
moving your print outside the loop since currently you print a line for every input value. You'll also have to catch the possibility that you may divide by zero (if the first thing entered was "stop").
handling non-numeric input that isn't "stop";
handling numeric input outside the 0..100 range.
Don't use this since you're trying to educate yourself (kudos on you "please don't solve it for me" comment by the way) and educators will check sites like SO for plagiarism, but a more robust solution could start with something like:
# Init stuff needed for calculating mean.
(count, total) = (0, 0)
#Get first grade, start processing unless stop.
grade = input()
while grade != "stop":
# Convert to number and accumulate, invalid number (or
# out of range one) will cause exception and not accumulate.
try:
current = int(grade)
if current < 0 or current > 100:
throw("range")
# Only reaches here if number valid.
total += int(grade)
count += 1
except:
print(f'Invalid input: {grade}, try again')
# Get next grade and check again at loop start.
grade = input()
# If we entered at least one valid number, report mean.
if count > 0:
print(total / count)
the first input does not work, covered by the second input;
when input is "stop", int("stop") is wrong;
When reading the input, do not display a prompt for the user. you should print the ans after the while loop
you can use endless loop and break to solve this problem.
...
while True:
grade = input()
if grade == 'stop':
break
...
print(ans)
Related
I'm new to python and there's a video on Youtube that I watched. I do the exact same code as he but mine doesn't work and I don' understand why.
Here's the code:
MAX_LINES = 3
def deposit():
while True:
amount = input("What would you like to deposit? $")
if amount.isdigit():
amount = int(amount)
if amount > 0:
break
else:
print("Amount must be greater than 0. ")
else:
print("Please enter a number. ")
return amount
def get_number_of_lines():
while True:
lines = input("Enter the number of lines to bet on (1-" + str(MAX_LINES) + ")? ")
if lines.isdigit():
lines = int(lines)
if 1 <= lines <= MAX_LINES:
break
else:
print("Please enter a valid number of lines. ")
else:
print("Please enter a number. ")
return lines
There are 3 problems.
Unindent amount does not match previous indent. I have no idea what does that mean
"return" can be used only within a function. As far as I'm concerned I'm using it in the function, copied the first function then pasted it into the second function and somehow it doesn't work
"lines" is not defined. What dou you mean it's not defined, I define it in the first line of the function
https://www.youtube.com/watch?v=th4OBktqK1I
This video's code what I'm trying to do
I appreciate any help!
I just simply don't understand why it works in one and not the other
You have one space too much in front of while True in function get_number_of_lines().
Yes used in functions to return value
Because function don't get inside while loop (because of indent problem), lines is never defined, probably this was the problem.
So try fix indent and run again
pseudocode
numtodouble=int
result=int
print("")
print("Enter a number you would like to double and press Enter.")
input (numtodouble)
<class 'int'>2
'2'
while numtodouble>0:
result=numtodouble*2
print("2 X", numtodouble, "=", result)
print("")
print("Enter a number you would like to double and press Enter.")
input(numtodouble)
break
print("OK, you entered a value <=0, ending execution.")
Does anyone know where I went wrong with my code? I've been struggling with this for hours.
try:
# input is stored as num_to_double. the input is cast to an int, and the string in input is the prompt
num_to_double = int(input("Enter a number you would like to double and press Enter."))
while num_to_double>0:
result=num_to_double*2
# Format puts the arguments into the curly braces in the order given
print("2 X {} = {}\n".format(num_to_double, result))
# input is cast to int and stored in num_to_double. The text in the input command is the prompt
num_to_double =int(input("Enter a number you would like to double and press Enter."))
# This is otuside the while loop, so this runs when the while loop breaks. The previous break command was making
# the code act not as intended
print("OK, you entered a value <=0, ending execution.")
# This catches if someone inputs a value that is not able to be cast to a string. It's the second half of the Try:
# Except block.
except ValueError as _:
print("A not-a-number was supplied")
This code is far simplier and does what you're trying to do. I assume you're learning python, so some of these things are not the simplest way to do things, like the format function, but are super useful to learn.
num_to_double = 0
result = 0
print("")
num_to_double = int(input("Enter number would you like to double and press enter."))
while num_to_double > 0:
result = num_to_double * 2
print("2 X {} = {}".format(num_to_double, result))
print("")
num_to_double = int(input("Enter number would you like to double and press enter."))
print("OK< you entered a value <=0, ending execution.")
This code is the closest I could do to the pseudocode provided. Declaring variables before they're used here isn't necessary and is messy. It's like the pseudocode wasn't meant to become python. Same with printing blank lines, those should be wrapped into the previous or next print lines.
I have a while statement which works well and I have a whole section of code that asks the user to input how many names they have which will then ask them for a name that amount of times and then each time a name will be entered.
I need the section of the names entered to be error tapped but I don't know how to do it, as I have a while statement and I may need to put another while statement in, although I have error tapped the section for amount of names in numbers.
Also there is code further on with a dictionary and sorts but I need help with the one section of error tapping started at while currentnum part
print("Please enter each name when asked without any spaces.") #The program will post this
print("Please enter each of your names individually also.") #Program will again post this
names = [] #This is the value of names which will be changed depending on the input
currentnum = 0 #Currentnum value is 0
while True: #While loop as it will revert to the start if question answered incorrectly
try:
numofnames = int(input("How many names do you have? "))
except ValueError: #if the input is not an integer or a whole number it will
print("Sorry that was not a valid input please retry")
continue #it will loop back and ask the question again as it says that the unput was not valid
else:
break #If the input is correct then the loop will break and continue to the next section of the program
while currentnum < numofnames: #This means that while currentnum is smaller than input for numofnames it will continue to ask question. This is another loop
currentnum = currentnum + 1 # every time the question is asked it means that currentnum gets 1 added to it and will continue to ask untill it is the same as the input for numofnames
name = str(input("Enter your name: ")) #Name asked to be entered in string
name = name.upper() #This changes all letters to upper case no matter what so there is no error for upper and lower case or a bigger dictionary showing lower and upper case values.
names.append(name)
Yep. The easiest way to describe what you're doing is to use the .isalpha attribute in an if statement. First you will have to def your while loop
Like the following:
def Loop():
name_input_complete = False
while name_input_complete != True:
string = input("Please input :")
string = str(string)
if string.isalpha():
name_input_complete = True
else:
print("Please do not use numbers and spaces")
Loop()
Loop()
Baisically you have to define the loop and then run it. The if statement(which is the part you should add to your loop) then checks if there is nothing other than letters. If true, your done with error trapping and the loop is exited. The program continues outside the loop. If not then the while is repeated because the Loop() function is called again.
Your code looks very good to me. I dont see what input can the user put that could cause an error, since most data in python can be stringed AND names can be pretty much anything!. If you could comment exactly what error could be caused i might be able to help you
Python isn't recognizing any number apart from 1 as an integer. When i enter a number to be multiplied the program will run the except ValueError even though i have entered an integer. This is the code i have.
Total = 0
Tsl = 100
receipt = open("Receipt.txt", "w")
while True:
try:
Prod_Code = input("Enter a code or Done to get your final receipt: ")
if len(Prod_Code) == 8:
int(Prod_Code)
with open("Data Base.txt", "r") as searchfile:
for line in searchfile:
if Prod_Code in line:
print(line)
Quantity = input("What quantity of this product do you want? ")
Total += float(line.split(",")[2] * int(Quantity))
print(Quantity)
print(Total)
receipt.write(line)
elif Prod_Code == "Done":
print("Bye Bye")
print(receipt)
receipt.close
exit()
else:
print("Incorrect length, try again")
except ValueError:
print("You must enter an integer")
The error occurs when i enter any other number than 1 when i enter the quantity. If anyone can see the problem any input will be appreciated
The problem is that
Total += float(line.split(",")[2] * int(Quantity))
multiplies the string line.split(",")[2] by the Quantity converted to integer. And then attempts to convert the resulting string to a float.
Eg, if line.split(",")[2] is '1.2' and Quantity is '3' then
line.split(",")[2] * int(Quantity)
results in '1.21.21.2', which can't be converted to float. :)
Instead do
Total += float(line.split(",")[2]) * int(Quantity)
BTW, you aren't actually closing the receipt file. You're just emitting the method name and discarding it. So change
receipt.close
to
receipt.close()
Even better: use with blocks to open all your files so they get closed automatically.
I should also mention that the plain exit() function is primarily intended for use in the interactive interpreter, and it's not guaranteed to exist in all environments. To ensure portability use sys.exit() instead. OTOH, it's not really needed here, you can just break out of that while loop.
One reason can be in inputing the Promo_Code , you are using input so if your promo code is abcdefgh then you must input it as 'abcdefgh' or "abcdefgh" because input in python 2 cannot take automatic decisions . For sake of simplicity always use raw_input() for inputting strings,
Also in your elif convert reciept.close to reciept.close().
I have been having problems with a block of code in a little project and I can't seem to fix it.
In the below code, I define inputrace() so that a process is carried out where the player types in a number that is above 0 and below 13 (there are 12 choices, each dictated by a number); it also checks for blank lines and strings and has the program state that there is an error and ask for user input again if they are detected. If it passes the check, RaceInp is returned and set to RaceChoice which allows the code below it to assign a Race to the player based on their selection.
#race check
def inputrace():
print ("Input number")
RaceInp = input()
Check = RaceInp
try:
int(RaceInp)
except ValueError:
print("Numbers only!")
inputrace()
if not int(Check)>12 or int(Check)<1:
return RaceInp
print (RaceInp) #this is here so I can check the value returned
Race = "NA"
RaceChoice = inputrace()
print (RaceChoice)
#assign race
if RaceChoice == "1":
Race = "Human"
#continues down to twelve
Everything works when valid strings are put in (any number 1-12), but things break when I purposefully put in an invalid string. It seems like RaceInp only retains the first user input and does not change, even after the function is recalled from an error. That means if I were to put in "a," the program will tell me it is wrong and ask again. However, when I put in "1" in an attempt to correct it, it accepts it but still keeps RaceInp as "a."
Is there any fix to this? I have no clue what's going on.
I appreciate the help and sorry if I got anything wrong in the question!
It seems that the problem is that you put the inputrace in a recursion instead of a loop. Something like this would probably be better:
def input_race():
while True:
print("Input a number between 1 and 12.")
race_input = input()
try:
race_input = int(race_input)
if race_input >= 1 and race_input <= 12:
return race_input
except ValueError:
pass
print ("'{input}' is not a number.".format(input=race_input))
race = "NA"
race_choice = input_race()
if race_choice == 1:
race = "Human"
print(race)