Integer and string conflicts - python

Currently I'm working on an assignment that requires that I create a program in which the user enters a number between 0-4. The program then checks which number the user inputs and outputs a specific string. For example if the user enters 4, the program will output "80 or above: Level 4"
The problem is that the user should also be able to quit the program. I decided to create the program so if the user inputs something that is not blank (while input != "":) the program will run, but if they decide to hit enter the program will end.
This is the code I've come up with so far:
def get_level():
level = raw_input("Enter a number from 0-4 (Press <Enter> to quit): ")
return level
def check_mark(level):
if int(level) == 4:
print "80 or above: Level 4"
elif int(level) == 3:
print "70 - 79: Level 3"
elif int(level) == 2:
print "60 - 69: Level 2"
elif int(level) == 1:
print "50 - 59: Level 1"
elif int(level) == 0:
print "Below 50: Level 0"
else:
print "ERROR: out of range"
def output(level):
while level != "":
level = raw_input("Enter a number from 0-4 (Press <Enter> to quit): ")
check_mark(level)
print
def main():
user_level = get_level()
user_mark = check_mark(user_level)
print
program_output = output(user_level)
main()
I'm pretty aware that the problem has to do with the fact that raw_input only accepts strings which is what activates the "while level != "":" statement. I tried working around this by placing int() operators before each level. The problem is that it conflicts with the input if the user enters blank since it checks whether the input is an integer. Something like that anyways.
So I was hoping someone could guide me to finding a way around this. It would be much appreciated!

You probably want the next looping code:
def output(level):
level = raw_input("Enter a number from 0-4 (Press <Enter> to quit): ")
while level != "":
check_mark(level)
level = raw_input("\nEnter a number from 0-4 (Press <Enter> to quit): ")

I don't htink there is any shortcut around validating input. So the user can either type "" or an integer. What happens if the user types in letters?
I would verify all input to handle accordingly so the program doesn't break
# check for blank
if level == '':
# exit for user
# validate input if not exit
try:
level_int = int(level)
except ValueErrror:
# integer not inputed
if not (0 <= level_int <= 4):
# check that input is between 0 4
# out of range
or you could just check for expection in check_mark when you call it in main

Related

How can i check if an inputted variable either starts with "Q" or it is a number

I am new so plz help. i am writting a program that adds numbers. it asks for input and until "Q" is inputed it keeps asking for input
def add_num(vari = "" , total = 0):
vari = input("Enter a num or press \"Q\" to stop: ")
while (vari.startswith("Q") and int(vari).isdigit() ) == False:
print("Error")
vari = input("plz enter again: ")
else:
print("Nice")
there are no indentation error. The problem i have is how can i check if it starts with "Q" or it is a number. I think this is the code that has errors
while (vari.startswith("Q") and int(vari).isdigit() ) == False:
vari.isdigit() is enough to check that all characters are digits.
You have a logic error in the while condition: it cannot be that vari.startswith("Q") and at the same time vari.isdigit(), so that would be always false, and comparing that to False would always be true.
Change it to while (vari.startswith("Q") or vari.isdigit()) == False:

How to create a number menu in python

