validating user input to text only and integer only - input

i have searched for a simple, non complicated answer on how to ensure that the user is asked again if they enter anything other than text for 1 and an integer for 2.
when entering these input variables, however i have only found complicated solutions that my teacher wont acccept.
is it possible if anyone can provide me with simple solutions on how to validate these variables. so far all i know how to validate is to use "while not in" functions, which only works for specific options. I am new to python, so please explain in a simple manner. thanks! :)
1-studentname=input("what is your name?:")
2-print("what is 10+10?:")
3-studentanswer=int(input("insert answer:"))

You can use a while loop with if , else in it
while(true):
t = int(input());
if t == 1:
# do whatever --> break at the end
else if t == 2:
# do whatever ---> break at the end
else:
continue

You can use the .isalpha and .isdigit method.
For example,
studentname=input("what's your name) ?
studentname.isalpha()
That checks whether the string consists of alphabetic characters only.
Both .isalpha and .isdigit return boolean, so you can use an if condition then.

Related

How to make a Password Validator in Scratch

So I am trying to make a password validator in Scratch where it asks the user to input an answer and then it puts the answer through some criterias and then outputs if it is a valid password or not. The criterias are:
Has at least 8 characters,
Has at least one uppercase letter,
Has at least one lowercase letter,
Has at least one number,
Has at least one special character,
Must contain less than 18 characters.
I tried to make a list first with all the different characters and check if the password contained them, but it doesn't actually work. I looked all over the internet for help on this but no one seems to have done it. The Scratch Wiki does have some stuff about case sensitivity but I haven't really been able to implement it. I really need help and I have been trying for a while now. Thanks.
If you just check if the password contains the list, it will only work if it has every single character of the list in order. If you want to make sure it contains each check, you're probably going to have to make a system that checks each letter for every check, which is a little complex.
Check if <lowercase letter/whatever check> contains(letter(text reading #) of (password))
If it passes this check, continue to the next check and set text reading # to 1. Otherwise, change text reading # by 1.
I assume you'll know how to code this properly, but I just partially phrased in the way a normal human would.
This will repeat until either it reaches the end of the password or it passes the check. it will then do this again, but for a different check. It's hard to explain in text, and this is my first answer, but I hope it helps.
You have to use the operators "contains", "length of" and > operators, from the end of the class. Combine "contains", "or" and "and".

Putting a Try and Except inside a Loop

Hi I'm trying to figure out how to put a 'Try and Except' inside of a while loop. My brother challenged me to creating a program of the computer creating a random number (1-100) then the user to try and guess what it is. I managed to get this working but I am stuck on if the user didn't actually input a number, what I should do so that the program doesn't just stop working but just prompts the user in what they have done wrong. Below I have attached my full code. The program works, but I am not sure how to put the While loop in it. I have tried doing things like 'While guess != integer' and I've been looking up different ways on how I could do it. The best I've seen is someone just saying to put the try and except into a while loop, but it didn't tell me how I could do it. try-except inside a loop . If possible I also wondered if there was anyway I could just call this loop at any point when the user answers, so if they do continuously mistype I don't need to do anything else. Thank you for taking your time to read this, sorry I wrote a lot
import random
import time
def guessMyNumber():
print("Hello , welcome to Guess My Number")
time.sleep(1)
print ("The computer is thinking of a number between 1-100")
time.sleep(2)
print("Try to guess the number in as few attempts as possible")
number=random.randint(1,100)
try:
guess=int(input("Take a guess "))
except ValueError:
print("You must enter a whole number")
guess=int(input("Please take another guess, making sure that it is a whole number. Thank you. "))
tries = 1
while guess !=number:
if guess>number:
print("You need to go lower")
guess=int(input("Take a guess "))
else:
print("Go higher!")
guess=int(input("Take a guess "))
tries=tries+1
if tries < 5:
print("Well done! You guessed the number in", tries, "tries! If you would like to play again please type 'guessMyNumber()'")
else:
print("You guessed the number in", tries, "tries. If you would like to play again type 'guessMyNumber()' ")
guessMyNumber()
Your except block should not raise exception, below is one example how you could do int and you could modify as per your program requirements
count = 0
while count < 5:
try:
guess=int(input("Take a guess "))
except ValueError:
print("You must enter a whole number")
print("Please take another guess, making sure that it is a whole number. Thank you. ")
count = count+1

Use String for IF statement conditions

I'm hoping someone can help answer my question, perhaps with an idea of where to go or whether what I'm trying to do is not possible with the way I want to do it.
I've been asked to write a set of rules based on the data held by our ERP form components or variables.
Unfortunately, these components and variables cannot be accessed or used outside of the ERP, so I can't use SQL to query the values and then build some kind of SQL query.
They'd like the ability to put statements like these:
C(MyComponentName) = C(MyOtherComponentName)
V(MyVariableName) > 16
(C(MyComponentName) = "") AND V(MyVariableName) <> "")
((C(MyComponentName) = "") OR C(MyOtherComponentName) = "") AND V(MyVariableName) <> "")
This should be turned into some kind of query which gets the value of MyComponentName and MyOtherComponentName and (in this case) compares them for equality.
They don't necessarily want to just compare for equality, but to be able to determine whether a component / variable value is greaterthan or lessthan etc.
Basically it's a free-form statement that gets converted into something similar to an IF statement.
I've tried this:
Sub TestCondition()
Dim Condition as string = String.Format("{0} = {1}", _
Component("MyComponent").Value, Component("MyOtherComponent").Value)
If (Condition) Then
' Do Something
Else
' Do Something Else
End If
End Sub
Obviously, this does not work and I honestly didn't think it would be so simple.
Ignoring the fact that I'd have to parse the line, extract the required operators, the values from components or variables (denoted by a C or V) - how can I do this?
I've looked at Expression Trees but these were confusing, especially as I'd never heard of them, let alone used them. (Is it possible to create an expression tree for dynamic if statements? - This link provided some detail on expression trees in C#)
I know an easier way to solve this might be to simply populate the form with a multitude of drop-down lists, so users pick what they want from lists or fill in a text box for a specific search criteria.
This wouldn't be a simple matter as the ERP doesn't allow you to dynamically create controls on its forms. You have to drag each component manually and would be next to useless as we'd potentially want at least 1 rule for every form we have (100+).
I'm either looking for someone to say you cannot do this the way you want to do it (with a suitable reason or suggestion as to how I could do it) that I can take to my manager or some hints, perhaps a link or 2 pointing me in the right direction.
If (Condition) Then
This is not possible. There is no way to treat data stored in a string as code. While the above statement is valid, it won't and can't function the way you want it to. Instead, Condition will be evaluated as what it is: a string. (Anything that doesn't boil down to 0 is treated as True; see this question.)
What you are attempting borders on allowing the user to type code dynamically to get a result. I won't say this is impossible per se in VB.Net, but it is incredibly ambitious.
Instead, I would suggest clearly defining what your application can and can't do. Enumerate the operators your code will allow and build code to support each directly. For example:
Public Function TestCondition(value1 As Object, value2 As Object, op as string) As Boolean
Select Case op
Case "="
Return value1 = value2
Case "<"
Return value1 < value2
Case ">"
Return value1 > value2
Case Else
'Error handling
End Select
End Function
Obviously you would need to tailor the above to the types of variables you will be handling and your other specific needs, but this approach should give you a workable solution.
For my particular requirements, using the NCalc library has enabled me to do most of what I was looking to do. Easy to work with and the documentation is quite extensive - lots of examples too.

VB.net Strange Conditional Statement (IF)

Was wondering if someone could lend me their expertise. Pretty new to Vb.net and have come across this conditional statement in one of our products. Could someone please confirm the validity of the statement and explain what's going on here? I've tried numerous searches, but I cannot find anything related.
If (IsDBNull(dr("someID")), "0", dr("someID")) = someID.ToString() Then
I have changed the "id" value names as it's code from a commercial product, but the ID's used were all the same variable (ints).
Thanks for any input you can offer on this!
Joe
PS: The reason I can't check this at run time is because of how the product operates.
It is an inline If statement
If(condition,iftrue,iffalse) if condition is true evaluate and return iftrue else iffalse
The If operator in VB.NET 2008 acts as a ternary operator.[ REFERENCE]
Example:
Dim foo as String = If(bar = buz, cat, dog) 'Condition satisfied then it'll return cat else dog.
The statement is checking to see if the dr("SomeID") equals the value someID.ToString. The reason the If is required is because you need to check if the dr("someID") Is Null. If it is 0 is used instead which presumably should not be equal to someID.
It is the same as doing the following:
If Not IsDBNull(dr("someID")) Then
If dr("someID").ToString = someID.ToString Then
End If
End If
I would suggest that something like this would be more appropriate (checking integer values instead of comparing strings)
If(IsDBNull(dr("someID")), 0, CInt(dr("someID"))) = someID Then
I would also suggest Turning Option Strict On as the code you posted should not compile!

How do i make multiple variations of a string in vb.net?

I made this one code and I was wondering how I can make it more effective with little work.
This is an example of one of the if then else statements I put in:
If lblQuestion.Text = "anti-" Then
lblCorrectAnswer.Text = "against, opposed to, preventive; used as a prefix"
If txtPlayersAnswer.Text = "against, opposed to, preventive" Then
lblRight.Text = "Correct"
Else
lblRight.Text = "Wrong!"
End If
End If
I was wondering if it was possible to make multiple variations for the statement
If txtPlayersAnswer.Text = "against, opposed to, preventive" Then
For example: Instead of having to code out each possible variation for that line of code is there a way to make that one line of code have all the possible variations, and if so how?
Thank you in advance.
Too many assumptions of user input for me , but
pseudo code
Given answers was an array of ["against"],["opposed to"],["preventative"]
then you could do something like
count = 0;
foreach(answer in answers)
if txtPlayersAnswer.Contains(answer) count++
case sensitive will be an issue as would be answer like "not against"
Me I'd get the user to enter each potential answer separately instead of having to rely on them entering them in a format you knew how to chop up.