Here I am coding in python for get output of length of any string. If user enter a integer value then print "Integer doesn't have length" else print the length of string.
Here is my code
def string_length(word):
if type(word) == int:
print("Integer doesn't have length")
else:
print("Length:", len(word))
word = input("Enter Word: ")
string_length(word)
print("End of Program!")
Here is my output result
Enter Word: 65
Length: 2
End of Program!
Thanks in Advance!
It's because input in python is taken as a string by default. One of the ways you can do this is checking string is numeric or not.
if word.isnumeric():
print("Integer doesn't have a length")
Related
I want a validation method that ensures that value entered is valid, it must be a integer (can include negative) and must not be blank. I have written this code, however not correct, can someone help me please. Thank you
If (b <> Integer Or " ") Then
Console.WriteLine("Value entered must be a number")
End If
new code:
Line98:
Console.WriteLine("Please input the value of, B:")
b = Console.ReadLine()
If Not Integer.TryParse(b, New Integer) Then
Console.WriteLine("Value entered must be a number")
GoTo Line98
End If
so i used a select statement, and if a user enters "abckak" any non numerical data i get an error Unhandled Exception: System.InvalidCastException: Conversion from string "gakjdg" to type 'Integer' is not valid.
how could this be fixed, this is a quick example of my code
Console.WriteLine("..........Main Menu..........")
Console.WriteLine("Please input 1 ")
Console.WriteLine("Please input 2")
Console.WriteLine("Please input 3 ")
Console.WriteLine("Please input 4 ")
Console.WriteLine("Please input 5 for Help")
Console.WriteLine("Please input 6 to Exit")
Console.WriteLine("Please enter your choice: ")
Choice = Console.ReadLine()
Select Case Choice
case1; etc
Case Else
Console.WriteLine("Error: " & Choice & " is not a option, Please try again")
Look into Integer.TryParse, it will try and parse the string into a integer if it can, if it can't it wont throw an exception...
Dim b As Integer
Console.WriteLine("Please input the value of, B:")
If Not Integer.TryParse(Console.ReadLine(), b) Then
Console.WriteLine("Value entered must be a number")
GoTo Line98
End If
If it can parse the input from the user, then b would be the value from the parse, otherwise the value of b is still 0...
Edit Per Comment
Dim b As Integer
Do Until b > 0
Console.WriteLine("Please input the value of, B:")
If Not Integer.TryParse(Console.ReadLine(), b) OrElse b <= 0 Then
Console.WriteLine("Value entered must be a number and not equal 0")
GoTo Line98
End If
Loop
I am a very beginner programmer that is taking a class in school. We have a project where we are required to check if a user input is an integer, if it is not, we have to return an error message. Would anybody know how to do such a thing?
Check input value is integer:
REM check if user input is integer
PRINT "Input";
INPUT X$
IF VAL(X$) THEN
PRINT "Input is numeric value"
END IF
Check if input is integer or fractional
EDIT: 05/07/2018 to include error checking
REM check if user input is integer
ON ERROR GOTO 100
PRINT "Input";
INPUT X$
IF VAL(X$) THEN
IF INSTR(X$, ".") THEN
PRINT "Input is fractional"
ELSE
PRINT "Input is numeric value"
END IF
END IF
END
100 IF ERR = 6 THEN PRINT "Overflow"
END
Sorry for the awkwardly worded question. In visual basic I have a prompt asking the user to "Enter a letter between A and D:"
If ValidChar(chrLetter) Then
Me.lblLetterResult.Text = chrLetter & " is a valid letter"
Else
Me.lblLetterResult.Text = chrLetter & " is not a valid letter"
End If
Function ValidChar(ByVal chrLetter As Char) As Boolean
Dim chrLowChar As Char = "D"
Dim chrHighChar As Char = "A"
If chrLetter >= chrLowChar And chrLetter <= chrHighChar Then
Return True
Else
Return False
End If
End Function
Obviously this isn't correct, but I'm not sure what the correct code should be. If the user were to enter the character "A" then it should display "A is a valid number". If the user were to enter "X" then it should display "X is not a valid number". Any help is appreciated!
Don't you just need to reverse your logic? D is greater than A.
Dim chrLowChar As Char = "A" ' ascii decimal value of 65
Dim chrHighChar As Char = "D" ' ascii decimal value of 68
Review decimal values for ASCII characters for more information on character values
http://www.asciitable.com/
Just create a string object "ABCD". Execute string.contains(). If using a wider range just convert to ASCII equivalent and use code similar to your example
I am using Integer.TryParse Method to validate whether user input is a numeric or non-numeric in my program.
1)if the user input is numeric, the program will then proceed and validate that the user input is range from 0 to 9.
2)If the user is enter a non-numeric input, the program will display the message "invalid input" and ask user to start from beginning.
Following is my coding:
Sub Main()
Dim sevenNumbers As Integer()
sevenNumbers = New Integer(6) {}
Dim index As Integer
Dim number As Integer
Dim reEnter As Boolean = True
Console.WriteLine("Please enter 7 integers: ")
Console.WriteLine("<ATTENTION: FROM 0 TO 9 ONLY>")
Console.WriteLine()
While reEnter
For index = 0 To 6
Console.WriteLine("Please enter the integer no." & "{0}" & " : ", index + 1) 'Prompt user to enter 7 integers.
sevenNumbers(index) = Console.ReadLine() 'The 7 integers are stored in an array.
If Integer.TryParse(sevenNumbers(index), number) Then
While sevenNumbers(index) < 0 Or sevenNumbers(index) > 9
Console.WriteLine("<invalid input>")
Console.WriteLine()
Console.WriteLine("------------------------------------------")
Console.WriteLine("<Please re-enter the 7 integers>")
Console.WriteLine("------------------------------------------")
Console.WriteLine()
reEnter = True
Exit For
End While
Else
Console.WriteLine("<invalid input>")
Console.WriteLine()
Console.WriteLine("------------------------------------------")
Console.WriteLine("<Please re-enter the 7 integers>")
Console.WriteLine("------------------------------------------")
Console.WriteLine()
reEnter = True
Exit For
End If
reEnter = False
Next
End While
End Sub
However, when a user enter a non-numeric input, the program can't continue and shows an error that forced to close.
i tried this
Sub Main()
Dim num As Integer
Console.Write("enter num:")
Dim input = Console.ReadLine
If Integer.TryParse(input, num) Then
Console.WriteLine("valid. num = " & num)
Else
Console.WriteLine("invalid")
End If
End Sub
it does works and i am wondering which part of my coding is wrong??
Thank for help!!
Your two samples of code are different. In your second attempt, you do this:
Dim input = Console.ReadLine
If Integer.TryParse(input, num) Then
The above code reads into a variable called input that will be a String (because Console.ReadLine returns a String). Then, you try to parse the string into a number.
However, in your original code, you do this (some lines omitted for clarity):
Dim sevenNumbers As Integer()
sevenNumbers = New Integer(6) {}
...
sevenNumbers(index) = Console.ReadLine()
In this case, you are reading into a variable that you have explicitly declared to be an Integer. If the user types "abc" then the conversion will fail at this point - you won't even get to the TryParse because you can't complete the innput.
Instead of reading to an integer, you need to read into a String variable and then parse that value into an Integer (as you did in your second code).
You could have spotted this yourself by taking note of the line that the error actually occurs on when debugging: you should note that the program crashes on the ReadLine, not on the TryParse.
Um. This line:
sevenNumbers(index) = Console.ReadLine()
Is storing whatever text has been read into an array of Integers. If it's compiling, then by the time you reach any later code, you're too late to control the conversion. It's already happened.
Maybe sevenNumbers should be String()?
(You really ought to turn on OPTION STRICT and OPTION EXPLICIT - it should find problems like this for you when it compiles the code)
I have this code which shifts the alphabet by a certain amount. The size of the alphabet is 26. When I enter a larger size shift (for example 22) I get some weird characters displaying. I think I need to mod the ASCII alphabet to 26 to get it working but Im not quite sure which bit to mod.
Basically I need to wrap around the alphabet (once it reaches Z it goes back to letter A) Do I have to create a dictionary for the mod to work (like A = 0... Z = 26) or can I stick with using the normal ASCII table? Here is the code below:
Public Function encrypt(ByVal input As String) 'input is a variable within the funcion
Dim n as Integer
Dim i As Integer
n = key.Text Mod 26 'gets what is in the text box of 'key' and sets it as n
' the key is a multiple of 26 so 26 will = 0
'need to remove white spaces
While input.Contains(" ") 'when the input text contains a space
input = input.Replace(" ", "") 'replaces it with no space.
End While
For i = 1 To Len(input) 'find the length of the input
Mid(input, i, 1) = Chr(Asc(Mid(input, i, 1)) + n) 'chr returns the character associated with the specified character code
'
Next
encrypt = input
End Function
Look at this code:
For i = 1 To Len(input) 'find the length of the input
Mid(input, i, 1) = Chr(Asc(Mid(input, i, 1)) + n) 'chr returns the character associated with the specified character code
'
Next
String indexes are 0-based. Your first index is 0, not 1! Also, you are assigning to the result of a function call. You need to instead construct a new string.
You didn't say, but the way you used the Replace and Contains methods indicates .Net, and if that's the case, I would do it like this:
Public Function encrypt(ByVal key As Integer, ByVal input As String) As String 'Don't forget the return type on the function
key = key Mod 26
Return New String(input.Replace(" ", "").ToUpper().Select(Function(c) Chr(((Asc(c) + key - Asc("A"c)) Mod 26) + Asc("A"c))).ToArray())
End Function
Just like that, and it's almost a one-liner. I can see this works now by calling it this way:
Encrypt("C"c, "the quick brown fox jumps over the lazy dog")
Encrypt("D"c, "the quick brown fox jumps over the lazy dog")
The results:
BPMYCQKSJZWEVNWFRCUXMLWDMZBPMTIHGLWOA
CQNZDRLTKAXFWOXGSDVYNMXENACQNUJIHMXPB
Look for the results mapped for the word "lazy", and you will see that the 'a' wraps to 'z' and 'y' correctly, and that the 'D' key results are one letter off of the 'C' results.