After else statement catches invalid input valid input isn't accepted - python

After the else statement catches invalid input and advises the user of this any input after this is caught as invalid input even when the input should be valid. Also, I'm very new to Python so any suggestions on the rest of the code would be appreciated. Below is the code I have written:
from __future__ import division #Allows for division to return a float value
from colorama import init,Fore,Style,Back #Allows for formating color and stylizing text output to terminal screen
init(convert=True) #Allows Colorama to work on Windows 10 machine
import os
running=True
def printAnswer(sign,userInput1,userInput2,answer):
"Prints the formated answer to the screen"
print
print Fore.RED, Style.BRIGHT,userInput1, sign, userInput2, "=", answer, "\n" #Changes text to red
print Style.RESET_ALL #Changes text back to normal from Red
try:
input= raw_input("Press any key to continue")
except NameError:
pass
def printAnswerRemainder(sign,userInput1,userInput2,answerInt,remainder):
"Prints the formated division answer with remainder"
print Fore.Red, Style.BRIGHT, "\n", userInput2, sign, userInput1, "=", answerInt," Remainder ", remainder, "\n" #Changes text color to red
print Style.RESET_All #Resets text color back to normal
def newAdd(userInput1,userInput2):
"Performs the addition function"
sign="+"
answer=userInput1+userInput2
printAnswer(sign,userInput1,userInput2,answer)
def newSub(userInput1,userInput2):
"Performs the Subtraction function"
sign="-"
answer=userInput1-userInput2
printAnswer(sign,userInput1,userInput2,answer)
def newDivision(userInput1, userInput2):
"Performs divsion function giving a decimal answer and an answer with the remainder"
sign="/"
answer=userInput2/userInput1
answerInt=userInput2//userInput1
remainder=userInput2%userInput1
printAnswerRemainder(sign,userInput1,userInput2,answerInt,remainder)
printAnswer(sign, userInput2, userInput1, answer)
def newMult(userInput1,userInput2):
sign="X"
answer=userInput1*userInput2
printAnswer(sign,userInput1,userInput2,answer)
while running==True:
os.system('cls' if os.name == 'nt' else 'clear') #Clears the terminal of previous activity
userSelect=raw_input("Please enter the number of the type of operation you would like to complete:\n\t 1.Addition\n\t 2.Subtraction\n\t 3.Division\n\t 4.Multiplication\n\t 5.Exit\n\n-------> ")
if userSelect=="1":
addNum1=input("Enter the first number to add:\n")
addNum2=input("Enter the second nummebr to add:\n")
newAdd(addNum1,addNum2)
elif userSelect=="2":
subNum1=input("Enter the number to subtract from: \n")
subNum2=input("Enter the number you would like to subtract: \n")
newSub(subNum1,subNum2)
elif userSelect=="3":
divNum1=input("Enter the dividend: \n")
divNum2=input("Enter the divisor: \n")
newDivision(divNum2,divNum1)
elif userSelect=="4":
multNum1=input("Enter the number that is being multiplied: \n")
multNum2=input("Enter the number to be multiplied by: \n")
newMult(multNum1,multNum2)
elif userSelect=="5":
running=False
**else:
print "The command was invalid"
try:
input= raw_input("Press any key to continue")
except NameError:
pass**

In this else clause, you are overwriting the build-in function input:
try:
input= raw_input("Press any key to continue")
Instead, this should work fine:
try:
anykey = raw_input("Press any key to continue")

Related

Open an image when requested

I'm trying to do a silly little program that will let me open an image given a specific number.
import os
c1= os.startfile('Cat1.PNG')
c2= os.startfile('Cat2.PNG')
c3= os.startfile('Cat3.PNG')
catlist= [c1,c2,c3]
valid= False
def cats(valid):
while not valid:
try:
answer=int(input('Choose a number between 1 and 3'))
valid= True
except ValueError:
print("This is not a number")
if answer >=1 and answer <=3:
print(catlist[answer-1])
else:
print('Wrong value')
del (answer)
cats(valid)
return
cats(valid)
My problem is that my pictures just get all open when I start the program, while I want to open them when I choose a specific number.
The problem with your code is in the part where you assign the os.startfile() function to a variable.
When Python interpreter goes through your code, as soon as it hits the c1= os.startfile('Cat1.PNG') line of code, it executes the command and opens the files immediately.
import os
valid = True
def cats(valid):
while valid:
try:
x = int(input("Enter a number here: "))
valid = False
except ValueError:
print("This is not a number!")
if x == 1:
os.startfile('1.jpg')
elif x == 2:
os.startfile('2.jpg')
elif x == 3:
os.startfile('3.jpg')
else:
print("Wrong value")
valid = True
cats(valid)
There is probably a better and more efficient way to do it, but here is a solution I came up with.

