How to get my Python program to pass an online grading system? - python-3.x

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!!

Related

What is the best way to deal with negative integers inputs in a python calculator?

Hello Fellow Developer's and Eng's:
How can I handle these two type's of input 1) when user enter "-0" and 2) When user enter minus symbol "-", within my while loop for adding nonnegative integers.
The program developed functions in the overall design, which is to add non negative integers, but it has a flaw when a user input -0 or -(minus) sign. I want to print('you have entered a negative int or a negative/minus - symbol') when these entries are made by the user.
Currently, the program continues without adding when user submit -0 in the input and there is ValueError when user just submit - symbol.
Please provide feedback.
entry = 0
sum = 0
# Request input from the user
print('This is nonnegative integer addition program. \n',)
while entry >= 0:
entry=int(input('Please enter numbers to add: '))
if entry >=0:
sum+=entry
elif entry<0 or str(entry[0])=='-' or str(entry)=='-0': # -0 nor (first index -(minus) does not work
print('You have entered a negative integer or symbol:', \
entry, ', therefore you have been exited out of the program')
print('total integer input sum =',sum)
As mentioned in the other answer. You convert your value to an int and you can no longer access the characters. I've made the program store the user_input and check that.
entry = 0
sum = 0
# Request input from the user
print('This is nonnegative integer addition program. \n',)
while entry >= 0:
user_input = input('Please enter numbers to add: ')
if '-' in user_input:
print(
'You have entered a negative integer or symbol:',
user_input,
', therefore you have been exited out of the program'
)
break
entry = int(user_input)
sum+=entry
print('total integer input sum =',sum)
In this version I store the input string as user_input and check it for a '-' symbol. I use '-' in instead of user_input[0]=='-' because input that starts with a space can still work with int.
Another thing to note, your if/elif was over specified.
if entry >=0:
sum+=entry
elif entry<0 or str(entry[0])=='-' or str(entry)=='-0':
break
In your second clause entry is guaranteed to be less than zero. So the str(entry[0]) never gets called. Thankfully because it was an error. Your if statement is equivalent to.
if entry>=0:
...
else:
...
Lastly a small point. When you have a set of brackets like in your print statment. You don't need a \ to indicate a line continuation.
print(
"one",
"two"
)
Python recognizes the open (. If you wanted to continue a string you would need it.
print("one \
two")
When you are storing the input as int entry=int(input('Please enter numbers to add: ')) the entry value is 0 because on int the is no -0 so if you want to check if the user input -0 you need to keep it as str.
You can try
entry = 0
sum = 0
print('This is nonnegative integer addition program. \n',)
while int(entry) >= 0:
entry=input('Please enter numbers to add: ')
if entry[0] !='-':
if int(entry) >= 0:
sum+=int(entry)
elif entry[0]=='-' or entry=='-0':
print('You have entered a negative integer or symbol:', \
entry, ', therefore you have been exited out of the program')
entry = -1
print('total integer input sum =',sum)

Python hangman script will not work if there are spaces

current code -
string = input("Enter word")
guessed= False
alphabet = 'abcdefghijklmnopqrstuvwxyz'
guesses=[]
while guessed== False:
char = input("Enter one letter :").lower()
if len(char) == 1:
if char not in alphabet:
print("Error you have not entered a letter")
elif char in guesses:
print("Letter has been guessed before")
elif char not in string:
print("Sorry this letter is not part of the word")
guesses.append(char)
elif char in string:
print("Well done")
guesses.append(char)
else:
print("Error")
else:
print("Only 1 character should be entered")
status= ''
if guessed == False:
for letter in string:
if letter in guesses:
status+=letter
if status==string:
print("Congratulations you have won")
guessed=True
else:
status+='_'
print(status)
If the word is "hello world" and the user guessed the words correctly the output below is displayed:
Well done
hello_world
Enter one letter :
The user is asked again to enter another letter even though the word is found. Im not sure on how to fix this.
I would add an extra condition for spaces like this
for letter in string:
if letter in guesses:
status+=letter
if status==string:
print("Congratulations you have won")
guessed=True
elif letter == ' ':
status += ' '
else:
status+='_'
This way the user sees that there are actually two words but does not have to enter a space explicitly.
Output
Enter one letter :h
Well done
h____ _____
Enter one letter :e
Well done
he___ _____
...
Enter one letter :d
Well done
Congratulations you have won
hello world
hello world contains a space, and yet space is not allowed as a guessed letter, so even if the user guesses all the right letters, the status will at best become hello_world, which is not equal to hello world, leaving the game unfinished.

Reject letters and only allow number inputs # enter first and second number in Python 3.x

Trying to only allow number inputs in python 3.x no letters and ask user to input a number if they enter a letter. I have two numbers that need to be entered and need it to reject singlarily as they are entered.
print ('Hello There, what is your name?') # String asks the user for their name
myname = input() #string
print ('Nice to meet you, '+ myname)# String responds "Nice to meet you" and input the users name that was entered
print() #adds a space
print ('We want to some math today!') # String tells user we want to do some math today
print() # adds a space
num1,num2 = float(input("Enter first number")), float(input("Enter second number"))
sum = num1+num2
if sum >100 : # Determines if users inputs when added together are > 100
print('They add up to a "Big Number" ') # If inputs are > 100 prints "They add up to a big number"
# and the users name
elif sum <=100 : # Determines if the users inputs when added are = to or <100
print ('They add up to' ,(sum))
You need a while loop to continuously accept a valid input which in your case is a numerical one.
Another thing is that you need to check if the entered input is numerical or not, in that case you can use Python's inbuilt isdigit() function to do it.
Lastly, type cast your input to float or int while you add the both to avoid str related errors.
print ('Hello there, what is your name?') # String asks the user for their name
myname = input() #string
print ('Nice to meet you, '+ myname) # String responds "Nice to meet you" and input the users name that was entered
print() #adds a space
print ('We want to some math today!') # String tells user we want to do some math today
print() # adds a space
i = False
while i == False:
num1 = input("Enter first number: ")
if num1.isdigit():
i = True
else:
i = False
print() # adds a space
j = False
while j == False:
num2 = input("Enter Second number: ")
if num2.isdigit():
j = True
else:
j = False
sum = float(num1) + float(num2)
if sum > 100 : # Determines if users inputs when added together are > 100
print('They add up to a "Big Number" ') # If inputs are > 100 prints "They add up to a big number"
# and the users name
elif sum <= 100 : # Determines if the users inputs when added are = to or <100
print ('They add up to' ,(sum))
Let me know, if that worked for you!
When you are validating multiple inputs, I usually make a separate function to do so. While it may not be necessary here, it is a good habit to factor out repeated code. It will exit if either of the inputs are not floats. Here's how I would do it, using a try block with a ValueError exception. By the way, newlines can be achieved by putting '\n' at the end of the desired strings. Using print() is a sloppy way of doing it.
import sys
def checkNum(number):
try:
number = float(number)
except ValueError:
print("That is not a float.")
sys.exit()
return number
Then, you can use the original code like so:
print ('Hello There, what is your name?') #String asks the user for their name
myname = input() #string
print ('Nice to meet you, '+ myname + '\n')#String responds "Nice to meet you" and input the users name that was entered
print ('We want to some math today!\n') #String tells user we want to do some math today
num1 = checkNum(input("Enter first number"))
num2 = checkNum(input("Enter second number"))
sum = num1+num2
if sum >100 : # Determines if users inputs when added together are > 100
print('They add up to a "Big Number" ') #If inputs are > 100 prints "They add up to a big number" and the users name
elif sum <=100 : #Determines if the users inputs when added are = to or <100
print ('They add up to' ,(sum))

finding largest and smallest number in python

I am very new to programming, please advise me if my code is correct.
I am trying to write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done':
break
try:
fnum = float(num)
except:
print("Invalid input")
continue
lst = []
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))
Your code is almost correct, there are just a couple things you need to change:
lst = []
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
try:
lst.append(int(user_input))
except ValueError:
print('Invalid input')
if lst:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
Also, since you said you're new to programming, I'll explain what I did, and why.
First, there's no need to set largest and smallest to None at the beginning. I actually never even put those values in variables because we only need them to print them out.
All your code is then identical up to the try/except block. Here, I try to convert the user input into an integer and append it to the list all at once. If any of this fails, print Invalid input. My except section is a little different: it says except ValueError. This means "only run the following code if a ValueError occurs". It is always a good idea to be specific when catching errors because except by itself will catch all errors, including ones we don't expect and will want to see if something goes wrong.
We do not want to use a continue here because continue means "skip the rest of the code and continue to the next loop iteration". We don't want to skip anything here.
Now let's talk about this block of code:
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
From your explanation, there is no need to get more input from the user, so none of this code is needed. It is also always a good idea to put int(input()) in a try/except block because if the user inputs something other than a number, int(input()) will error out.
And lastly, the print statement:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
In python, you can use the "string formatting operator", the percent (%) sign to put data into strings. You can use %d to fill in numbers, %s to fill in strings. Here is the full list of characters to put after the percent if you scroll down a bit. It also does a good job of explaining it, but here are some examples:
print('number %d' % 11)
x = 'world'
print('Hello, %s!' % x)
user_list = []
while True:
user_input = int(input())
if user_input < 0:
break
user_list.append(user_input)
print(min(user_list), max(user_list))

why is this not printing

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: ')

Resources