In my code for guessing game, even when the guess is 1, it returns that the guess is too high. Cant figure it out. Thanks!
Essentially you should not be using raw_input as this will get you a string and not an integer. Try using input
Please see this question for more details: Python read input as integers
Your guessNum is string. Need to make it to int when ever you expect a user to input an integer. For example:
guessNum = int(raw_input('Enter a number between 1 and 100: '))
Related
I have a calculator for my friends. When someone enters an expression like eval(99999999999999999**9999999999999999) my program stops working. How do I fix this if possible? If not, can I just disallow it to be entered and how?
How do I fix this if possible?
You can't. 99999999999999999 to the power of 9999999999999999 is way too big to be computed.
If not, can I just disallow it to be entered and how?
You can set certain constraints on the input by putting it into a while loop:
number = int(input("Enter a number smaller than 100"))
while number > 100:
number = int(input("Enter a number smaller than 100"))
I am new to programming, and I am trying to understand how Python interprets commands, and in this case I am having trouble understanding how Python knows to identify an integer, floating number, or string using a try-except clause. Here is my code (please excuse the cheekiness)
print("DETECTING INPUT TYPE WITH LIMITED CHANCES")
print("Enter an integer and ONLY AN INTEGER. YOU HAVE ONLY 5 CHANCES")
n=0
final=0
for n in range(5):
abc=input()
try:
int(abc) #This line checks for whether the input is an integer. If this is a floating number, the int() operator executes and
# converts the number to an integer
final=1
break
except:
try:
float(abc)
print("WHAT DID I TELL YOU? YOU PUT IN A FLOATING NUMBER! DO IT RIGHT!")
print("Enter an integer and ONLY AN INTEGER")
except:
print("...you put a string didn't you? HOW DARE YOU DEFY THIS PROGRAM? DO IT RIGHT!")
print("Enter an integer and ONLY AN INTEGER")
if final==1:
print("Good... very good, here is your number:",abc)
else:
print("You were given 5 chances and you couldn't get it right.")
This code works as intended, but how does the program throw an exception to allow the try-except clause to execute when I put a floating number? For example, here is what happens when I put "1.0" for my input when executing the program:
DETECTING INPUT TYPE WITH LIMITED CHANCES
Enter an integer and ONLY AN INTEGER. YOU HAVE ONLY 5 CHANCES
1.0
WHAT DID I TELL YOU? YOU PUT IN A FLOATING NUMBER! DO IT RIGHT!
Enter an integer and ONLY AN INTEGER
And then what it looks like when I correct myself and input an integer:
1
Good... very good, here is your number: 1
However, if I manually type in the following into the console, I do not get an error. Instead, the int() command does what it is supposed to, and converts my floating number to an integer.
abc=1.0
int(abc)
Out[3]: 1
What does the try-except clause do to the int() operator to raise an exception and allow my code to execute properly?
Thank you!
The result of input is a string. To replicate it in the console you should do
abc = "1.0"
and then int(abc) will raise a ValueError as expected.
I was using the if not equal to code but I needed the equal to code specifically for lengths from some previous posts I have tried this code of len(pin(4)) however this somehow still doesn't work
thank you in advance
pay =input("card or cash")
if pay ==("card"):
pin = str(input("enter your pin number"))
while True:
if len(pin)!=4:
str(input("not four digit try again"))
if len(pin(4)):
print("payment cleared")
else:
print("payment cleared")
break
There are several problems with your code, starting with the formatting. You may use essentially any form of tabbing or spacing in python, but the convention and general best practice is to use 4 spaces.
Next, the line. if pay ==("card"): is unnecessarily confusing.
if pay == "card": is much clearer and functions identically.
The first big error you make is to ask for the pin outside of the loop. Since your pin = str(input("enter your pin number")) occurs outside of your while True: loop, your program will only accept input once, then will enter an infinite loop unless the else clause of len(pin)!=4 occurs.
The line str(input("not four digit try again")) makes absolutely no sense. Here, you are accepting input in a line which you surely instead meant to use the print statement instead, and on top of that you are unneccessarily converting the value entered via input into a string. A simple print("not four digits! try again.") will suffice here.
The line if len(pin(4)): should throw an error if run, as there is no builtin called pin which you should be able to call with pin(4). The correct syntax would be if len(pin) == 4:.
I made a couple changes in the code below besides those described above to help with usability. I first convert the value of pin to integer to check if the value is a number. I assume that it is not inappropriate to represent a value which must clearly be a number as an integer in your example, but if you really want it to be a string you could use regex to check if it is a number or not with the re module. Something like if re.match('[0-9]{4}', pin): would work in this case.
pay = input("card or cash")
if pay == "card":
while True:
try:
pin = int(input("enter your pin number: "))
if len(str(pin))!=4:
print("not four digits! try again.")
else:
print("payment cleared")
break
except ValueError:
print('not a valid number! try again.')
I'm completely new to Python so all of this is a bit new for me.
I'm trying to create a script in which it by itself thinks of a number and after wards wants the user to guess a number and enter it. It seemed to work but there are wo problems here.
It understands everything however it does not understand the == part.
Because even though the both numbers are the same, it still goes on towards the else statement.
import random
while True:
Thethinker = random.randint(1,10)
Guessnumber = (input("Guess a random number "))
if Guessnumber == Thethinker:
print("Correct")
print(Thethinker)
else:
print("Not correct")
print(Thethinker)
Any help?
Assuming Python 3, input returns a string.
In Python, a string and a number can never be "equal"; you have to transform one or the other. E.g, if you use
Thethinker = str(random.randint(1,10))
then the equality-comparison with another string can succeed.
Your input returns a string instead of an integer. To get an integer do:
int(Guessnumber)
This is better than using str() because then if you ever want to change the numbers, you wouldn't be able to do that without doing the method I suggested
As far as I know, I don't do much Python
I am currently trying to learn Python 2.7 via Learn Python The Hard Way, but have a question about Study Drill 5 of Exercise 35.
The code I'm looking at is:
choice = raw_input("> ")
if "0" in choice or "1" in choice:
how_much = int(choice)
else:
dead("Man, learn to type a number.")
The study drill asks if there is a better way than checking if the number contains zero or one, and to look at how int() works for clues.
I obviously want to be able to accept any number given by the user while dismissing strings, and I understand that int() converts what was given in raw_input() into a number.
So, I tried a couple of ways of amending the if statement which threw up fatal errors when typing a string, but struggled to find anything suitable. I tried variations of the following code, and now understand why they don't work:
choice = int(raw_input("> "))
if choice > 0:
After searching SO I discovered this answer which gives two ways to solve the problem, however try...except and .isdigit() aren't something mentioned in the book at this point.
Is there any other ways to achieve taking user input, converting it to an integer if necessary, and returning an error if not that is appropriate for this stage of the book?
You can write your own is_digit function
def my_digit(input):
digits = ['0','1','2','3','4','5','6','7','8','9']
for i in list(input):
if not i in digits:
return False
return True
So, firstly read what jonrsharpe linked to in the comments and accept that try-except is the best way of doing this.
Then consider what it means to be an integer:
Everything must be a digit (no decimal point, too)
So that's what you check for. You want everything to be a digit.
Thus, for a represents_integer(string) function:
for every letter in the string:
check that it is one of "0", "1", "2", ..., "9"
if it is not, this is not a number, so return false
if we are here, everything was satisfied, so return true
Note that the check that is is one of might require another loop, although there are faster ways.
Finally, consider "", which won't work in this method (or GregS').
Since you already learned sets, you can test that every character is a digit by something like
choice = choice.strip()
for d in choice:
if d not in "0123456789":
# harass user for their idiocy
how_much = int (choice)