creating a code that use .isdigit - python

I'm new to python. I was creating a code that use .isdigit. It goes like this:
a = int(input("Enter 1st number: "))
if 'a'.isdigit():
b = int(input("Enter 2nd number: "))
else:
print "Your input is invalid."
But when I enter an alphabet, it doesn't come out the "Your input is invalid.
And if I entered a digit, it doesn't show the b, 'Enter 2nd number'.
Is there anyway anyone out there can help me see what's the issue with my code.
That will be a great help. Thanks.

You are assigning the input to a variable a, but when you try to query it with isdigit() you're actually querying a string 'a', not the variable you created.
Also, you are forcing a conversion to an int before you've even checked if it's an int. If you need to convert it to an int, you should do that after you run the .isdigit() check:
a = raw_input("Enter 1st number: ")
if a.isdigit():
a = int(a)
b = int(raw_input("Enter 2nd number: "))
else:
print("Your input is invalid.")

Try to convert your a variable to string type, like this:
a = int(input("Enter 1st number: "))
if str(a).isdigit():
b = int(input("Enter 2nd number: "))
else:
print("Your input is invalid.")

Related

Get True when getting any input (Python)

I'm new to programming. I searched for an answer but didn't seem to find one. Maybe I just can't Google properly.
I want to get something True, when the user inputs anything. Example:
another_number = input("Want to enter another number? ")
What I want:
if another_number = True
float(input("Enter another number: "))
Sure I can say if another_number = ("Yes", "yes", "Y", "y") but in my program I want to get True when entering really anything.
Strings that contain characters are 'truthy', so you can do something like:
if another_number:
x = float(input("Enter another number: "))
The empty string is 'falsy', so this produces nothing:
s = ""
if s:
print("s has characters")
This trick also works on other Python objects, like lists (empty lists are falsy), and numbers (0 is falsy). To read more about it, check out answers to this question.
In python, any non-empty string is evaluated to True.
So, you can simply do:
another_number = input("Want to enter another number? ")
if another_number: #==== Which means 'if True'
float(input("Enter another number: "))
And that will allow for any input.
Alternatively, you can also fo:
another_number = input("Want to enter another number? ")
if another_number!='': #=== if string is not blank as without entering anything, '' is returned. You can also use ```if len(another_number)!=0: where the length of the string is not 0
float(input("Enter another number: "))

Is there a way to enter a specific INTEGER (for example, 3) and have python print same amount of characters (like, entering 3 and printing "aaa" out)

If i entered an integer numeral, like 3, I would like the computer to print the same amount of a particular character, in this case, a. So I want the output to look something like this: (Sorry I am extremely new to python)
> Input: Input a number: 7
> Output: aaaaaaa
Yes,
# take inputs
numOfTimes= int(input("Enter a number : "))
chrc = input("Enter the character : ")
# build the string you want
text = chrc*numOfTimes
# You can multiply a string from integer to repeat it.
print(text)
Example:
Enter a number : 5
Enter the character : A
AAAAA
Yes, it's very easy in fact:
num = int(input("Input a number: "))
print('a'*num)
You may want to verify that the input is an integer, though:
def get_num(msg):
while True:
try:
d = int(input(msg))
if d > 0:
return d
else:
print('Please enter a positive integer.')
except ValueError:
print('Please enter a positive integer.')
num = get_num('Input a number: ')
print('a'*num)

How to Make a Dictionary Accept any Integer to Trigger a Function

Let's say you have the following code:
def statementz():
print("You typed in", number)
digits = {
56 : statementz
}
while True:
try:
number = int(input("Enter a number: "))
except TypeError:
print("Invalid. Try again.\n")
continue
else:
digits.get(number, lambda : None)()
break
I am wondering if there is a way so that one could allow the dictionary to trigger the "statementz" function if the variable "number" holds the value of any integer/float, and not just the integer that is given in the (rather sloppy) example above.
Is it possible to do this? Thank you in advance for any guidance given!
If you want any number to be passed to statementz(), you can simply call it directly after validating it as a number. A dict is only useful if you want to map different numbers to different functions, which is not the behavior you are asking for. Also note that your statementz() should take a number as a parameter since you want to print the number in the function:
def statementz(number):
print("You typed in", number)
while True:
try:
number = float(input("Enter a number: "))
statementz(number)
except TypeError:
print("Invalid. Try again.\n")
Without try-except:
Try using:
def statementz(number):
print("You typed in", number)
while True:
number = input("Enter a number: ")
if number.isdigit():
statementz(number)
break
else:
print("Invalid. Try again.\n")
Example Output:
Enter a number: Apple
Invalid. Try again.
Enter a number: 12ab
Invalid. Try again.
Enter a number: --41-
Invalid. Try again.
Enter a number: 24
You typed in 24

