pointsToAdd = 30
strengthPoints = 0
healthPoints = 0
wisdomPoints= 0
dexterityPoints = 0
while pointsToAdd > 0:
choice = int(input("Choice(1-4): "))
if choice == 1:
pointsToAdd = int(input("How many Strength points would you like to add: "))
if pointsToAdd < 31 and pointsToAdd > 0 and pointsToAdd - strengthPoints > 0:
strengthPoints += pointsToAdd
pointsToAdd -= strengthPoints
print("You now have",strengthPoints,"strength points")
elif pointsToAdd > 30:
print("You cannot add that many!")
elif pointsToAdd<1:
print("You cannot add less than one point!")
elif pointsToAdd - strengthPoints <= 0:
print("You only have",pointsToAdd,"points!")
else:
print("We are sorry, but an error has occurred")
I am trying to make it so that the user can enter points for any of the four categories, but has no more than 30 points to expend(I have not yet written the code for the health, wisdom or dexterity points). Why when i run the program does the loop only run again if you choose to add a number of points between 1-30? If the user enters the points they want to allocate towards strengthPoints using numbers not between 1-30, the loop will run the associated if statement, but will not run through the loop again, why is this the case?
you are using the same variable for two different purposes pointsToAdd. You have it as the total points to assign, and what was selected by the user to add to a stat. Once you stomp the total points to assign with the users choice, you then add it to the 0 strength and subtract it from your user entered value, setting it to zero. Using to separate variables like below will fix it.
totalPointsToAdd = 30
strengthPoints = 0
healthPoints = 0
wisdomPoints= 0
dexterityPoints = 0
while totalPointsToAdd > 0:
choice = int(input("Choice(1-4): "))
if choice == 1:
pointsToAdd = int(input("How many Strength points would you like to add: "))
if pointsToAdd < 31 and pointsToAdd > 0 and pointsToAdd - strengthPoints > 0:
strengthPoints += pointsToAdd
totalPointsToAdd -= pointsToAdd
print("You now have",strengthPoints,"strength points")
You do
pointsToAdd = 30
Then in the loop
pointsToAdd = int(input("How many Strength points would you like to add: "))
Then in the test
# Here pointsToAdd is not 30, but the value inputed by the user
strengthPoints += pointsToAdd
# Here strengthPoints == pointsToAdd == the value from the input
pointsToAdd -= strengthPoints
# Here pointsToAdd == 0
This results in pointsToAdd == 0 after than.
You need to use another variable for the input of your user.
As other pointed out you are overwriting the same variable pointsToAdd. I also consider that you can cut down your conditions to two:
pointsToAdd = 30
strengthPoints = 0
while pointsToAdd:
print ('You have', pointsToAdd, 'available points.')
choice = int(input("Choice(1-4): "))
if choice == 1:
toBeAdded = int(input("How many Strength points would you like to add: "))
if toBeAdded < 1: # Can't assign negative or null values
print("You cannot add less than one point!")
continue
if toBeAdded > pointsToAdd: # Don't have enough points to spend
print("You only have", pointsToAdd, "available points!")
continue
strengthPoints += toBeAdded
pointsToAdd -= toBeAdded
print("You now have", strengthPoints, "strength points")
In Python 2.x use: raw_input
In Python 3.x use: input
If you want compatibility between Python 2.x and 3.x, you can use:
try:
input = raw_input
except NameError:
pass
Related
I'm new to python and have been trying to create a simple grade calculator which tells the user what grade they've achieved based on their final score they've inputted.
def grades():
try:
score = int(input("Please enter your score between 0 and 100:"))
if score >= 90:
print("Grade:A")
elif score >= 80 :
print("Grade:B")
elif score >= 70:
print("Grade:C")
elif score >= 60:
print("Grade:D")
elif score >= 50:
print("Grade:E")
elif score < 50:
print("Grade:F")
except score not in range (0,101) or ValueError:
int(input("Incorrect value. Please enter your score between 0 and 100:"))
However when I try to run the program, it disregards the range and value error and gives it a grade anyway. Is there any way to rectify this, and if possible how could I make the program more efficient. As I said, I'm new to python, so any feedback would be useful.
Just for fun, let's make it a Match Case statement:
Since you only accept integers, we can take and assign score to input with :=, then check if it's valid with str.isnumeric. If that's true then we'll make score an integer := and check if it's between 0 and 100.
We'll change the input statement if they don't put valid input the first time around.
def grades():
text = "Please enter your score between 0 and 100: "
while True:
if ((score := input(text)).isnumeric() and
(score := int(score)) in range(0, 101)):
break
else:
text = "Incorrect value. Please enter your score between 0 and 100: "
match score:
case x if x >= 90 : grade = 'A'
case x if x >= 80 : grade = 'B'
case x if x >= 70 : grade = 'C'
case x if x >= 60 : grade = 'D'
case x if x >= 50 : grade = 'E'
case _ : grade = 'F'
print(f'Grade: {grade}')
Please note that this will only work in Python 3.10 or greater.
Just do this:
def grades():
try:
score = int(input("Please enter your score between 0 and 100:"))
if score > 100:
while True:
int(input("Incorrect value. Please enter your score between 0 and 100:"))
if score <= 100:
pass
else:
break
if score >= 90:
print("Grade:A")
elif score >= 80 :
print("Grade:B")
elif score >= 70:
print("Grade:C")
elif score >= 60:
print("Grade:D")
elif score >= 50:
print("Grade:E")
elif score < 50:
print("Grade:F")
except:
print("Oops. sommthing went wrong")
grades();
I made some corrections to your code. I added some comments to help explain what is going on. Let me know if this solution works for you:
def grades():
while True:
# Start a loop to ask for user input:
score = int(input("Please enter your score between 0 and 100:"))
# If not in range 1, 100, print error message
if score in range(0, 101):
break
print('Incorrect value. Please enter your score between 0 and 100:')
# calculate grade:
if score >= 90:
print("Grade:A")
elif score >= 80:
print("Grade:B")
elif score >= 70:
print("Grade:C")
elif score >= 60:
print("Grade:D")
elif score >= 50:
print("Grade:E")
elif score < 50:
print("Grade:F")
if __name__ == '__main__':
grades()
Simply assert that the input is in the determined range before checking through score ranges. Really, there is no need for a try/except statement.
def grades():
while True:
score = int(input(...))
if 0 <= score <= 100:
break
# Invalid score
# Check score ranges
...
I have made changes to your code, please test to ensure it performs to expectations.
I have added a while True loop, which attempts to validate the score to be between 0 - 100. If a non-integer value is entered it will hit the ValueError exception. This loop will only exit when a number within the range is entered.
The if statements use interval comparators X <= score < Y. You can read more about interval comparators here.
The if statement was also removed out of the try - except to make debugging easier. The idea is to have the least code possible in try - except so that when an exception triggers, it would be caused by the intended code.
Lastly, you don't want to ask for the user input inside the exception as the user might enter something which may cause another exception which will go uncaught.
def grades():
while True:
# Perform basic input validation.
try:
# Gets the user input.
score = int(input("Please enter your score between 0 and 100: "))
# Checks if the number entered is within 0 - 100. Note that range is non-inclusive for the stop. If it is within 0 - 100 break out of the while loop.
if 0 <= score <= 100:
break
# If a non-integer is entered an exception will be thrown.
except ValueError:
print("Input entered is not a valid number")
# Checking of scores using interval comparison
if score >= 90:
print("Grade:A")
elif 80 <= score < 90:
print("Grade:B")
elif 70 <= score < 80:
print("Grade:C")
elif 60 <= score < 70:
print("Grade:D")
elif 50 <= score < 60:
print("Grade:E")
else:
print("Grade:F")
I'm currently making a guessing game where user can get a congrats statement if they guess correctly 3 times in a row or a hint statement if they guesses incorrectly 3 times in a row. If user makes two correct guesses and one incorrect guess the count will reset and vice versa for incorrect guesses. the goal is for the right/wrong guess to be 3 times in a row for the statement to print
Here is what I have
count = 0
rightGuess = 0
wrongGuess = 0
die1 = random.randint(1,6)
guess = int(input('Enter guess: '))
if guess == die1:
rightGuess += 1
print('Good job')
if rightGuess == 3:
print('You guessed three times in a row!')
if guess != die1:
wrongGuess += 1
print('Uh oh wrong answer')
if wrongGuess == 3:
print("Hint: issa number :)")
This works but it displays the text whenever the user reaches 3 wrong or right guesses even if it's not in a row. Please help
You can reset the rightGuess variable using rightGuess = 0 when you add 1 to the wrongGuess variable.
You just have to reset the opposite variable to 0 when incrementing either of them.
count = 0
consecutiveRightGuess = 0
consecutiveWrongGuess = 0
die1 = random.randint(1, 6)
guess = int(input('Enter guess: '))
if guess == die1:
consecutiveWrongGuess = 0
consecutiveRightGuess += 1
print('Good job')
if consecutiveRightGuess == 3:
print('You guessed three times in a row!')
if guess != die1:
consecutiveRightGuess = 0
consecutiveWrongGuess += 1
print('Uh oh wrong answer')
if consecutiveWrongGuess == 3:
print("Hint: issa number :)")
You could also do it like this only using one variable for counting guesses:
import random
count = 0
while True:
die1 = random.randint(1,6)
guess = int(input("Enter guess: "))
if guess == die1:
count = count + 1 if count >= 0 else 1
print('Good job')
if guess != die1:
print('Uh oh wrong answer')
count = count - 1 if count <= 0 else -1
if count == 3:
print('You guessed three times in a row!')
break
if count == -3:
print("Hint: issa number :)")
break
Very new to python and trying to figure out how to use the and operator to check if a number is between 50 and 100. Tried using and, && and || , but just getting invalid syntax python parser-16 error. If I take the and or alternative out of the code, then it partly works and dosn't give me a error message, though it dosn't check if the value is below 100, so presumly it must the and part that I'm doing wrong?
x = int(input("Enter a number between 0 and 100"))
if x < 50:
print("That is below 50!")
elif x > 50 and < 100:
print("That is above 50!")
else:
print("That number is too high!")
close!
x = int(input("Enter a number between 0 and 100"))
if x < 50:
print("That is below 50!")
elif x > 50 and x < 100:
print("That is above 50!")
else:
print("That number is too high!")
if x > 50 and x < 100 you have to reference it each time you check if its true
Alternative solution:
x = int(input("Enter a number between 0 and 100: "))# for a better look
if x < 50:
print("That is below 50!")
elif 100 >= x >= 50:# the numbers 50 and 100 shall be inclusive in one of the three params
print("That is between 50 and 100!")
else:
print("That number is too high!")
To simplify it more, you can write as below.
x = int(input("Enter a number between 0 and 100"))
if x < 50:
print("That is below 50!")
elif 50 < x < 100:
print("That is above 50!")
else:
print("That number is too high!")
If x<50:
print('Below 50')
elif x>50 and x<100:
print('Between 50 and 100');
else:
print('Above 100');
Try this
I'm new to Python. I'm trying to write a small game that asks the end user to pick a number from 1 to 1000 and keep it in their head (the number is not provided to the program). The program should be able to find the number within 10 guesses. As I typically do, I went down the wrong path. My program works most of the time, but there are occasions where it does not find the number in under 10 guesses. Here is my code:
# script to guess a user's number between 1 and 1000 within 10 guesses
# import random so we can use it to generate random numbers
from random import randint
# Variables
lowerBound = 1
upperBound = 1000
numGuesses = 1
myGuess = 500
failed = False
# Welcome Message
print("#####################################################################################################"
"\n# #"
"\n# Please think of a number between 1 and 1000. I will attempt to guess the number in 10 tries. #"
"\n# #"
"\n#####################################################################################################")
while numGuesses <= 10:
# if the lower and upper bounds match we've found the number
if lowerBound == upperBound:
print(f"\nYour number is {str(lowerBound)}. It took me '{str(numGuesses)} guesses!")
break
print(f"\nIs the number {str(myGuess)}? If correct, type CORRECT. If low, type LOW. If high, type HIGH.")
# uncomment for var output
# print(f"\nGuesses = {str(numGuesses)}\nLower bound = {str(lowerBound)}\nUpper bound = {str(upperBound)}")
userFeedback = input("\nResponse: ").upper()
if userFeedback == 'HIGH':
print(f"\nGuess #{str(numGuesses)} was too high")
if numGuesses == 10:
failed = True
break
upperBound = myGuess - 1
myGuess = randint(lowerBound, upperBound)
elif userFeedback == 'LOW':
print(f"\nGuess #{str(numGuesses)} was too low")
if numGuesses == 10:
failed = True
break
lowerBound = myGuess + 1
myGuess = randint(lowerBound, upperBound)
elif userFeedback == 'CORRECT':
print(f"\nYour number is {str(myGuess)}! It took me {str(numGuesses)} guesses!")
break
numGuesses += 1
if failed:
print(f"\nMy final guess of {str(myGuess)} was not correct. I wasn't able to guess your number in 10 tries.")
It seems clear (now) that the way I'm whittling down the numbers is not going to work. I had originally thought to ask if it was 500 and, if lower, ask if it was 250. If lower again, ask if it was 125, and so on. If higher, ask if it was 750, 875 and so on. Is that the correct approach here?
I've been thinking about this too long and I believe I've cooked my brain. Thanks!
myGuess = int(math.ceil((myGuess) / 2))
is not correct.
If you have narrowed down the range to between 6 and 8 and you were guessing 7, your previous code would call 4 instead which is outside your search range.
if userFeedback == 'HIGH':
print(f"\nGuess #{numGuesses} was too high")
upperBound = myGuess - 1
elif userFeedback == 'LOW':
print(f"\nGuess #{numGuesses} was too low")
lowerBound = myGuess + 1
myGuess = int(lowerBound + ((upperBound - lowerBound) / 2))
I've updated my code and I think I have it. Thanks for the tips.
# script to guess a number between 1 and 1000 within 10 guesses
# Variables
lowerBound = 1
upperBound = 1000
numGuesses = 1
myGuess = 500
# Welcome Message
print("#####################################################################################################"
"\n# #"
"\n# Please think of a number between 1 and 1000. I will attempt to guess the number in 10 tries. #"
"\n# #"
"\n#####################################################################################################")
while numGuesses <= 10:
# uncomment next line for var output
# print(f"\nGuesses = {numGuesses}\nLower bound = {lowerBound}\nUpper bound = {upperBound}")
print(f"\nIs the number {myGuess}? If correct, type CORRECT. If low, type LOW. If high, type HIGH.")
userFeedback = input("\nResponse: ").upper()
if userFeedback == 'HIGH':
print(f"\nGuess #{numGuesses} was too high")
upperBound = myGuess
myGuess = (lowerBound + myGuess) // 2
elif userFeedback == 'LOW':
print(f"\nGuess #{numGuesses} was too low")
lowerBound = myGuess
myGuess = (upperBound + myGuess + 1) // 2
elif userFeedback == 'CORRECT':
print(f"\nYour number is {myGuess}! It took me {numGuesses} guesses!")
break
numGuesses += 1
i have no idea why this is broken. Also dont tell me to use python's built in function because this is designed for some practice not to actually be used. It is binary to decimal that is broken. It has a index error with the variable 'index'
print('Please choose from the list below:')
print('')
print('1) Convert from decimal/denary to binary; ')
print('2) Covert from binary to denary/decimal; ') #Main Menu
print('3) Infomation and settings (coming soon);')
print('4) Exit. ')
print('')
menu_choice = str(input('Enter your choice here: ')) #User inputs choice here
if menu_choice == '1':
dec_binary()
elif menu_choice == '2':
binary_dec()
elif menu_choice == '3':
print('By Callum Suttle')
else:
return 'Thank You'
def dec_binary(): #Module 1: decimal to binary
dec = int(input('Enter a number in decimal up to 255: ')) #Checks The number is an ok size, could be made bigger
while dec > 255:
dec = int(input('Enter a number up to 255, no more: '))
power = int(7) #change 7 to make bigger by 1 digit
convert = []
while power > -1: #until power goes below zero
if dec - pow(2, power) >= 0: #if entered number subtract 2 to the power of var-pow returns posotive number
convert.append(1)
power -=1 # add a 1
dec = dec - pow(2, power) >= 0
else:
convert.append(0)#if not add a zero
power -=1
print('')
print(convert) # print completed number
print('')
binary_decimal_converter() #back to main menu
def binary_dec():
anwser = 0
l_bi = str(input('Enter a number in binary up to 7 digits: '))
while len(l_bi) != 7: #checks for correct length
l_bi = str(input('Enter a number in binary up to 7 digits, you may add zeros before: '))
power = 7 #size can be increased by using this
index = 0
while index > 6: #until every power has been checked (in reverse order)
if l_bi[index] == '1': #if the digit is equal to 1
anwser += pow(2, power) #add that amount
power -= 1 #take the power to check next #why is this broken
index += 1 # add another index to check previous
else:
power -= 1 #as above
index += 1 #/\
print('')
print(anwser) #prints result
print('')
binary_decimal_converter() #main menu
this doesn't seem right
index = 0
while index > 6: #until every power has been checked (in reverse order)
...
you never enter this loop, do you?
a better loop would be something like
for i, bit in enumerate(l_bi):
answer += int(bit) * pow(2, 7-i)
also, since you're just practicing, you should find a better way to jump from menu to functions and back. you're doing recursive calls, which is a waste of stack, i.e. your functions actually never finish but just call more and more functions.
Some fixes:
def binary_dec():
anwser = 0
l_bi = str(input('Enter a number in binary up to 7 digits: '))
while len(l_bi) > 7: # LOOP UNTIL LENGTH IS LESS THAN 7
l_bi = str(input('Enter... : '))
power = len(l_bi) - 1 # directly set the power based on length
index = 0
while index < len(l_bi): # CORRECT LOOP CONDITION