match = input('Enter match? ')
odd1 = input("Enter tip for home: ")
if(not odd1.replace(".","").isnumeric()):
print("Sorry home tip is not numeric")
exit(0)
if(float(odd1)<=1):
print("Odd cannot be less than one")
exit(0)
odd2 = input("Enter tip for draw: ")
if(not odd2.replace(".","").isnumeric()):
print("Sorry draw tip is not numeric")
exit(0)
if(float(odd2)<=1):
print("Odd cannot be less than one")
exit(0)
odd3 = input("Enter tip for away: ")
#isnumberic() is it number
if(not odd3.replace(".","").isnumeric()):
print("Sorry your tip is not numeric")
exit(0)
if(float(odd3)<=1):
print("Odd cannot be less than one")
exit(0)
print("Thank you, your odd is: ")
print("Match: ", match)
print("Home: ", odd1)
print("Draw: ", odd2)
print("Away: ", odd3)
Generally replace(val1, val2) method changes old value with a new one which is second argument. Why in this code checks if number is float. If I type float number in odd1 without replace, I am getting the message Sorry home tip is not numeric?
odd1.replace(".","") means that change every dot in the string odd1 into to nothing (means delete it) generally .replace() is used to search about a char in a string and replace it with another
for example
s = "Hello. world"
r = s.replace(".", ",")
print(r)
this code replace every dot in the string s with a comma
and then .isnumeric() tests if the value of odd1 after replacing is a number or not
Related
So I've almost finished a program in which the user inputs a name/word and it spits out the Soundex counterpart.
The code runs well and the Soundex methodology is sound, "Get it Sound". What I had issues with were the strings being returned. Things like space before or after the word typed in or having an uppercase and lowercase name being repeated when they shouldn't have been. Those got fixed rather easily.
What I'm having issues with now is when the user inputs something like, "Carl Sagan" it returns the ("Word should only contain characters") elif of my program.
What I'd like to do is respond to the user and say, ("Two words entered at once, Please enter one at a time."). When those instances happen.
Here's a snippet of my code:
#input name
name = input("To start, Please give your name :")
print("\nGreetings,", name.strip().capitalize(), "Your Soundex-name is:", convert_to_soundex(name), "\n" )
#creating dictionary
dicti={}
#convert name to code and store in dictionary
dicti[name]=convert_to_soundex(name)
# keeping asking user for a word or name until user enters 0
while(True):
word=input("Please give a word to convert (0 to exit) :").strip().capitalize()
if word=='0':
break
elif word=="":
print("Please give word with atleast one character.")
elif not word.isalpha():
print("Word should only contain characters.")
else:
if word in dicti:
print("Word already exists")
else:
dicti[word]=convert_to_soundex(word)
#printing formatted data
printData(dicti)
You can add another while..if instead of name input like this:
while True:
name = input("To start, Please give your name :")
if ' ' in name:
print("Two words entered at once, Please enter one at a time.")
else:
break
#input name
name = input("To start, Please give your name :")
print("\nGreetings,", name.strip().capitalize(), "Your Soundex-name is:", convert_to_soundex(name), "\n" )
#creating dictionary
dicti={}
#convert name to code and store in dictionary
dicti[name]=convert_to_soundex(name)
# keeping asking user for a word or name until user enters 0
while(True):
word=input("Please give a word to convert (0 to exit) :").strip().capitalize()
if word=='0':
break
elif ' ' in word:
print("Two words entered at once, Please enter one at a time.")
elif word=="":
print("Please give word with atleast one character.")
elif not word.isalpha():
print("Word should only contain characters.")
else:
if word in dicti:
print("Word already exists")
else:
dicti[word]=convert_to_soundex(word)
#printing formatted data
printData(dicti)
name = input("give name please...")
for nam in name:
if nam == " ":
print('invalid input')
# removes space from input
print(''.join([i for i in name if i != " "]))
I am currently new to Python and trying to construct a program that takes two integers and outputs whether they are larger, smaller than each other or both equal. I also want to add a while loop which asks for 2 more sets of integers each time, otherwise if the user types "quit" the program ends. Only issue is, I think my casting is off as when I type quit, it actually compares that. So if I typed quit twice it would state they're equal which is true rather than stop the program.
onenumber = int(input("Please enter your first number to compare:"))
twonumber = int(input("Please enter your second number to compare:"))
if onenumber > twonumber:
print (onenumber, "is the biggest!")
elif twonumber > onenumber:
print (twonumber, "is the biggest!")
else:
print ("Both are equal!")
while onenumber != "quit":
onenumber = input("Please enter your first number to compare, or type quit:")
twonumber = input("Please enter your second number to compare:")
if onenumber > twonumber:
print (onenumber, "is the biggest!")
elif twonumber > onenumber:
print (twonumber, "is the biggest!")
else:
print ("Both are equal!")
I changed your code slightly to begin in the while loop. Ideally, you want as few lines of code as you can and as you had two repeated lines I removed them.
Now that both number variables are not cast as int we can use the in-built string function .isdigit() which returns a True or False if the variable is a digit. This helps us out by ensuring there won't be an error when comparing them.
Happy to answer any questions you have!
while True:
number_one = input("Please enter your first number to compare or type 'quit':")
number_two = input("Please enter your second number to compare:")
if number_one.isdigit() and number_two.isdigit():
number_one = int(number_one)
number_two = int(number_two)
if number_one > number_two:
print(number_one, "is the biggest!")
elif number_two > number_one:
print(number_two, "is the biggest!")
else:
print("Both are equal!")
elif number_one == "quit":
print("Thanks for playing!")
exit()
else:
print("Please enter a number or type 'quit'!")
Actually your program does exactly what it should do. But think about it, your condition is stating: As long as onenumber is not "quit" execute all commands inside the while loop. So if your onenumber variable is "quit" it will still perform the comparison ONE TIME more before it ends the program. But after that your program will stop. But obviously this won't happen because an exception will occur. You can verify it with below code:
number1 = "proceed"
while number1 != 'quit':
number1 = str(input("declare number1"))
number2 = str(input("declare number2"))
try:
if int(number1) > int(number2):
print("number1 is is bigger than number2")
elif int(number1) < int(number2):
print("number2 is bigger than number1")
else:
print("both numbers are equal")
except:
pass
One solution for example without Exception handling would be the following:
number1 = "proceed"
while number1 != 'quit':
number1 = str(input("declare number1"))
number2 = str(input("declare number2"))
if number1 != 'quit':
if int(number1) > int(number2):
print("number1 is is bigger than number2")
elif int(number1) < int(number2):
print("number2 is bigger than number1")
else:
print("both numbers are equal")
Its easier to ask for forgiveness than permission.
https://docs.python.org/3.4/glossary.html
number_1 = input("Please enter your first number to compare or type 'quit':")
number_2 = input("Please enter your second number to compare:")
try:
smaller = int(number_1) < int(number_2)
same = int(number_1) is int(number_2)
if smaller:
print(number_1, "is the smaller")
else:
print(number_2, "is the biggest")
if same:
print("Both are equal")
except ValueError:
if number_1 == "quit"
print("Thanks for playing!")
I am brand new to Python and am trying to build a text based game.
The first question is "How old are you?"
How can I use if/else statements to print a certain message when the user doesn't input his age.
for instance if the user inputs a character instead of a letter I want to print "please enter a digit, not characters" or if the user inputs a digit smaller than 12 I want to print "You are not old enough" and if the user inputs a digit greater or equal to 12 I want to say "Welcome"
I have written some code to try and do this myself and spent about 4 hours on it but can't figure it out.
This is my block of code:
input_age = raw_input("What is your age, " + input_name + "? ")
if len(input_age) == 0:
print("You didn't enter anything")
elif input_age < 12 and input_age.isdigit():
print("Sorry, you are not old enogh to play")
elif input_age >= 12 and input_age.isdigit():
print ("Welcome")
else:
print("You entered a character or characters instead of a digit or digits")
For some reason the elif on line 4 gets skipped or something because even if i enter 4 as my age it still carries on and prints "Welcome" instead of "You are not old enough"
#roganjosh is right, raw_input returns a string, so you have to do the below:
input_age = raw_input("What is your age, " + input_name + "? ")
if not input_age:
print("You didn't enter anything")
elif input_age.isdigit():
if int(input_age) < 12 :
print("Sorry, you are not old enogh to play")
elif int(input_age) >= 12:
print ("Welcome")
if not input_age.isdigit():
print("You entered a character or characters instead of a digit or digits")
I have this problem when i run the program it all goes good an all, but when a user gets the right answer, the code does not print neither print("Good Job!") or print("Correct"). what is wrong with the code ?
import random
firstNumber = random.randint(1, 50)
secondNumber = random.randint(1, 50)
result = firstNumber + secondNumber
result = int(result)
print("Hello ! What\'s your name ? ")
name = input()
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
userAnswer = int(input("Your answer : "))
while (userAnswer != result) :
if (userAnswer > result) :
print("Wrong")
else:
print("Wrong")
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
input("\n\n Press to exit")
The problem is that your while-loop will only run as long as the first answer is wrong. Everything that is indented after while (userAnswer != result) will be ignored by Python if the first answer is right. So logically a first correct answer can never reach print("Correct"), since that would require the answer to be both wrong (to start the while loop) and right (to get to "Correct").
One option is to get rid of the while-loop, and just use if's. You get two chances this way, then you lose.
if (userAnswer == result):
print("Well done!")
else:
print("Wrong")
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
else:
print("Nope all wrong you lose")
Another option is to make an infinite loop using While. (like #csharpcoder said)
while (True) :
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print ("Wrong answer")
In the last option a wrong answer gets "Wrong answer" and the while-loop starts again, since True is of course still True. So you try again, until you get the right answer, which will bring you to "correct, good job" and then break (which stops the loop).
I struggled with while-loops and kind of getting it in my head that indentation means Python will treat it as 'one thing' and skip it all if I start it with something that's False.
If the answer is correct, then
while (userAnswer != result) :
will cause the loop contents to be skipped.
First of all, you get input outside of your loop and then don't do anything with it. If your answer is correct on the first try, you will get no output because userAnswer != result will be False immediately and your while loop won't run.
Some other points:
if (userAnswer > result) :
print("Wrong")
else:
print("Wrong")
is redundant because you are guaranteed to fall into one of these, as you will only get here if the answer is wrong (and therefore > or < result). Just print "Wrong" without a condition, as the only reason this would run is if the answer was wrong.
print("Correct")
print("Good Job!")
You can use \n to print on a new line instead of having multiple print statements together. Usually you only use multiple prints together for readability, but print("Correct\nGood job!") isn't that much less readable.
if (userAnswer == result):
#...
break
You don't need break here because the answer is already correct and the loop won't repeat anyway.
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
Here, you append string literals to string literals ("Hello!" + " "). You don't need to do that as you can just write "Hello! ".
result = firstNumber + secondNumber
result = int(result)
The result (pun not intended) is already an integer, so you don't need to convert it.
How about using a infinite while loop something like this :
while (True) :
userAnswer = int(input("Your answer : "))
if (userAnswer == result):
print("Correct")
print("Good Job!")
break
else:
print ("Wrong answer")
In your logic if you enter the wrong answer first time and correct answer afterwards , then it will work as per your requirement , but if you enter the correct answer first time it will simple skip the while loop .
I played around a bit to refactor, in an attempt to make it more clear:
import random
name = input("Hello ! What's your name? ")
print("Hello, {name}!".format(name=name))
print("Ok, {name}, let's start!".format(name=name))
first_number = random.randint(1, 50)
second_number = random.randint(1, 50)
correct_answer = first_number + second_number
print("What is, '{first} + {second}'?".format(first=first_number,
second=second_number))
user_answer = None
while user_answer != correct_answer:
try:
user_answer = int(input("Your answer : ")) # ValueError will be raised if non integer value given
except ValueError:
print("Invalid Input!")
user_answer = None
if user_answer:
if user_answer == correct_answer:
print("Correct")
print("Good Job!")
else:
print('--> Wrong, try again!')
input("\n<< Press any key to exit >>")
Alright, I'm doing this for a project and whenever I attempt to have it divide by zero or square root a negative number that program closes out. I've attempted to find something I can insert into the code to make it display a message and then prompt for the value again, but everything that I've tried inserting causes the program to close out instantly when I start it up.
Here's the calculator without anything inserted to fix the crashes.
import math
def convertString(str):
try:
returnValue = int(str)
except ValueError:
returnValue = float(str)
return returnValue
def addition(a, B):
return convertString(a) + convertString(B)
def subtraction(a, B):
return convertString(a) - convertString(B)
def multiplication(a, B):
return convertString(a) * convertString(B)
def division(a, B):
return convertString(a) / convertString(B)
def sqrt(a):
return math.sqrt(convertString(a))
keepProgramRunning = True
print "Welcome to [Removed]'s 2011 4-H Project! This is a simple calculator coded in Python, which is a high-level programming language. Java, C, C++, and Perl are other high-level programming languages that you may have heard of."
while keepProgramRunning:
print ""
print "Please choose what you would like to do:"
print ""
print "1) Addition"
print "2) Subtraction"
print "3) Multiplication"
print "4) Division"
print "5) Square Root"
print "6) Quit Program"
choice = raw_input()
if choice == "1":
numberA = raw_input("Enter your first addend: ")
numberB = raw_input("Enter your second addend: ")
print "The sum of those numbers is:"
print addition(numberA, numberB)
elif choice == "2":
numberA = raw_input("Enter your first term: ")
numberB = raw_input("Enter your second term: ")
print "The difference of those numbers is:"
print subtraction(numberA, numberB)
elif choice == "3":
numberA = raw_input("Enter your first factor: ")
numberB = raw_input("Enter your second factor: ")
print "The product of those numbers is:"
print multiplication(numberA, numberB)
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
print division(numberA, numberB)
elif choice == "5":
numberA = raw_input("Enter the number you wish to find the square root of: ")
print "Your result is:"
print sqrt(numberA)
elif choice == "6":
print "Goodbye! Thank you for your time spent both judging my project and those of everyone else! Have a nice day! (。◕‿◕。)"
keepProgramRunning = False
else:
print "Please choose a valid option."
print "\n"
I'm not real sure what to insert and where to solve the crashes, but I think the problem lies with my placement.
I've been attempting to insert something like this:
except ValueError:
print "You cannot divide by zero. Please choose another divisor."
numberB = raw_input("Enter your divisor: ")
Would that work? Where would I insert it? If it wouldn't work, what would and where would it go?
I've been attempting to put it after
numberB = raw_input("Enter your divisor: ")
So that section would read
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
except ValueError:
print "You cannot divide by zero. Please choose another divisor."
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
print division(numberA, numberB)
But as I said, the program will close as soon as it opens when I do try that. Also, I know that if they inputted 0 again the program would crash. Is there any way to make it return to the line that it's under?
Also, for closing the program, the message it is supposed to display can't be read as the program is closing immediately after it's displayed, or the commands are being executed at the same time. Either way, the message can't be read. Is there any way to make the message appear in a separate dialog window that will cause the program to close when the window is closed? Or at least a way to make it delay before closing?
Please correct me if I got any terminology wrong. I'm still somewhat new to this.
And, as always, (constructive) feedback for any part of the program is always appreciated.
The problem is that you are trying to catch an exception before it is thrown. Instead, try this:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
while float(numberB) == 0:
print "You cannot divide by zero. Please choose another divisor."
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
print division(numberA, numberB)
Here's your answer without exception handling.
Essentially you just make this questionable input at the beginning of an infinite loop, but break out when you find that the input is all good.
For your square root:
elif choice == "5":
while True:
numberA = raw_input("Enter the number you wish to find the square root of: ")
if float(numberA) >= 0:
break
print "Cannot take the square root of a negative number."
print "Your result is:", sqrt(numberA)
and for division:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
while True:
numberB = raw_input("Enter your divisor: ")
if numberB != "0":
break
print "You cannot divide by zero. Please choose another divisor."
print "The quotient of those numbers is:", division(numberA, numberB)
And to make your program stall before it closes:
elif choice == "6":
print "Goodbye! Thank you for your time spent both judging my project and those of everyone else! Have a nice day! (。◕‿◕。)"
raw_input('')
keepProgramRunning = False
Cheers!
You should use exceptions, like you're already doing in convertString.
try:
result = division(numberA, numberB)
print "The quotient of those numbers is:"
print result
except ZeroDivisionError:
print "You cannot divide by zero. Please choose another divisor."
Your format of the try:...except: statement is wrong. Try this:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
print "The quotient of those numbers is:"
try:
print division(numberA, numberB)
except ZeroDivisionError:
print "You cannot divide by zero. Please choose another divisor."
This does not answer your coding question, but I think it is worth to comment.
sqrt: The square root of a negative number is an imaginary number. Python supports complex numbers with complex(real_part, imaginary_part).
so your sqrt calculation could be written as:
elif choice == "5":
numberA = raw_input("Enter the number you wish to find the square root of: ")
numberA = float(numberA)
if numberA < 0:
sqrt_numberA = complex(0, sqrt(abs(numberA)))
else:
sqrt_numberA = sqrt(numberA)
print "Your result is:", sqrt_numberA
division: A division by 0 is infinite. Python indicates infinite with 'inf'. In fact, it returns 'inf' with numbers higher than 1E309:
>>> 1E309
inf
and the division of two of these numbers produces 'nan'
>>> 1E309/1E309
nan
so that you could write:
elif choice == "4":
numberA = raw_input("Enter your dividend: ")
numberB = raw_input("Enter your divisor: ")
try:
div = division(numberA, numberB)
except ZeroDivisionError:
div = 'inf'
print "The quotient of those numbers is:", div
this code should be additionally extended to return -inf, when numberA is negative, and to take into account situations such as 0/0