How to prompt a user for input until the input is valid in Julia - julia

I am trying to make a program to prompt a user for input until they enter a number within a specific range.
What is the best approach to make sure the code does not error out when I enter a letter, a symbol, or a number outside of the specified range?

In alternative to parse, you can use tryparse:
tryparse(type, str; base)
Like parse, but returns either a value of the requested type, or
nothing if the string does not contain a valid number.
The advantage over parse is that you can have a cleaner error handling without resorting to try/catch, which would hide all exceptions raised within the block.
For example you can do:
while true
print("Please enter a whole number between 1 and 5: ")
input = readline(stdin)
value = tryparse(Int, input)
if value !== nothing && 1 <= value <= 5
println("You entered $(input)")
break
else
#warn "Enter a whole number between 1 and 5"
end
end
Sample run:
Please enter a whole number between 1 and 5: 42
┌ Warning: Enter a whole number between 1 and 5
└ # Main myscript.jl:9
Please enter a whole number between 1 and 5: abcde
┌ Warning: Enter a whole number between 1 and 5
└ # Main myscript.jl:9
Please enter a whole number between 1 and 5: 3
You entered 3

This is one possible way to achieve this sort of thing:
while true
print("Please enter a whole number between 1 and 5: ")
input = readline(stdin)
try
if parse(Int, input) <= 5 || parse(Int, input) >= 1
print("You entered $(input)")
break
end
catch
#warn "Enter a whole number between 1 and 5"
end
end
Sample Run:
Please enter a whole number between 1 and 5: 2
You entered 2
See this link for how to parse the user input into an int.

Related

The encryption won't decrypt

I was given an encrypted copy of the study guide here, but how do you decrypt and read it???
In a file called pa11.py write a method called decode(inputfile,outputfile). Decode should take two parameters - both of which are strings. The first should be the name of an encoded file (either helloworld.txt or superdupertopsecretstudyguide.txt or yet another file that I might use to test your code). The second should be the name of a file that you will use as an output file.
Your method should read in the contents of the inputfile and, using the scheme described in the hints.txt file above, decode the hidden message, writing to the outputfile as it goes (or all at once when it is done depending on what you decide to use).
The penny math lecture is here.
"""
Program: pennyMath.py
Author: CS 1510
Description: Calculates the penny math value of a string.
"""
# Get the input string
original = input("Enter a string to get its cost in penny math: ")
cost = 0
Go through each character in the input string
for char in original:
value = ord(char) #ord() gives us the encoded number!
if char>="a" and char<="z":
cost = cost+(value-96) #offset the value of ord by 96
elif char>="A" and char<="Z":
cost = cost+(value-64) #offset the value of ord by 64
print("The cost of",original,"is",cost)
Another hint: Don't forget about while loops...
Another hint: After letters -
skip ahead by their pennymath value positions + 2
After numbers - skip ahead by their number + 7 positions
After anything else - just skip ahead by 1 position
The issue I'm having in that I cant seem to get the coding right to decode the file it comes out looking the same. This is the current code I have been using. But once I try to decrypt the message it stays the same.
def pennycost(c):
if c >="a" and c <="z":
return ord(c)-96
elif c>="A" and c<="Z":
return ord(c)-64
def decryption(inputfile,outputfile):
with open(inputfile) as f:
fo = open(outputfile,"w")
count = 0
while True:
c = f.read(1)
if not c:
break;
if count > 0:
count = count -1;
continue
elif c.isalpha():
count = pennycost(c)
fo.write(c)
elif c.isdigit():
count = int(c)
fo.write(c)
else:
count = 6
fo.write(c)
fo.close()
inputfile = input("Please enter the input file name: ")
outputfile = input("Plese enter the output file name(EXISTING FILE WILL BE OVER WRITTEN!): ")
decryption(inputfile,outputfile)

How can I solve the error when the user inputs only an "enter" in R?

