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
Related
I am currently using readline() function in Kotlin. However, I want it to continue after registering the enter key ten times. I don't know how to do this.
using the function readline() on a console application that is reading from the keyboard, you dont need to register the enter-key because ENTER represents a valid end of the line. So a simple loop which is executed 10 times will fully work out here. for(i in 0..9) { <READ INPUT> }
Using it on files works the same. Normal editors will show a text in X lines if the border window is reached even without ENTER. readline() will not do that and read a single line in a file until a line-end sign is found. So here again - just loop it 10 times for 10 lines.
From your question it is not very clear, what you are trying to achieve. I assume you want to read ten lines from the console with Console.readLine().
The code
val lines = (1..10).map { readLine() }
will read ten lines from the console and store them in the variable lines as list of strings.
I am trying to setup a program that takes user input for database ddl generation. I have it working to the point where it can ask a user for the name of the table, the number of columns and any attributes that might be needed. The problem comes when I try to print a string that includes the variables used for the column names. Due to trying to let users have as many columns as they want I used variables similar to this newvar(number that increases every time you enter a column name). This works fine and I can get the values if i do send %newvar1% but it doesn't work to do send newvar%increasing number%. I need to know if this is possible or if I'm just missing something obvious. Also I don't have the code with me but I can post it once I get back to my main computer.
I have tried quite a few things like, send %newvar%%number%, send newvar%number%, othervar = newvar%number% send %othervar%.
I'll show some once I have access to it in about 2 hours.
I expect to be able to output names for increasing variables using an ever increasing number. Class is starting I'll clarify some things later.
You can use a lone percent % beginning the first argument for the send command to achieve what you want. This will make everything after it to be evaluated (up to the next comma). Here is an example:
f1::
newvar1 := "This " , newvar2 := "is just a " , newvar3 := "test."
Loop , 3
Send , % newvar%A_Index%
Return
See: https://www.autohotkey.com/docs/Language.htm#-expression
I have met this a lot recently reading other people's scripts. A short example is below:
Say we need input and store them in var A and B, the scheme is below:
int ok;
ok = false;
while(!ok){
//ask input for A
//ask input for B
ok = true;
}
I understand what it wants, but why is this scheme necessary? can I only have "ask input for A and B".
but why is this scheme necessary?
It is not necessary.
can I only have "ask input for A and B".
You sure can.
However, if user gives you input that is not useful (for example: you ask for the users age, and they type "horse"), then you might want to ask again. Allowing re-trying of input is generally a useful feature. The canonical control structure for repeating a piece of program is a loop.
Your example program however, sets ok unconditionally, so in that case there is really no use for the loop. The loop makes sense only if there is some form of validation that must be passed before the input is OK.
When there are no checks in the code you omitted, but you see this same construct all over the place, then it's a copy&paste artifact.
Someone had a piece of code that was reading input and validating it, then copied the code somewhere else, removed the validation bits, and left the rest as-is. Then they copy&pasted that code all over the place.
In my experience, this happens very often.
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.
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.