Beginner Programmer here. I'm trying to write a program that will ask a user for a quiz grade until they enter a blank input. Also, I'm trying to get the input to go from displaying "quiz1: " to "quiz2: ", "quiz3: ", and so on each time the user enters a new quiz grade. Like so:
quiz1: 10
quiz2: 11
quiz3: 12
Here's what I've written so far:
grade = input ("quiz1: ")
count = 0
while grade != "" :
count += 1
grade = input ("quiz ", count, ": ")
I've successfully managed to make my program end when a blank value is entered into the input, but when I try to enter an integer for a quiz grade I receive the following error:
Traceback (most recent call last):
File "C:\Users\Kyle\Desktop\test script.py", line 5, in <module>
grade = input ("quiz ", count, ": ")
TypeError: input expected at most 1 arguments, got 3
How do I include more than one argument inside the parenthesis associated with the grade input?
The input function only accepts one argument, being the message. However to get around it, one option would be to use a print statement before with an empty ending character like so:
.
.
.
while grade != "":
count += 1
print("quiz ", count,": ", end="")
grade = input()
Use .format, e.g.:
count = 0
while grade != "" :
count += 1
grade = input('quiz {}:'.format(count))
Of course, it is easy to make the variable within the str () function to convert it from a number to a string and to separate all the arguments using "+" and do not use "-" where programmatically when using "+" Python will be considered as one string
grade = input ("quiz 1: ")
count = 1
while grade != "" :
count += 1
grade = input ("quiz "+ str(count) + ": ")
Related
I'm creating a simple interactive story game where I ask the user to input and display to them some sentences. what I want to do is ask the user where they're from and if they enter an int instead of a string. I would like to repeatedly ask where they're from without the user inputting an int. I've tried if and while loops and it seems not to work for me
import time
name = input("what is your name? ")
def greeting (name):
print("hhhmmm..... is that so?")
time.sleep(0)
x = input("Well " + name + " where have you been all these years?")
place_char = ""
while True:
if x == place_char:
break
# I want to keep asking for location until the user put a string or char not a number
print("please enter a location ")
print("So " + name + " you're telling me that you've been at " + x + " this entir time?")
greeting(name)
One method is to use isalpha() to return True if all characters in the alphabet:
x.isalpha()
If this returns False, ask for a new input and continue the while loop.
while x.isalpha() == False:
x = input("please enter a location ")
#This program calculates the average of integer entered
#Once the use press "S".
#"S" is the sentinel
COUNT= 0
SUM= 0
INT=1
Sentinel = "S"
print('Enter test scores as integers, or enter S to get average.')
INT=input('Enter integer: ') # input received as a string to allow for the entry of "S"
#Continue processing as long as the user
#does not enter S
while INT!= Sentinel:
INT=input('Enter integer: ')
I=int(INT) #attempting to format the input(INT) as an integer
COUNT= + 1
SUM = COUNT + I
if INT == Sentinel:
AVRG= SUM/(COUNT-1)
I keep getting this error message :
Traceback (most recent call last):
File "C:\Users\joshu\Documents\COP100 Python\practice examples\program4-13.py", line 16, in
I=int(INT)
ValueError: invalid literal for int() with base 10: 'S'
Your code is assuming that the user will always enter a numeric value.
This line will accept any data entered by the user. It could be numeric or non-numeric.
INT=input('Enter integer: ') # input received as a string to allow for the entry of "S"
Before you convert the data into integer, check if the value is numeric. If it is not, then you may want to send an error message back to the user.
I=int(INT) #attempting to format the input(INT) as an integer
You can do that by doing:
if INT.isnumeric():
I = int(INT)
else:
print ('not a numeric value')
I am assuming that users will enter only integers. The above code will work only for integers. If you want to check for floats, then use a try: except statement.
Also, your computation of SUM to get the average is incorrect. You shouldn't add COUNT to SUM. You should only add I to SUM while incrementing COUNT.
Also don't try to use variable names as sum, int (even if it is uppercase).
Here's a working code for you to try.
count = 0
total = 0
Sentinel = "S"
#Continue processing as long as the user does not enter S
while True:
test_score = input('Enter test score as integer or enter S to get average: ')
# input received as a string to allow for the entry of "S"
if test_score.isnumeric():
score = int(test_score) #attempting to format the input(INT) as an integer
count += 1
total += score
elif test_score.upper() == Sentinel:
break
else:
print ('Not an integer or S. Please re-enter the value')
if count > 0:
print (total, count)
average_score = total/count
print ('average score is : ', average_score)
else:
print ('No valid entries were made. Average score is N/A')
I'm trying to create a program that takes input from the user, -1 or 1 to play or quit, number of characters (n), two words for comparison (s1,s2), and calls this function: def strNcompare (s1,s2,n) and then prints the result. The function should return 0,-1,1 if n-character portion of s1 is equal to, less than, or greater than the corresponding n-character of s2, respectively. So for example is the first string is equal to the second string, it should return a 0.
The loop should end when the user enters, -1.
I'm just starting out in Python so the code I have is pretty rough. I know I need an if/else statement to print the results using the return value of the function and a while loop to make the program run.
This is what I have so far, it by no means works but my knowledge ends here. I don't know how to integrate the character (n) piece at all either.
com = input ("String comparison [1(play), -1(quit)]: ")
while (com=='1'):
s1 = input ("enter first string: ")
s2 = input ("enter second string: ")
n = int(input("number of characters: ")
s1 = s1[:n]
s1 = s2[:n]
if com==-1:
break
def strNcompare(s1,s2,n):
return s1==s2
elif s1==s2:
print(f'{s1} is equal to {s2}')
elif s1>s2:
print (f'{s1} is greater than {s2}')
elif s1<s2:
print (f'{s1} is less than {s2}')
else:
print ("QUIT")
break
com = input ("String comparison [1(play), -1(quit)]: ")
As of 10/05/2019 - I revised the code and now I am getting a syntax error at "s1 = s1[:n]"
it did not made much sense and especially the variable 'n' is not completely clear to me. I would not code it like that but I tried to be as close to your logic as possible.
com = input ("String comparison [1(play), -1(quit)]: ")
while (com=='1'):
s1 = input ("enter first string: ")
s2 = input ("enter second string: ")
n = input ("number of characters: ") #what is the purpose of this?
if s1==s2:
print(f'{s1} is equal than {s2}')
elif s1>s2:
print (f'{s1} is greater than {s2}')
elif s1<s2:
print (f'{s1} is less than {s2}')
else:
print ("Error")
Question:
The hand is displayed.
The user may input a word or a single period (the string ".")
to indicate they're done playing
Invalid words are rejected, and a message is displayed asking
the user to choose another word until they enter a valid word or "."
When a valid word is entered, it uses up letters from the hand.
After every valid word: the score for that word is displayed,
the remaining letters in the hand are displayed, and the user
is asked to input another word.
The sum of the word scores is displayed when the hand finishes.
The hand finishes when there are no more unused letters or the user inputs a "."
hand: dictionary (string -> int)
wordList: list of lowercase strings
I am trying to write a code for my Python programming online course. However, I am getting an error :
ERROR: Failed to display hand correctly - be sure 'Current Hand' and the display of the hand are on the same line!
Here is my code :
def playHand(hand, wordList, n):
total = 0
while True:
print("\nCurrent Hand:",)
displayHand(hand)
entered = input('Enter word, or a "." to indicate that you are finished: ')
if entered == '.':
print ("Goodbye! Total score: " + str(total) +" points.")
break
if isValidWord(entered, hand, wordList) == False:
print ("Invalid word, please try again.")
else:
total += getWordScore(entered, n)
print (str(entered), "earned", getWordScore(entered,n), "points. Total:", str(total))
hand = updateHand(hand, entered)
if calculateHandlen(hand) == 0:
print ("\nRun out of letters. Total score: " + str(total) +" points.")
break
The answer is in your code already:
def displayHand(hand):
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ") # print all on the same line
print() # print an empty line
Use end=" " in your print statement!!
This is from Ken Lambert's "Fundamentals of Python":
{
sum=0
while True:
data = input('enter a number or just enter to quit: ')
if data == "":
break
number = float(data)
sum += number
print("the sum is", sum)
}
error message:
data = input('enter a number or just enter to quit: ')
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
Process finished with exit code 1
Use raw_input rather than input. The description of input begins with:
Equivalent to eval(raw_input(prompt))
You're getting an error because eval("") reports a syntax error, because there's no expression there; it gets EOF immediately.
On the other hand, the description of raw_input says:
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
Since you want the string that the user typed, rather than the evaluation of an expression, this is the function you should use.
The error you provided is because you used input, which tries to execute the text from stdin as python code https://docs.python.org/2/library/functions.html#input. I've provided some fixes below.
sum=0
while True:
data = raw_input('enter a number or just enter to quit: ')
if len(data) < 1:
break
number = float(data)
sum += number
print("the sum is %f" % sum)
I found that you have a syntax problem with your code. If you want to to put data in a variable you should use that:
variable = raw_input("Please enter ____")
Therefore you should replace line 4 to:
data = raw_input('enter a number or just enter to quit: ')