So here I am again, clueless as always. I'm somewhat of a novice, so this is probably biting off more than I can chew, but whatever.
The point of this program is to provide an output based off of input values from the user. It's meant to implement an input trap should the user not enter the correct input.
I'm trying to make it so the input of a letter or a non-integer value causes the message "Please enter only whole numbers." It works for the float points, but not letters. I should note that the "Enter a number between 0 and 10" message is working fine.
Also, the loop is supposed to close when the user inputs 'done', but that only results in a "ValueError: could not convert string to float: 'done'".
I haven't written this in While True format as it's more comfortable for me to stick away from that method of writing while loops.
setCount = 1
allScore = 0
done = False
while not done:
strScore = float (input ( "Enter Set#" + str(hwCount) + " score: "))
if (strScore == int (strScore) and strScore >=0 and strScore <=10):
totalScore = totalScore + (strScore)
setCount = setCount + 1
elif ( setScore == int (strScore) and( setScore < 0 or setScore > 10)):
print ("Please enter a number between 0 and 10.")
elif setScore != "done":
print ("Please enter only whole numbers.")
else:
done = True
You immediately convert the input string to a float on the same line where you read it:
strScore = float (input ( "Enter HW#" + str(hwCount) + " score: "))
In order to accept "done" as an input, you need to keep it as a string, and convert it to float (or int) after you have done all input validation.
drop float() and strScore will be a string. Then check if it equals "done". Finally, convert it to an integer inside a try block
print ( "Enter the homework scores one at a time. Type \"done\" when finished." )
hwCount = 1
totalScore = 0
while True:
strScore = input ( "Enter HW#" + str(hwCount) + " score: ")
if strScore == "done":
break
try:
intScore = int(strScore)
except ValueError:
print ("Please enter only whole numbers.")
continue
if (intScore >=0 and intScore <=10):
totalScore += intScore
hwCount += 1
else:
print ("Please enter a number between 0 and 10.")
You should really clean your code up, all those extra spaces hurts readability. I'd suggest using PyLint (pip install pylint, pylint file.py).
I'm not going to refactor your code too much, but you need to check for 'done' before converting to a float. And you'll want to catch ValueErrors incase somebody enters an invalid answer and handle it gracefully.
print("Enter the homework scores one at a time. Type \"done\" when finished. Ctrl+c to quit at any time.")
hwCount = 1
totalScore = 0
try:
while True:
strScore = input("Enter HW#" + str(hwCount) + " score: ")
if strScore == 'done':
break #done
else:
try:
strScore = float(strScore)
except ValueError:
print('Invalid input: must be a numerical score or "done"')
continue
if (strScore == int (strScore) and strScore >=0 and strScore <=10):
totalScore = totalScore + (strScore)
hwCount = hwCount + 1
elif ( strScore == int (strScore) and( strScore < 0 or strScore > 10)):
print ("Please enter a number between 0 and 10.")
elif strScore != "done":
print ("Please enter only whole numbers.")
except KeyboardInterrupt:
pass #done
Heres a more complete version of your program, for reference. It's how I would have refactored it.
#!/usr/bin/env python3
def findmode(lst):
bucket = dict.fromkeys(lst, 0)
for item in lst:
bucket[item] += 1
return max((k for k in bucket), key=lambda x: bucket[x])
print("Enter the homework scores one at a time.")
print("Type 'done' when finished or ctrl+c to quit.")
scores = []
try:
while True:
strScore = input("Enter score: ")
if strScore == 'done':
break #done
else:
try:
strScore = int(strScore)
except ValueError:
print('Invalid input: must be a score or "done"')
continue
if (0 <= strScore <= 10):
scores.append(strScore)
else:
print("Please enter a valid score between 0 and 10.")
except KeyboardInterrupt:
pass # user wants to quit, ctrl+c
finally:
print("Total scores graded: {}".format(len(scores)))
print("Highest score: {}".format(max(scores)))
print("Lowest score: {}".format(min(scores)))
print("Mean score: {}".format(sum(scores)/len(scores)))
print("Mode score: {}".format(findmode(scores)))
Related
Can't seem to get the code to work on if player_guess in player_lucky_list:. It does not check if I had guessed the right number. Also having trouble with the task d.
d. If it is a number, and in the list, but doesn’t match
lucky_number then you find out number(s) that has max
difference as is 10, and assign the numbers that has 10
difference into list input_diff and add the lucky_number if
it was not in the list, then write out:
“your number is 10 points more or less from these
numbers : {input_diff}, do you like to try again? (type ‘Y’
= yes, ‘N’ = no)”
from datetime import datetime, date
import random
def age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
player_fname = input("Name: ")
player_age = int(input("Age: "))
running = True
while running:
player_birthday = datetime.strptime(input("Birthday (format yyyymmdd): "), "%Y%m%d")
age_player = int(age(player_birthday))
if age_player == player_age:
print("Wow your age is right, let’s continue!")
running = False
else:
print("Aha, we are in 2022 and your age is not right, kindly enter it again?")
lucky_number = random.randint(1, 200)
tries_count = 0
player_lucky_list = []
n = 10
for i in range(n):
player_lucky_list.append(random.randint(0, 200))
player_lucky_guess = []
guessing = True
while guessing:
message = "Hi {}, this is your try # {}".format(player_fname, tries_count)
print(message)
player_guess = input("Please enter number from {}: ".format(player_lucky_list))
if player_guess in player_lucky_list:
print("Congratulations, your lucky number is {} you got it from try # {}".format(player_guess, tries_count))
elif str in player_guess:
print("Sorry, wrong value, Enter a INTEGER NUMBER!!!!")
else:
print("Try again")
tries_count += 1
player_lucky_guess.append(player_guess)
print(player_lucky_guess)
Your list is storing different int values. The input function defaults to accepting strings. So you need to convert the string of "player_guess" into an int.
while guessing:
message = "Hi {}, this is your try # {}".format(player_fname, tries_count)
print(message)
player_guess = input("Please enter number from {}: ".format(player_lucky_list))
if int(player_guess) in player_lucky_list:
print("Congratulations, your lucky number is {} you got it from try # {}".format(player_guess, tries_count))
elif int(player_guess) not in player_lucky_list:
print("Sorry, wrong value, Enter a INTEGER NUMBER!!!!")
else:
print("Try again")
tries_count += 1
player_lucky_guess.append(player_guess)
print(player_lucky_guess)
i want to print a message depending on the type of the input but every time i input a complex number, FOR EXAMPLE (5j) it's detected as a string input. How do i solve this please? Thanks.
while True:
a = input("a ? ")
if (isinstance(a, complex)):
print("Valid number, please not Complex!")
try:
a = float(a)
except ValueError:
print ('please input a int or float')
if (type(a)==str):
print("Valid number, please not String!")
continue
if 0.5 <= a <= 100:
break
elif 0 <= a < 0.5:
print ('bigger number, please: 0.5-100')
elif a < 0:
print ('positive number, please')
elif a > 100:
print ('smaller number, please: 0.5-100')
Example of execution:
a ? 5j
please input a int or float
Valid number, please not String!
i tried doing this :
while True:
try:
a = input("a ? ")
if ('j' in a):
print("Valid number, please not Complex!")
a = float(a)
except ValueError:
print ('please input a int or float')
if (type(a)==str and 'j' not in a):
print("Valid number, please not String!")
continue
if 0.5 <= a <= 100:
break
elif 0 <= a < 0.5:
print ('bigger number, please: 0.5-100')
elif a < 0:
print ('positive number, please')
elif a > 100:
print ('smaller number, please: 0.5-100')
but it's not "Perfect"
You can add the first block of code into try block
Like this -
while True:
try:
a = input("a ? ")
if (isinstance(a, complex)):
print("Valid number, please not Complex!")
a = float(a)
except ValueError:
print ('please input a int or float')
if (type(a)==str):
print("Valid number, please not String!")
continue
if 0.5 <= a <= 100:
break
elif 0 <= a < 0.5:
print ('bigger number, please: 0.5-100')
elif a < 0:
print ('positive number, please')
elif a > 100:
print ('smaller number, please: 0.5-100')
Is this what you meant?
You can use nested try-except and the inbuilt function complex() instead.
So, your code needs to be like this
while True:
a = input("a? ")
try:
a = float(a)
if 0.5 <= a <= 100:
break
elif 0 <= a < 0.5:
print ('bigger number, please: 0.5-100')
elif a < 0:
print ('positive number, please')
elif a > 100:
print ('smaller number, please: 0.5-100')
except ValueError:
try:
a = complex(a)
print("Valid number, please not Complex!")
except ValueError:
print ("Valid number, please not String!")
continue
Hi i am albert i am learning python, in this block of code i wrote i intend it to print the total, but the input statements just keep going in a loop
print("this program prints your invoice")
while True:
ID = input("item identification: ")
if ID == "done":
break
if len(ID) < 3:
print("identification must be at least 3 characters long")
exit(1)
break
try:
Quantity = int(input("quantity sold: "))
except ValueError:
print("please enter an integer for quantity sold!!!")
exit(2)
if Quantity <= 0:
break
print("please enter an integer for quantity sold!!!")
exit(3)
try:
price = float(input("price of item"))
except ValueError:
print("please enter a float for price of item!!")
exit(4)
if price <= 0:
print("please enter a positive value for the price!!!")
exit(5)
break
cost = 0
total = cost + (Quantity*price)
print(total)
I think you need this
cost = 0
total = cost + (Quantity*price)
print(total)
to be inside the while loop. Else, skip the loop completely.
Try this:
print("This program prints your invoice")
total = 0
more_to_add = True
while more_to_add == True:
ID = input("Item identification: ")
if len(ID) < 3:
print("Identification must be at least 3 characters long")
continue
try:
Quantity = int(input("Quantity sold: "))
except ValueError:
print("Please enter an integer for quantity sold!!!")
continue
if Quantity <= 0:
print("Please enter an integer for quantity sold!!!")
continue
try:
price = float(input("Price of item: "))
except ValueError:
print("Please enter a float for price of item!!")
continue
if price <= 0:
print("Please enter a positive value for the price!!!")
continue
total = total + (Quantity*price)
answer = input("Want to add more? (Y/N)" )
if answer == 'Y':
more_to_add = True
else:
more_to_add = False
print(total)
import random
four_digit_number = random.randint(1000, 9999) # Random Number generated
def normal():
four_digit = str(four_digit_number)
while True: # Data Validation
try:
guess = int(input("Please enter your guess: "))
except ValueError or len(str(guess)) > 4 or len(str(guess)) < 4:
print("Please enter a 4 digit number as your guess not a word or a different digit number")
else:
break
guess = str(guess)
counter = 0
correct = 0
while counter < len(four_digit):
if guess[counter] in four_digit:
correct += 1
counter += 1
if correct == 4:
print("You got the number correct!")
else:
print("You got " + str(correct) + " digits correct")
normal()
I don't understand why it says the index is not in range. When I use 0 instead of actually using counter it works. This only happens when I enter a value under 4 and when I enter a value over 4 the loop does not restart but it breaks out of the loop.
I would propose such a solution:
def normal():
four_digit = str(four_digit_number)
while True: # Data Validation
try:
guess = str(int(input("Please enter your guess: ")))
assert len(guess) == 4
except (ValueError, AssertionError):
print("Please enter a 4 digit number as your guess not a word or a different digit number")
else:
break
correct = sum(a == b for a, b in zip(four_digit, guess))
if correct == 4:
print("You got the number correct!")
else:
print("You got " + str(correct) + " digits correct")
#My code should take a random between 1 and 100 and let you guess it.
#This part works, but I want to add the posibility to reveal the number and then is when I get the error "could not convert string to float"
def reveal(guess):
return secret_number
import random
secret_number = random.random()*100
guess = float(input("Take a guess: ")) #This is the input
while secret_number != guess :
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = float(input("Take a guess: ")) #This input is here in order for the program not to print Higher or Lower without ever stopping
else:
print("\nYou guessed it! The number was " ,secret_number)
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", secret_number)
input("\n\n Press the enter key to exit")
Any help would be a great service. Also I am only programming for just a few weeks so sorry if my code looks wrong.
If you want to use float number to compare, the game may be endless because a float number has many fractional digits. Use int number.
#!/usr/bin/env python3.3
# coding: utf-8
import random
def guess_number():
try:
guess = int(input("Take a guess:"))
except ValueError:
print("Sorry, you should input a number")
guess = -1
return guess
if __name__ == '__main__':
secret_number = int(random.random() * 100)
while True:
guess = guess_number()
if guess == -1:
continue
elif guess < secret_number:
print("Lower...")
elif guess > secret_number:
print("Higher...")
else:
print("\nYou got it! The number was ", secret_number)
input("\n\nPress any key to exit.")
break # or 'import sys; sys.exit(0)'
import random
LOWEST = 1
HIGHEST = 100
def main():
print('Guess the secret number between {} and {}!'.format(LOWEST, HIGHEST))
secret = random.randint(LOWEST, HIGHEST)
tries = 0
while True:
guess = raw_input('Your guess: ').strip().lower()
if guess.isdigit():
tries += 1
guess = int(guess)
if guess < secret:
print('Higher!')
elif guess > secret:
print('Lower!')
else:
print('You got it in {} tries!'.format(tries))
break
elif guess == "reveal":
print('The secret number was {}'.format(secret))
break
else:
print('Please enter a number between {} and {}'.format(LOWEST, HIGHEST))
if __name__=="__main__":
main()
Use random.range instead of random.random.
secret_number = random.range(1,100,1)
And ...,str(secret_number)
...
else:
print("\nYou guessed it! The number was " ,str(secret_number))
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", str(secret_number))
...
That way you will be concatenating a string with a string. Also, you can keep random.random and only make the second change.
EDIT:
Another thing to do is to use raw_input instead of input. Then use try.
guess = raw_input("Take a guess: ")
try:
guess = float(guess)
except:
pass
This will try to convert guess into a float, and it that fails, then it will remain a string. That should solve your problem.
You could isolate concerns by defining a function that asks user for input until a float is provided:
def input_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("You should input a float number. Try again.")
Then you could use it in your script:
guess = input_float("Take a guess: ")
If you want to accept 'reveal' as an input in addition to a float number:
def input_float_or_command(prompt, command='reveal'):
while True:
s = input(prompt)
if s == command:
return s
try:
return float(s)
except ValueError:
print("You should input a float number or %r. Try again." % command)