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.
Related
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.')
All the logic of the program is okay, the program takes the user input and prints an error if the user inputted anything other than a integer, but im not sure how to get the program to loop if the user enters an invalid input.
Passlimit = 10
while Passlimit:
try:
Passinput = int(raw_input("how many characters and numbers would you like for your password to contain? NO LONGER THAN 10 CHARACTERS: "))
if not (Passinput <= Passlimit):
raise ValueError()
except ValueError:
print("Invald input, Please only input numbers")
else:
print("NUMBER SELECTED")
break
The break is immediately following the try...except...else clause. I think you meant to indent the break, so that it is only executed in the else branch.
You would still need to add code though to keep track of the number of tries, otherwise it will loop indefinitely as long as the user provides invalid input.
Completely new to programmming and I'm having quite a few difficulties understanding loops.
I've entered the below code in Python, which tests a users knowledge of the 7 times table:
print('Let\'s test your knowledge of the 7 times table')
table = 7
for i in range(1, 13):
print('What\'s', i, 'x', table, '?')
guess = input()
if guess == 'stop':
break
if guess == 'skip':
print('Skipping. Next question:')
continue
ans = i * table
if int(guess) == ans:
print('You has teh Corrects!')
else:
print('Wrong, it\'s', ans)
print('Finished').')
I wanted to add an 'if' condition to prevent a user from inputting anything other than 'stop', 'skip' or integer input, in order to avoid the 'invalid literal for int() with base 10:' error message. I expressed this as follows:
if guess != int or 'stop' or 'skip':
print('Invalid input. Please enter either a valid command or numeric response.')
continue
I added this code below where the function of the 'skip' input string is defined but when I run the program now it won't recognise numeric input. I've tried inserting this after the point that it's defined that 'guess' can be an integer but at this point the loop doesn't appear to execute this part of the code as I get the 'invalid literal' error I was trying to prevent.
Apologies in advance, I know this is probably a very basic query but I've tried a number of different solutions and I'm struggling to identify whether it's my understanding of loops that's the problem or the way in which I've expressed the '!=' statement.
Thanks
The code you have written in the first part seems like it should work to me, if the break under if guess == "stop" be moved one tab to the right so break is "inside" of the if.
The code in the second part is wrong. You would to it like this:
if guess != "stop" and guess != "skip" and not guess.isdigit():
# Do something.
Use .isdigit():
if not (guess.isdigit() or guess == 'stop' or guess == 'skip'):
print('Invalid input. Please enter either a valid command or numeric response.')
continue
You have to repeat the guess variable, that's why you probably had a syntax error. If not, it was because of the break's indentation.
The error message is caused by the int(guess) itself, and not by the lack of another specific if statement. The int(guess) makes Python try to convert guess to an int and fails (returns a ValueError) if it isn't actually an integer. A way to avoid int(guess) returning an error would be to catch that exception (although I don't know if you've dealt with exceptions yet).
The way this is done is 'trying' to execute int(guess), and if it returns a ValueError, 'catching' that error:
try:
if int(guess) == ans:
print('You has teh Corrects!')
else:
print('Wrong, it\'s', ans)
except ValueError:
print('Invalid input. Please enter either a valid command or numeric response.')
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: '))
UserInput = raw_input('Enter something: ')
print type(UserInput)
print (UserInput)
This is a very simple piece of code that is supposed to tell me what type the enter input is. e.g int or bool. For some reason It always come up as string. Lets say I enter "1" (no quotes) when I am prompted to "Enter Something". That should return as type int. The problem I think lies in the fact that UserInput is a string "raw_input('Enter something: ')". How do I fix my script to return the type the input that the user gave me? I am using python 2.7
The raw_input() function always returns a string, it is documented as such:
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
Emphasis mine.
Perhaps you were looking for input() instead? It evaluates the input given as a Python expression and is the equivalent of eval(raw_input()):
Equivalent to eval(raw_input(prompt)).
This function does not catch user errors. If the input is not
syntactically valid, a SyntaxError will be raised. Other exceptions
may be raised if there is an error during evaluation.
If you entered 1, it'd be interpreted as an integer literal and type(UserInput) would print <type 'int'>.
You are missing a bracket here in the second line. To solve the problem try this:
UserInput = raw_input('Enter something: ')
print(type(UserInput))
print(UserInput)