i need a simple python code which makes a number menu, that doesn't take up many lines
print ("Pick an option")
menu =0
Menu = input("""
1. Check Password
2. Generate Password
3. Quit
""")
if (menu) == 1:
Password = input("Please enter the password you want to check")
points =0
i tried this but it did not work how i thought it would. i thought this code would work as i have tried it before and it worked but i must have made a mistake in this one.
anyone have any suggestions?
thanks
this is my full code:
print ("Pick an option")
menu =0
Menu = input("""
1. Check Password
2. Generate Password
3. Quit
""")
if (menu) == 1:
Password = input("Please enter the password you want to check")
points =0
smybols = ['!','%','^','&','*','(',')','-','_','=','+',]
querty =
["qwertyuiop","QWERTYUIOP","asdfghjl","ASDFGHJKL","zxcvbnm","ZXCVBNM"]
if len(password) >24:
print ('password is too long It must be between 8 and 24 characters')
elif len(password) <8:
print ('password is too short It must be between 8 and 24 characters')
elif len(password) >=8 and len(password) <= 24:
print ('password ok\n')
There are some fundamental flaws with your code that tells us you are not sure what the difference between types are (str vs int), or what some functions actually do (input()). These need to be corrected before you progress any further with your program.
Lets take a look at what your code currently does:
print ("Pick an option") # prints a message
menu = 0 # initializes a variable (menu) of type int to 0
Menu = input(""" # prints a message to receive input for variable (Menu) of type str
1. Check Password
2. Generate Password
3. Quit
""")
if (menu) == 1: # conditional check against (menu) to int of 1
...
Now stop here and look a little closer:
menu = 0 this sets a variable called menu equal to 0; the variable has a lowercase m and is of type int since you initialized it with an int.
Menu = input(...) this sets a variable called Menu equal to a str received from input(). So if you input 1, then what happens is a str is returned such that Menu = '1'. Notice that the variable has an uppercase M unlike menu before it; also note the ' ' around the 1. That means this is a str.
if (menu) == 1:... this checks the lower case'd menu against 1. Well you initialized menu = 0 and then you never touch the lower case'd menu again, so when you get to this it is still 0. So of course this will fail.
Given all that, here is what you can do to fix your code:
menu = 0
menu = int(input("Pick an option:\n"
"1. Check Password\n"
"2. Generate Password\n"
"3. Quit\n\n"
"Option Selected: ")
if (menu) == 1:
....
Because you are comparing a str and int. convert it into int
print ("Pick an option")
Menu = int(input("""
1. Check Password
2. Generate Password
3. Quit
"""))
if Menu == 1:
Password = input("Please enter the password you want to check")
points =0

Creating a "Flashcard" vocabulary program

I'd like to make a program in Python 3 that would be essentially vocabulary flashcards. I'd be able to list the terms, add a term, or display a random definition to try and accurately guess. Once guessed accurately, I would be given the option for another definition to guess. Alternatively, I'd like to just be able to display a random key:value pair, and to continue viewing pairs until I enter EXIT.
I have made most of the program using a dictionary, but am not sure how to go about with entering the proper command to enter the key for the definition displayed. If anyone could provide suggestions, I'd appreciate it! Also I got some sort of error message when entering this code in and had to do a bunch of indentations, not sure what I did wrong there.
import random
terms = {"1" : "def 1", #Dictionary of 'terms' and 'definitions'
"2" : "def 2",
"3" : "def 3"}
menu = None
while menu != "4":
print("""
DIGITAL FLASHCARDS!
1 - List Terms
2 - Add Term
3 - Guess Random Definition
4 - Exit
""")
menu = input("\t\t\tEnter Menu option: ")
if menu == "1": # List Terms
print("\n")
for term in terms:
print("\t\t\t", term)
input("\n\tPress 'Enter' to return to Main Menu.\n")
elif menu == "2": # Add Term
term = input("\n\tEnter the new term: ").upper()
if term not in terms:
definition = input("\tWhat is the definition? ")
terms[term] = definition
print("\n\t" + term, "has been added.")
else:
print("\n\tThat term already exists!")
input("\n\tPress 'Enter' to return to Main Menu.\n")
elif menu == "3": # Guess Random Definition. Once correct, choose new random definition
print("\n\t\t\tType 'Exit' to return to Menu\n")
choice = random.choice(list(terms.values()))
print("\n\t" + choice + "\n")
guess = None
while guess != "EXIT":
guess = str(input("\tWhat is the term? ")).upper()
display a random definition to try and accurately guess. Once guessed accurately, I would be given the option for another definition to guess
Use terms.items() to get key and value at the same time.
Define the process of generating a new definition question into a function generate_question() to avoid duplicity.
elif menu == "3": # Guess Random Definition. Once correct, choose new random definition
print("\n\t\t\tType 'Exit' to return to Menu\n")
def generate_question():
term, definition = random.choice(list(terms.items()))
print("\n\t" + definition + "\n")
return term
term = generate_question()
guess = None
while guess != "EXIT":
guess = input("\tWhat is the term? ").upper()
if guess == term:
print("Correct!")
if input("\tAnother definition?(y/n)").upper() in ["Y", "YES"]:
term = generate_question()
else:
break
Alternatively, I'd like to just be able to display a random key:value pair, and to continue viewing pairs until I enter EXIT.
elif menu == "4": # Random display a term-definition pair.
print("\n\t\t\tType 'Exit' to return to Menu\n")
exit = None
while exit != "EXIT":
term, definition = random.choice(list(terms.items()))
print(term + ":", definition)
exit = input("").upper() # Press enter to continue.
Remember to modify the beginning part:
while menu != "5":
print("""
DIGITAL FLASHCARDS!
1 - List Terms
2 - Add Term
3 - Guess Random Definition
4 - View term-definition pairs
5 - Exit
""")

chr() ord() entering spaces ValueError: chr() arg not in range(0x110000)

I am trying to create a Vigenere Cypher in python and have come across this problem (it is probably me being either blind or just stupid!) and need some assistance, the main encrypt/decrypt function works fine but I am trying to include spaces in the input message and keyword, when I try and type in "hello there" by the keyword "hello there" it gives me this output
crypt += chr(new)
ValueError: chr() arg not in range (0x110000)
this is my code:
import sys #This imports the "system" module, this allows me to safely close the code
accept_yes = ["YES", "Y"]
accept_no = ["NO", "N"]
accept_encrypt = ["ENCRYPT", "E"]
accept_decrypt = ["DEDCRYPT", "D"]
accept_exit = ["EXIT"] #These lists create a group of allowed inputs
def Task2(): #This defines a function so I can call it later in the code
encrypt_or_decrypt = input("Do you wish to Encrypt, Decrypt or Exit? ").upper() #This asks the user to type whether they would like to Encrypt, Decrypt or Exit the code
if encrypt_or_decrypt in accept_encrypt: #This checks if the user input is one of the words inside the "accept_encrypt" list at the top of the code
print("You chose Encrypt") #It then confirms the choice
elif encrypt_or_decrypt in accept_decrypt: #This checks if the user input is one of the words inside the "accept_decrypt" list at the top of the code
print("You chose Decrypt") #It then confirms the choice
elif encrypt_or_decrypt == ("EXIT"): #Then checks if the input was "Exit"
print("Closing...\n\n\n\n\n\n") #If it was, tell the user that the code is closing
sys.exit() #This shuts down the running code safely (made possible my the "import sys" at the top)
else: #If the input was not in any of the lists above it will do the following
print("Invalid Input") #Let the user know what has happened
print("Try again") #And tells them to retry
Task2() #It then calls the "Task2" function
plaintext = input("Please enter the message you wish to Encrypt/Decrypt: ").upper() #This asks the user to input a message of their choice to encrypt/decrypt
if not all(x.isalpha() or x.isspace() for x in plaintext): #This part checks if the "msg" variables has any spaces in it or has any numbers/symbols
print("Invalid input") #If it does then
print("Try again")
Task2()
if len(plaintext) == 0: #This checks if the length of the input is 0 characters and if so...
print("Invalid input length") #Tell them what happened
print("Key must be of length 1 or more") #Explains what the problem was
print("Please try again") #And lets them retry
Task2() #Then calls the "Task2" function
keyword = input("Enter a key to offset your code: ").upper() #This asks for a different user input for the keyword to offset the previous message by
if not all(x.isalpha() or x.isspace() for x in keyword): #This part checks if the "msg" variables has any spaces in it or has any numbers/symbols
print("Invalid input") #If it does then
print("Try again")
Task2()
if len(keyword) == 0: #This checks if the length of the input is 0 characters and if so...
print ("Invalid input length") #Tell them what happened
print("Key must be of length 1 or more") #Explains what the problem was
print("Please try again") #And lets them retry
Task2() #Then calls the "Task2" function
crypt = ('') #This sets a blank variable which will be altered to be the final message
decrypt = ('') #This sets a different blank variable which will be altered to be the final message
for n in range(0, len(plaintext)):
new = ord(plaintext[n]) + ord(keyword[n%len(keyword)]) - 65 #This set the variable "new" as the ascii number of the message plus the ascii number of the keyword
if new > 90: #This checks if the "new" variable is larger than 90...
new -= 26 #If it is, minus 26 from what it was originally
crypt += chr(new) #This makes "crypt" the ascii letter + the "new" value
new = ord(plaintext[n]) - ord(keyword[n%len(keyword)]) + 65 #This set the variable "new" as the ascii number of the message minus the ascii number of the keyword
if new < 65: #If the "new" variable value is less than 65...
new += 26 #Make "new" 26 more than it was originally
decrypt += chr(new) #And makes "decrypt" the ascii letter + the "new" value
if encrypt_or_decrypt in accept_encrypt: #If they wanted to encrypt...
print ("\nEncrypted message: " + crypt + "\n") #print the final message to the user
Restart() #Calls the "Restart" function
elif encrypt_or_decrypt in accept_decrypt: #If they wanted to decrypt...
print ("\nDecrypted message: " + decrypt + "\n") #print the final message to the user
Restart() #Calls the "Restart" function
def Restart(): #This defines a function so I can call it later in the code
restart = input("Would you like to restart?\n").upper() #This asks the user if they want to restart
if restart in accept_yes: #If the input is in the "accept_yes" list at the top of the code...
print ("Restarting...\n\n\n\n\n\n") #Tell the user that the code is restarting
Task2() #Then call the "Task2" function I defined
elif restart in accept_no: #If the input is in the "accept_no" list at the top of the code...
print ("Closing...\n\n\n\n\n\n") #Tell the user that the code is closing
sys.exit() #Safely shuts down the running code
else: #If the input was none of these...
print ("Invalid Input") #Tell the user what the problem was
Restart() #Calls the "Restart" function again
Task2() #This calls the actual encryption/decryption function
I would really appreaciate it if someone could help me with the problem I am facing!
If both the plain text character and the keyword are spaces (ASCII 32) you end up with negative 1:
>>> plain = keyword = ' ' # space is ASCII 32
>>> ord(plain) + ord(keyword) - 65 # 32 + 32 - 65
-1
>>> chr(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: chr() arg not in range(0x110000)
You'll have to consider how to handle this case in your cipher, or strip spaces altogether, which is what traditionally was done.
If you wanted to include the spaces, just add them to the ciphertext and continue (at the risk of making it easier to crack your code):
for n in range(0, len(plaintext)):
if plaintext[n] == ' ':
crypt += ' '
decrypt += ' '
continue
# your original loop body
Another option is to disallow spaces in the key; you'll get encrypted text where spaces in the plaintext are encrypted to a space, the symbols !"#$%&\'()*+,-. or the digits 0 through to 9. To do this simply change
if not all(x.isalpha() or x.isspace() for x in keyword):
to
if not keyword.isalpha():

Python 3.x - If quitting program, at the y/n conditional how do I make the no answer go back to the start of program?

I'm trying to create a high scores program. It has to be able to do the following:
1. Display the names / scores
2. Add a name / score
3. Delete a name / score
4. Sort list ascending
5. Sort list descending
6. Quit option < this is where I'm having an issue
I can't figure out how to make the y/n quit conditional at the end go back to the start of the program.
import sys
#declaring variables
choice = int()
name = str()
score = int()
entry = (name, score)
scores = [("Moe", 1000), ("Larry", 1500), ("Curly", 3000), ("Mirza", 9000), ("George", 100)]
#asking user to choose
print ("Please enter your choice.")
print ("0 = quit, 1 = List players and scores, 2 = Add more scores, 3 = Delete score, 4 = sort ascending, 5 = sort descending")
choice = input()
if choice == "1":#this lists the already pre-defined list
for entry in scores:
name, score = entry
print (name, "\t", score)
elif choice == "2":#this adds a name / score to the list
print("What is the player's name?")
name = input()
print("What score did the player get?")
score = int(input())
entry = (name, score)
scores.append(entry)
print(scores)
elif choice == "3":#this deletes a name / score from the list
print("What is the player's name you wish to delete?")
name = input()
print("What is said players score?")
score = int(input())
entry = (name, score)
scores.remove(entry)
print(scores)
elif choice == "4":#this sorts in ascending order
scores.sort()
print(scores)
elif choice == "5":#this sorts in descending order
scores.sort(reverse = True)
print(scores)
else:#here is a conditional y/n statement to quit program
print("Are you sure you want to quit? Please enter y for yes and n for no")
response = input().lower()
if response == "y":
sys.exit(0)
## elif response == "n":
###How do I make the N conditional go back to the start of the program???? I can't figure this out.
You will definitely need a loop of some kind. This could work for you:
while True:
# do some stuff
if (want_to_go_to_start_early):
continue # Go back to the start of the loop
if (want_to_exit_loop):
break # Exit the loop
# do other stuff in the loop
# at the end of the loop it goes back to the top
# stuff outside the loop (only gets reached after the 'break')
You can simply do:
exit = ''
while( exit != 'yes' ):
menu() # print menu
in menu you if exit will get set to 'yes' program ( loop ) will end.
So you can have choice like - Exit program? where you set exit to 'yes', and you can aswell ask for confirmation.
A slightly different take on the problem would be to recursivly call your main sequence again on the "no" condition and return on the "yes" condition.
def main():
#do stuff
if(condition == 'y'):
return;
else:
main();
your going to need to enclose your main program in a loop like:
def display_menu():
start_over=False
print ("Please enter your choice.")
print ("0 = quit, 1 = List players and scores, 2 = Add more scores, 3 = Delete score, 4 = sort ascending, 5 = sort descending")
choice = input()
if choice == "1":#this lists the already pre-defined list
...
....
....
if choice == "0":
start_over=True
return start_over
while true:
play_game()
...
...
start_over_flag=display_menu()
if not start_over_flag:
break
sys.exit()
Read up on looping mechanisms and functions in the python documentation. The Docs will become your best friend these next few months.
make sure you are reading the right version (I linked you the latest, but you may be using 2.7 instead of 3.x)

Categories