Python typewriter function returning none when used within input?

import random,sys,time,os
os.system("cls")
def dialogue(passage): # Function for dialogue to type slowly
for letter in passage:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(0.1)
name = input(dialogue("Hi, WHat is your name?"))
the input would pop up in the terminal as "Hi, WHat is your name?"NONE.
is there any way I can change this to just return the input without it stating NONE where the output should be?
Just add return '' to the end of the dialogue function:
def dialogue(passage):
for letter in passage:
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(0.1)
return ''
name = input(dialogue("Hi, What is your name? "))

How do I get my code to run the if statement?

I'm a beginner in Python and I'm writing a code for a school project and ran into an early bug.
For some reason my if function won't run.
import time #imports computer time to program(buit in function)
count= 0
print(" Gymship") # center this
print("--------------------------------------") # this should go across the whole screen
print("Input a level to view the description or InputSign up to begin signing up for a card")
print("--------------------------------------------------------------------------")
print("Bronze")
time.sleep(1) # this wil pause the program for 1 second(for effect)
print("Silver")
time.sleep(1)
print("Gold")
time.sleep(1)
print("Platinum")
time.sleep(2)
print("-----------------------------------------------") # this should go across the whole screen
print("Sign up")
print(" ")
input()
if input == "Bronze":
print("Bronze")
print("--------------------------------------------")
print("You acquire a bronze card when you use two or less gym services")
print("2 Hours limit in the gym")
print("-------------------------------------")
print(input("Back to return to menu screen"))
count = count + 1
This is not correct:
input()
if input == "Bronze":
The way input() works is by returning a value. The name input refers to the function itself, so the function input will never equal the text "Bronze" unless you explicitly do something bad, like input = "Bronze" (it's bad because if you overwrite input, you'll no longer be able to access that function).
Instead, you should be using the returned value:
usr_input = input()
if usr_input == "Bronze":
Also, the line print(input("Back to return to menu screen")) is unnecessarily complicated; the print() will print whatever was returned by input(), but input() will display the "Back to return to menu screen" prompt without wrapping it in an if statement. So, input("Back to return to menu screen") is all you need. If you keep it the way you have it, if someone typed some text and then hit enter, the text would display again, because the print() is printing whatever that text was that the user typed.
You first need to assign a variable to the input and then check if the variable is equal to "Bronze"
Right now you are taking the input, but are not storing it anywhere. So the fixed code would be
user_input = input()
if user_input == "Bronze":

Error prompt instead of prompt to re enter input