How to insert as many numbers as were mentioned before using raw_input?

I want the user of my program to provide a number and then the user must input that number of numbers.
My input collection code
inp1 = int(raw_input("Insert number: "))
inp2 = raw_input("Insert your numbers: ")
Example:
If the user enters 3 at Insert number: then they have to input three numbers (with spaces between them) at Insert your numbers:.
How do I limit the number of values in the second response to the amount specified in the first response?
I assume, we should use a list to work with.
my_list = inp2.split()
I'm using Python 2.7
Use the len function to get the length of the list, then test if it is correct:
inp1 = int(raw_input("Insert number: "))
inp2 = raw_input("Insert your numbers: ").split()
while len(inp2) != inp1:
print "Invalid input"
inp2 = raw_input("Insert your numbers: ").split()
Another approach would be to get each input on a new line seperately, with a loop:
inp1 = int(raw_input("Insert number: "))
inp2 = []
for i in range(inp1):
inp2.append(raw_input("Enter input " + str(i) + ": "))
This way, there are no invalid inputs; the user has to enter the right amount of numbers. However, it isn't exactly what your question asked.

Python 2.7 getting user input and manipulating as string without quotations

I want to get a string from a user, and then to manipulate it.
testVar = input("Ask user for something.")
Is there a way for testVar to be a string without me having the user type his response in quotes? i.e. "Hello" vs. Hello
If the user types in Hello, I get the following error:
NameError: name 'Hello' is not defined
Use raw_input() instead of input():
testVar = raw_input("Ask user for something.")
input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.
The function input will also evaluate the data it just read as python code, which is not really what you want.
The generic approach would be to treat the user input (from sys.stdin) like any other file. Try
import sys
sys.stdin.readline()
If you want to keep it short, you can use raw_input which is the same as input but omits the evaluation.
We can use the raw_input() function in Python 2 and the input() function in Python 3.
By default the input function takes an input in string format. For other data type you have to cast the user input.
In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting
x = raw_input("Enter a number: ") #String input
x = int(raw_input("Enter a number: ")) #integer input
x = float(raw_input("Enter a float number: ")) #float input
x = eval(raw_input("Enter a float number: ")) #eval input
In Python 3 we use the input() function which returns a user input value.
x = input("Enter a number: ") #String input
If you enter a string, int, float, eval it will take as string input
x = int(input("Enter a number: ")) #integer input
If you enter a string for int cast ValueError: invalid literal for int() with base 10:
x = float(input("Enter a float number: ")) #float input
If you enter a string for float cast ValueError: could not convert string to float
x = eval(input("Enter a float number: ")) #eval input
If you enter a string for eval cast NameError: name ' ' is not defined
Those error also applicable for Python 2.
If you want to use input instead of raw_input in python 2.x,then this trick will come handy
if hasattr(__builtins__, 'raw_input'):
input=raw_input
After which,
testVar = input("Ask user for something.")
will work just fine.
testVar = raw_input("Ask user for something.")
My Working code with fixes:
import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)
correct= False
while(correct == False):
guess1= input("Which number is the highest? "+ str(list) + ": ")
if maxNum == guess1:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
if sqrtOne >= 2.0 and str(guess3) == "y":
print("Correct!")
correct = True
elif sqrtOne < 2.0 and str(guess3) == "n":
print("Correct!")
correct = True
else:
print("Incorrect, try again")
print("Thanks for playing!")
This is my work around to fail safe in case if i will need to move to python 3 in future.
def _input(msg):
return raw_input(msg)
The issue seems to be resolved in Python version 3.4.2.
testVar = input("Ask user for something.")
Will work fine.

Categories

Resources