I am currently attempting to create a GPA calculator where the user types in his grade as a letter and it should convert into a number. However, it is not running the first if statement while running the break statement.
I have searched for answers and none have been able to fix the code. How can I alter or change the if statement so it appends to the list?
Here is the code:
yourGrade = {}
while True:
score = str(input("Enter your letter grades: "))
if score.lower() == 'A' or score.lower() == 'A+' or score.lower() == 'A-':
yourGrade.append(int(4))
print(yourGrade)
if score.lower() == 'done':
break
print(yourGrade)
You are checking if a variable in all lower-case is equal to a string literal with capitals in it.
Try this:
if score.lower() == 'a' or score.lower() == 'a+' or score.lower() == 'a-':
Related
I try to code my first little text based role play game.
The first step would be to enter your character name and then type "y" if you are fine with the name and "n" if you want to change the name.
So I want that the Program is asking you again to enter "y" or "n" if you fatfinger a "g" for example. And only let you reenter your name if you type "n"
Instead of these the program will let you reenter your name directly if you enter "g".
I already tried to do a "while True or False" loop around the _yesorno function.
Here is the code:
main.py
from Classes.character import character
from functions.yesorno import _yesorno
#character
char = character()
while True:
print("please enter a name for your character")
char.set_name(input())
print("Your name is: " + char.name + ". Are you happy with your choice? Type 'y' for yes, 'n' for no.")
if _yesorno(input()):
break
else:
continue
_yesorno.py
def _yesorno(input:str)->bool:
if input == "y":
return True
elif input == "n":
return False
else:
print("please use y for yes and n for no")
return None
As I am pretty new I would be happy, if you can explain your answer newbie friendly and not only with "your logic is wrong" :D
Thanks in advance!
if None is equal to while if False. Python have dynamic typing for types.
To check wrong input you can do things like:
def _yesorno(input_:str)->bool:
while input_ not in ['y', 'n']:
print("please use y for yes and n for no")
input_ = input()
return input_ == 'y'
That code check input directly instead itself. input_ not in ['y', 'n'] that part check if your input_ is one of array element.
After user enter 'y' or 'n' the function return proper result.
I would approach this with a pair of recursive functions. One that ran until the user gave a valid response, the other until a name was properly set.
Note that in many cases, recursive functions can be rewritten as loops and since python lacks tail call optimization, some people will prefer not using recursion. I think it is usually fine to do so though.
def get_input_restricted(prompt, allowed_responses):
choice = input(prompt)
if choice in allowed_responses:
return choice
print(f"\"{choice}\" must be one of {allowed_responses}")
return get_input_restricted(prompt, allowed_responses)
def set_character_name():
prospective_name = input("Enter a name for your character: ")
print(f"Your name will be: {prospective_name}.")
confirmation = get_input_restricted("Are you happy with your choice (y|n)? ", ["y", "n"])
if "y" == confirmation:
return prospective_name
return set_character_name()
character_name = set_character_name()
print(f"I am your character. Call me {character_name}.")
The reason why an input of 'g' is making the user reenter their name is because 'None' is treated as False therefore the loop will continue... you could try a simple if statement in a while loop and disregard your _yesorno function with
while(True):
print("please enter a name for your character")
charName = input()
while(True):
print("Your name is: " + charName + ". Are you happy with your choice? Type 'y' for yes, 'n' for no.")
yesorno = input()
if(yesorno == 'y' or yesorno == 'n'):
break
if(yesorno == 'y'):
break
char.set_name(charName)
print("and your name is {0}".format(char.name))
Whenever I try to append(guesses) to the all_guesses variable it seemingly replaces the existing value from the previous loop. I want the program to record down all the player's number of guesses per game round but it only record the most recent value. I made sure the variable isn't in the while loop so that it doesn't overwrite it, so what's wrong? I'm really new to python programming so I can't seem to figure this out. Each time I run the loop the guessed and all_guesses values are reset to their original.
This is a snippet of my program:
def main():
guesses = 0
guessed = []
all_guesses = []
guess = input('\nPlease guess a letter: ').lower()
letter = 'abcdefghi'
answer = random.choice(letter)
while len(guess) != 1 or guess not in letter:
print("\nInvalid entry! One alphabet only.")
guess = input('Please guess a letter: ')
while len(guess) < 2 and guess in letter:
if guess in guessed:
guess = input("\nYou've already guessed that! Try again: ").lower()
else:
if guess == answer:
guesses = guesses + 1
played = played + 1
print("\nCongratulations, that is correct!")
replay = input('Would you like to play again? Type y/n: ').lower()
all_guesses.append(guesses)
The short answer would be that all_guesses needs to be a global defined outside of main and the replay logic also needs to wrapped around main.
You seem to be missing logic, as you never modify guessed but expect to find things in there. And there are dead ends and other missing parts to the code. As best as I can guess, this is roughly what you're trying to do:
from random import choice
from string import ascii_lowercase as LETTERS
all_guesses = []
def main():
guessed = []
answer = choice(LETTERS)
guess = input('\nPlease guess a letter: ').lower()
while len(guess) != 1 or guess not in LETTERS:
print("\nInvalid entry! One alphabet only.")
guess = input('Please guess a letter: ').lower()
while len(guess) == 1 and guess in LETTERS:
if guess in guessed:
guess = input("\nYou've already guessed that! Try again: ").lower()
continue
guessed.append(guess)
if guess == answer:
print("\nCongratulations, that is correct!")
break
guess = input("\nIt's not that letter. Try again: ").lower()
all_guesses.append(len(guessed))
while True:
main()
replay = input('Would you like to play again? Type y/n: ').lower()
if replay == 'n':
break
print(all_guesses)
I am new to python. I was making a guess the random number game, and I run into issues when having both int and str as inputs, I want the user to exit the program when pressing Q or q, while the game to check for numbers as well. After hours of googling and rewriting this is what I came up with:
#! Python3
import random
upper = 10
number = random.randint(1, upper)
print(number) #TODO: THIS LINE FOR TESTING ONLY
print("Guess a number between 1 and {}. Press Q to quit!".format(upper))
total_guesses = 0
guess = 0
while guess != number:
total_guesses += 1
guess = input()
if guess.isalpha():
if guess == "q" or "Q":
break
elif guess != "q" or "Q":
print("Please type in a valid guess.")
guess = 0
if guess.isnumeric():
guess = int(guess)
if guess == number:
print("Good job! You guessed the number in {} tries!.".format(total_guesses))
break
if guess < number:
print("Guess Higher!")
if guess > number:
print("Guess lower!")
else:
print("Valid inputs only")
guess = 0
This code ALMOST works as intended; issues I have now is that at line 13 and 14 the loop breaks every time when any letter is typed, even though I set the if statement to only check for Q or q, and I can't understand why this is doing it. Any help is appreciated!
if guess == 'q' or "Q":
The way this line is read by python is -
if guess == "q":
and also -
if "Q":
"Q" is a character, which means it's truthy. if "Q" returns True. Try:
if guess == "q" or guess == "Q":
if you feels that's too much, other options include -
if guess in ["Q", "q"]:
if guess.upper() == "Q":
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.
Just to clarify, I have pasted my whole program as the problem can only be identified when it is with all the code in my program. My problem is, I have in-putted if else and elif statements in my program. When the user inputs "no" the program ends, and this runs fine and if the user inputs "yes" the program advances like it is supposed to do. The problem is when the user will input something invalid, something other than "yes" or "no" it should take them back to retyping their option but instead it carries on as if the user has inputted "yes".
while True:
print (" Position Finder")
choice = (input("Do you want to run the Position Finder program? Please enter yes or no!"))
# Lets the user input an answer to question I am asking it
if choice.lower() == "no":
# If the user input is "no"
print("The program will not run")
# This statement will be printed out and the program will not run
quit()
elif choice.lower() == "yes":
# If the user input is "yes"
print("The program will now run")
# This statement will be printed and the program will run
else:
# If an invalid statement is inputted
print("Invalid entry, please type again")
# This statement will be printed and the user will be given the option to input again
sentList = "ask not what your country can do for you ask what you can do for your country"
# Creates a list
sentList2 = sentList.split()
# This will split the list and give each word a position
print (sentList)
# This will print out the sentence in the program
word = (input("Enter Word: "))
# Lets the user input a word from the sentence
wordFound = False
# This boolean statement, "wordFound" will be set to true when the word has been found in the list
for (num, x) in enumerate(list(sentList2)):
# For every word in the users sentence
while word.lower() == x:
# While the users word is equal to the position in the sentence
print (ordinalSuffix())
# Print the ordinal suffix function
wordFound = True
# This boolean statement has been set to true as the word has been found in the list
break
# This will break the while loop from the boolean variable called "wordFound"
if wordFound == False:
# If the word has not been found in the list and the "wordFound" boolean variable has not been set to true
print ("Please enter a word from the sentence")
# This statement will print,meaning the user has to enter a word from the list
You may use continue keyword.
The continue statement, also borrowed from C, continues with the next
iteration of the loop:
while True:
print (" Position Finder")
choice = (input("Do you want to run the Position Finder program? Please enter yes or no!"))
if choice.lower() == "no":
print("The program will not run")
quit()
elif choice.lower() == "yes":
print("The program will now run")
else:
print("Invalid entry, please type again")
continue # move to next iteration
rest_of_your_code()
You only wrote a print statement in the else clause: print("Invalid entry, please type again"), but that does not make the program repeat the previous instructions. A possible solution:
choice = ""
while choice.lower() != "yes":
choice = (input("Do you want to run the Position Finder program? Please enter yes or no!"))
if choice.lower() == "no":
print("The program will not run")
quit()
elif choice.lower() == "yes":
print("The program will now run")
else:
print("Invalid entry, please type again")
You need to put one while loop more for that, returning the user in syntactically wrong answer and breaking loop in right answer. The question part should look like this:
while True: # Main loop
while True: # Question loop
choice = (input("Do you want to run the Position Finder program? Please enter yes or no!"))
if choice.lower() == "no":
print("The program will not run")
run = False
break
elif choice.lower() == "yes":
print("The program will now run")
run = True
break
else:
print("Invalid entry, please type again")
# In case of invalid entry Question loop will run again
# Outside Question loop
# Let's check if we should run the program
if not run:
break
# This will be executed if *run* is False, it will break the Main loop
# Your program