Python: Break statements for while blocks - python

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

Related

My debugger does not show the return values of the programs when the program finishes

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

Random Number Guesser not running as intended

import random
input = input("Guess the number from 1 to 20 Computer is thinking: ")
if input.isdigit():
int(input)
else:
print("Error")
exit()
computer = int(random.randrange(1, 5))
print("Computer thinks of number", str(computer) + ".", end = " ")
if input == computer:
print("You Win!")
elif input != computer:
print("You Lost.")
Whenever I guessed the right number, It says that I lost. This is a simple project I made as a beginner so please explain in the simplest way possible
The key issue in your code is the variable not being stored.
In your provided picture here, you call int(input) to convert the input number into an integer, showing that you understand that input() returns a string (not many beginners know this!), however, you did not store the result returned by int() to a variable. In your case, it seems like you want to store it back to the input variable.
Because you did not store it, calling int(input) will not modify the value in the existing input variable, making it still string, and thus failing the comparison with the computer generated number which is an integer.
To fix this, simply replace the int(input) with input = int(input)
On a side note, it is not advisable to use variable names that are same as built-in functions, like input, or str, as doing so will override the built-in function, causing the subsequent calls to the input() function to return error, since now input is a variable, not a function anymore.

Python While Loop not executing else block

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

User inputted script

I am trying to run a script which asks users for their favorite sports teams. This is what I have so far:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input is "Yankees":
print("Good choice, go Yankees")
elif input is "Knicks":
print("Why...? They are terrible")
elif input is "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
Whenever I run this script, the last "else" function takes over before the user can input anything.
Also, none of the teams to choose from are defined. Help?
Input is a function that asks user for an answer.
You need to call it and assign the return value to some variable.
Then check that variable, not the input itself.
Note
you probably want raw_input() instead to get the string you want.
Just remember to strip the whitespace.
Your main problem is that you are using is to compare values. As it was discussed in the question here --> String comparison in Python: is vs. ==
You use == when comparing values and is when comparing identities.
You would want to change your code to look like this:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input == "Yankees":
print("Good choice, go Yankees")
elif input == "Knicks":
print("Why...? They are terrible")
elif input == "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
However, you may want to consider putting your code into a while loop so that the user is asked the question until thy answer with an accepted answer.
You may also want to consider adding some human error tolerance, by forcing the compared value into lowercase letters. That way as long as the team name is spelled correctly, they comparison will be made accurately.
For example, see the code below:
while True: #This means that the loop will continue until a "break"
answer = input("Who is your favorite sports team: Yankees, Knicks, or Jets? ").lower()
#the .lower() is where the input is made lowercase
if answer == "yankees":
print("Good choice, go Yankees")
break
elif answer == "knicks":
print("Why...? They are terrible")
break
elif answer == "jets":
print("They are terrible too...")
break
else:
print("I have never heard of that team, try another team.")

2 codes work, the third doesn't

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()
#...

Categories

Resources