I am making a price is right game. I am currently working on a game mode similar to the contestant row, where they guess the price of an item.
When it asks you to submit a bid, if you enter a word (instead of a bid), the program crashes and displays the following error:
"Traceback (most recent call last):
File "C:\Users\alexe\AppData\Local\Programs\Python\Python36\Thepriceisright.py", line 36, in
contestantrow()
File "C:\Users\alexe\AppData\Local\Programs\Python\Python36\Thepriceisright.py", line 24, in contestantrow
protagnum=int(input(propername +", what is your bid?"))
ValueError: invalid literal for int() with base 10: 'alexei'"
Here's my code:
import random
print(" The Price is Sorta Right - 000776331")
welcomeplayer = True
contestantrow = True
def welcome():
while True:
global welcomeplayer
global propername
welcomeplayer = input("Please enter your name using only letters")
validname = welcomeplayer.isalpha()
propername = welcomeplayer.capitalize()
if validname == True:
print( propername, " ! Come on down! You're the next contestant on the Price is (sorta) right")
print (" Dew Drop welcomes " ,propername ," to contestants row joining EIMNOT A. HUMAN,ARTHURFICIAL EINTEL , ROBORT")
return
else:
print("Please only write letters on your name tag")
welcomeplayer = False
def contestantrow():
while True:
print("Dew Drop shows the price that you are bidding on")
protagnum=int(input(propername +", what is your bid?"))
if protagnum > 0:
componebid = random.randint(1,1000)
print("EIMNOT A. HUMAN bids: ",componebid)
comptwobid = random.randint(1,1000)
print("ARTHURFICIAL EINTEL bids: ",comptwobid)
compthreebid =random.randint(1,1000)
print("ROBORT bids: ",compthreebid)
else:
print(" Dew Drop says [Im sorry bids should start at atleast one dollar]")
contestantrow = False
welcome()
contestantrow()
protagnum=int(input(propername +", what is your bid?"))
You're converting an int / string to int. "1" will work but "a" will raise a ValueError
while True:
try:
protagnum=int(input(propername +", what is your bid?"))
break
except ValueError:
print("Invalid bid, please try again")

Why can't I call a function here?

Hi guys I was working on a shoppinglist-creator code but at the end I faced with a surprise.
My code:
import time
import math
import random
dict_of_lists={}
def addlist():
while True:
try:
listname=str(raw_input("=>Name of the list:\n"))
dict_of_lists[listname]={}
break
except ValueError:
print "=>Please enter a valid name.\n"
print "=>You added a new list named %s.\n" % (listname)
def printlists():
for lists in dict_of_lists:
return "-"+lists
def addproduct():
while True:
try:
reachlistname=input("=>Name of the list you want to add a product,Available lists are these:\n %s \nPlease enter one:\n" % (printlists()))
break
except ValueError:
print "=>Please enter a valid list name.\n"
while True:
try:
productname=raw_input("=>Name of the product:\n")
break
except ValueError:
print "=>Please enter a valid name.\n"
while True:
try:
productprice=input("=>Price of the product:\n")
if isinstance(float(productprice),float):
break
except ValueError:
print "=>Please enter a valid number.\n"
while True:
try:
productcount=input("=>Amount of the product:\n")
if isinstance(int(productcount),int):
break
except ValueError:
print "=>Please enter a valid number.\n"
dict_of_lists[reachlistname][productname]={"price":productprice,"count":productcount}
dict_of_lists[reachlistname]={productname:{"price":productprice,"count":productcount}}
allevents="1-Add a list"+" 2-Add a product to a list"
def eventtochoose():
while True:
try:
event=raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
if not isinstance(int(event),int):
print "\n=>Please enter a number.\n"
else:
if event==1:
addlist()
break
elif event==2:
addproduct()
break
except ValueError:
print "\n=>Please enter a valid input.\n "
while True:
print "%s" % ("\n"*100)
eventtochoose()
So, the problem is (I suggest you run the code) it says "=>What would you like to do? Here are the all things you can do:
1-Add a list 2-Add a product to a list
Please enter the number before the thing you want to do:" and when i put an answer it simply doesn't call the fucntion.
If I put 1 It should have called the fucntion addlist but I think it doesn't. There is nothing to explain I think just look at the code and find the problem if you want to help crocodiles. Thx
When you do int(event), that returns an int if possible, and raises a ValueError if not. So, testing the type of the result doesn't do you any good—if your code gets that far, the type has to be an int.
You already have code to handle the ValueError, so you don't need any other test for the same problem.
Meanwhile, you want to start the number that you got from int(event). That's the thing that can be == 1; the original string '1' will never be == 1.
So:
while True:
try:
event=raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
event = int(event)
if event==1:
addlist()
break
elif event==2:
addproduct()
break
except ValueError:
print "\n=>Please enter a valid input.\n "
You are not converting your input to an integer before comparing, so the comparisons are always false:
'1' == 1 # false
Try:
event = raw_input("=>What would you like to do? Here are the all things you can do:\n %s\nPlease enter the number before the thing you want to do:" % (allevents))
try:
event = int(event)
if event == 1:
addlist()
elif event == 2:
addproduct()
break
except ValueError:
print('Please enter a valid input')

Categories