Beginner here. :)
So I want to achieve is this:
User enters a number. It spits out the ^3 of the number. If user enters a letter instead, it prints out a error message.
Code #1 works great:
def thirdpower():
try:
number = int(raw_input("Enter a number : "))
n=number**3
print "%d to the 3rd power is %d" % (number,n)
except ValueError:
print "You must enter an integer, please try again."
thirdpower()
thirdpower()
But I want to try doing the same thing with a while statement since I want to practice with it. I know its a bit more verbose this way, but I think it's good practice nonetheless.
number=raw_input("Please Enter an integer")
while number.isalpha():
print "You have entered letter. Please try again"
number=raw_input("Please Enter an integer")
n=int(number)**3
print "%d to the 3rd power is %d" %(int(number), n)
My question is this. If I remove the number=raw_input("Please Enter an integer") under the while statement and replace it with a break, the code doesn't work.
Here is what I mean:
number=raw_input("Please Enter an integer")
while number.isalpha():
print "You have entered letter. Please try again"
break #This break here ruins everything :(
n=int(number)**3
print "%d to the 3rd power is %d" %(int(number), n)
Can anyone explain why?
The break exits out of the while loop, at which point number is still whatever letter was entered so you get an error trying to make it an int.
A break statement jumps out of a loop.
In this case, if the user types in a letter, the loop runs the print statement, then immediately reaches the break and terminates instead of looping over and over. (break is more useful when you put it inside an if statement that the program doesn't always reach.)
But using break doesn't stop the rest of your program from running, so Python still tries to run line 6. Since the number variable contains a letter, the program crashes when it tries to convert it to a number.
You were probably trying to end the program if the user typed in a letter. In that case, you could use the built-in sys module to do something like this:
import sys
number=raw_input("Please Enter an integer")
if number.isalpha():
print "You have entered letter. Please try again"
sys.exit()
#...
Related
in the output pane ı cannot see the values that ı entered before when the program finishes (when using debugger). I think, normally ı should see the guess that ı made between the two lines in the output( ı draw an arrow).
You have multiple errors in your code so far, maybe you are about to write the logic for it after you have the desired output, but I am anyway going to mention it.
1.If you want the user to guess multiple times you need to use a loop.
For example:
while True:
if ():
print()
elif():
print()
else:
print("Correct")
break
2.Also, if you want the user to guess again you would need to take input inside the if-elif structure.
3.To print the user input you can do as previous suggestion and put it inside the print-statement inside the if-statement like this:
answer = 5
guess = int(input("Please guess a number between 1 and 10:"))
while True:
if guess < answer:
print("You guessed:", guess)
guess = int(input())
.
.
.
else:
print("You guessed:", guess)
print("Congrats, it was correct!")
break
you can add:
print(guess)
before all the "if" statements if you want to see the input value printed
I am brand new to programming and I'm building a guessing game for fun as a first program. I've already figured out the following:
How to set a specific number for them to guess between 1-50 (for example)
What happens when they guess outside the parameters
Number of guesses and attempts to "break the game"
Included while loops full of if statements
What I can't seem to figure out though is how to stop the user from inputting anything other than a number into the game. I want them to be able to, but I'd like to print out a personal error message then exit the while loop. (Essentially ending the game).
This is as close as I've been able to guess:
if guess == number:
print('Hey wait! That\'s not a number!')
print('Try again tomorrow.')
guessed = True
break
I get the error: "ValueError: invalid literal for int() with base 10" and I'm clueless on how to figure this out. I've been reading about isdigit and isalpha and have tried messing around with those to see what happens, but I get the same error. Maybe I'm just putting it in the wrong section of code
Any hints? :)
Thank you!
Use try/except to handle exceptions:
try:
guess = int(input("What's your guess? "))
except ValueError:
print("Hey wait! That's not a number!")
print("Try again tomorrow.")
guessed = True
break
# otherwise, do stuff with guess, which is now guaranteed to be an int
You can use a try / except to attempt the cast to an integer or floating point number and then if the cast fails catch the error. Example:
try:
guessInt = int(guess)
except ValueError:
print('Hey wait! That\'s not a number!')
print('Try again tomorrow.')
guessed = True
break
def jump_slide():
num=int(input('Enter a number :'))
if num>20:
print('slide under')
else:
print('jump over')
The above runs just fine when not in a while loop.
But once in the loop below, it completely ignores the else block
while True:
jump_slide()
Any suggestion please.
I'm new to Python
Your code is dependent on the input that you give to the variable num in the function `jump_slide()'.
If you give a value less than 20 to the num variable, it will execute the else block.
otherwise your code is fine as far as syntax is concerned.
if-elseis a conditional statement so depending on the condition inside the if it will execute either of the statements.
An example in your program:
Say you enter a number 30 when you run the program, it will print "slide under" but suppose
if you enter 10 your program will print "jump over".
So depending on your input it will print either of the statements but not both.
Your code is fine. One more way for doing your work is.
def jump_slide():
while(True):
num=int(input('Enter a number :'))
if num>20:
print('slide under')
else:
print('jump over')
if num==-1:
break
dont put while loop here.
jump_slide()
now if you enter num greater than 20 if execute and "Slide under" print on the screen
if you enter number smaller than 20 else execute and "Jump over" print on the screen
if you press -1 than your loop will break and code after the function will execute or the program ends
import random
def get_num ():
return random.randrange (999,9999)
print ("{}".format (get_num ()))
def get_user_input():
while True:
user_input = input
print("Please enter a four digit number")
return user_input
if False:
print ("Length of string:" , len (str))
Here in this piece of coding I am trying to make a random 4 digit number which will tell user whether or not s/he has guessed the right number (essentially),
specifically though: It will tell the user (at the end of the game) if s/he has guessed certain digits correctly but not which position.
I want 'break' statement to be fitted into this which will separate the while block from the if False. How do I do this correctly? I have tried maany times but I have 4 problems:
1- I don't know where to insert the break
2- When I run the program it doesn't print the second print function.
3- When I run the program it doesn't tell me the length of the string so I don't know if the user is even enterring the correct number of digits.
4- How do I set a limit on python (i.e. how many goes a player can have before the game ends?
I guess you are new to programming and this may be one of your very first codes. It would be great if you start by learning syntax of programming language which you have decided to use as well as working of loops, return statements, etc. I personally preferred reading any basic programming language book. For your case, it would be any book of python which is for beginners. For the sake of completeness, i have added the below code which is probably not exactly what you asked for:
import random
def get_num():
return random.randrange (999,9999)
def get_user_input():
user_input = int(input())
return user_input
while True:
comp_num = get_num()
print("The computer gave: {}".format(comp_num))
print("Your turn:")
user_num = get_user_input()
if user_num == comp_num:
print("Done it!")
break
else:
print("No, it's different. Try again!")
print()
In the above code, there are two functions and a while loop. One of the functions takes input from the user while the other generates a random number. The while loop is set to run for infinite iterations in case the user doesn't give the same input as the computer. As soon as the user gives the same input as the computer (which is displayed on the screen before he is asked to give input), the if condition evaluates to true, some things are printed and the break statement breaks the loop. And since, there is no further code, the program terminates
Well, I'm learning how to use Python, I'm using turtle-graphics to do a menu, in one part I ask for a number with
def getNumber():
return screen.numinput("Title"," Enter a number...")
Running the program, when I call this function and insert a letter or nothing and , I get an error: "Not a floating point valid. Please try again" in a window. So, Is there a way to change the message?, I would like to change that message to "Enter a number, not a letter!" or something like that.
edited:
import sys, tkMessageBox
def getNumber():
try:
return screen.numinput('Title', 'Enter a number...')
except:
tkMessageBox.showerror(title='Wrong Input',message='Enter a valid number!')
sys.exit(1)
All user input is always a string. You must explicitly convert the string to a number:
result = float(getNumber())
-or-
def getNumber():
s = screen.numinput("Title"," Enter a number...")
return float(s)