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
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
Example
if input1 is None:
messagebox("Error", "No data was entered")
else:
#code to continue program
Any ideas how to do this?
If I understand you correctly, you want to not give out a messagebox, if the input is given, right? Then you can simply not write the else-clause. Now if the if-condition is not met, the program will just continue running without executing the code of the if-clause.
while True: # loop will run until break
input1 = # get the input however
if input1 is None:
messagebox("Error", "No data was entered")
else:
break # end the loop
# program continues here after loop ends with break
I have written a program but I do not know how to loop it. Help would be appreciated.
Here is the program I need help with.
There are two types of loops: indefinite (while) loops and definite (for) loops. If you want to loop your program a specific amount of times, then use the for loop:
for count in range(0, <number of repetitions minus one>):
# code
If you want to loop the program until the user enters "QUIT" or some other string, use this:
sentinel = input("Enter QUIT to exit or anything else to continue: ")
while sentinel.upper() != "QUIT":
# code
Here are some helpful links to tutorials:
http://www.learnpython.org/en/Loops
http://www.python-course.eu/python3_for_loop.php
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/whilestatements.html#while-statements
If you're talking about an infinite loop (i.e it has to go on and on without stopping) then simply use
white True:
<Your code here>
If it's not an infinite loop and only till a certain value comes true then you can do something like:
counter = 0
while counter <= 10:
print "This will continue till counter = 10"
counter += 1
You should make a function of the program, this function you can put in a loop. For further help, please post your code!
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
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()
#...