I make a code based on a table game. At the beginning of the code, it must ask the player the name of the player, and when the player inputs an "enter", my code shows an error. I want that when the player inputs an "enter", the program says something like "This name is invalid", ask repeat asking the name of the player. Here is a part of my code:
repeat{
if(r==1){
print("Name Player 1: ")
name1=scan(,what="character",1)
if(any(name1==gamers)){
r=readline(prompt = "This player is already in the file. Would you like to change the name? \n 1. Yes \n 2. No \n Select an option: ")
if(r==0){
r<-99
}
Instead of print(...); name1=scan(...), I'd use readline, as such:
while (!nzchar(name1 <- readline("Name Player 1: "))) TRUE
# Name Player 1: <-- me just hitting <enter>
# Name Player 1: <-- again
# Name Player 1: r2evans
name1
# [1] "r2evans"
You might prefer to allow a max number of failed attempts, though, instead of requiring the user interrupt the process with ctrl-c, so perhaps:
tries <- 3L
while (tries > 0 && !nzchar(name1 <- readline("Name Player 1: "))) tries <- tries - 1L
# Name Player 1:
# Name Player 1:
# Name Player 1:
And the loop just stopped/exited. You "know" that the user chose to quit because after the loop, tries == 0L and !nzchar(name1) both indicate the user's intent.

Regex in if else statement in R

I have a rather simple question. I am trying to get the if else statement below to work.
It is supposed to assign '1' if the if statement is met, 0 otherwise.
My problem is that I cannot get the regex in the if statement to work ('\w*|\W*). It is supposed to specify the condition that the string either is "Registration Required" or Registration required followed by any character. I cannot specify the exact cases, because following the "Registration required" (in the cases where something follows), it will usually be a date (varying for each observation) and a few words.
Registration_cleaned <- c()
for (i in 1:length(Registration)) {
if (Registration[i] == ' Registration Required\\w*|\\W*') {
Meta_Registration_cleaned <- 1
} else {
Meta_Registration_cleaned <- 0
}
Registration_cleaned <- c(Registration_cleaned, Meta_Registration_cleaned)
}
You may use transform together with ifelse function to set the Meta_Registration_cleaned.
For matching the regular expression grep function can be used with pattern "Registration Required\w*".
Registration <- data.frame(reg = c("Registration Required", "Registration Required ddfdqf","some str", "Regixxstration Required ddfdqf"),stringsAsFactors = F)
transform(Registration,Meta_Registration_cleaned = ifelse(grepl("Registration Required\\w*",Registration[,"reg"]), 1, 0))
Gives result:
reg Meta_Registration_cleaned
1 Registration Required 1
2 Registration Required ddfdqf 1
3 some str 0
4 Regixxstration Required ddfdqf 0
I might have misunderstood the OP completely, because I have understood the question entirely differently than anyone else here.
My comment earlier suggested looking for the regex at the end of the string.
Registration <- data.frame(reg = c("Registration Required", "Registration Required ddfdqf","Registration Required 10/12/2000"),stringsAsFactors = F)
#thanks #user1653941 for drafting the sample vector
Registration$Meta_Registration_cleaned <- grepl('Registration required$', Registration$reg, ignore.case = TRUE)
Registration
1 Registration Required TRUE
2 Registration Required ddfdqf FALSE
3 Registration Required 10/12/2000 FALSE
I understand the OP as such that the condition is: Either the string "Registration required" without following characters, or... anything else. Looking forward to the OPs comment.

How to convert an empty string to integer value 0

Good day. I am a newbie in creating a python program. My program is to write code that prints Hello if 1 is stored in spam, prints Howdy if 2 is stored in spam, and prints Greetings! if anything else is stored in spam.
My problem is that I would like to repeat the process if the user will not input anything or an empty value. How will I convert '' to value 0. Thanks. Im sorry if my program is not that good.
while True:
print ('Enter value of spam')
spam = int(input())
if spam == 1:
print ('Hello')
continue
elif spam == 2:
print ('Howdy')
continue
elif spam != 0:
print ('Greeting')
continue
Try this.
print ('Enter value of spam')
spam = input()
while spam != "" or spam == 0:
if int(spam) == 1:
print ('Hello')
elif int(spam)== 2:
print ('Howdy')
elif int(spam)!= 0:
print ('Greeting')
print ('Enter value of spam')
spam = input()
You could use a try-except block to handle any situation where your user's input can't be understood as an integer:
while True:
print ('Enter value of spam')
try:
spam = int(input())
except ValueError:
spam = 0
if spam == 1:
print ('Hello')
continue
elif spam == 2:
print ('Howdy')
continue
elif spam != 0:
print ('Greeting')
continue

C# Regular expression for input values of Textbox

I want to validate the text within a textbox using a regular expression.
The text should be a number greater than 0 and less than and equal to 1000.
"^[1-9][0-9]*{1,2}$" is the regex you are looking for.
if(Regex.IsMatch(YourTextBox.Text,"^[1-9][0-9]*{1,2}$"))
{
//Write your logic here
}
Try this regex:
//for 0 < x < 1000
^((?<=[1-9])0|[1-9]){1,3}$
explain:
(?<=[1-9])0 //look behind to see if there is digits (1-9)
test:
0 -> invalid
000 -> invalid
45 -> valid
5 -> valid 'Ashwin Singh' solution can not capture this
101 -> valid
999 -> valid
1000 -> invalid
12345 -> invalid
10000 -> invalid
2558 -> invalid
205 -> valid
1001 -> invalid
2000 -> invalid
And better way convert to Decimal (if you dont use regular expression validator):
Decimal dc = Decimal.TryParse(textBox.Text);
if( dc > 0 && dc < 1000)
// do some thing
I found it:
^([1-9]|[1-9][0-9]|[1-9][0-9][0-9])$|^(1000)
I test it in range 0~1000

Resources