Function with "break" inside - python

I am currently working on a small project for a master's course.
I would like to make a short game, and I am using very often the same question.
I would like to make functions, but to ask the user the choice he wants to make (integer) I should make the following codes:
def IntNumber(fac):
while True :
num_fac = int(input("How many %s do you want to buy?" %fac))
try:
num_fac = int(input("How many %s do you want to buy?" %fac))
if num_fac <0 :
raise ValueError(num_fac, "is not valid.")
break
except ValueError:
print("That's not a valid number!")
continue
However, with a "break" inside I can't make the function work the way I want: the value of num_fac is deleted, and I get an error message that num_fac isn't defined.
How can I do that otherwise? I really need to make my codes shorter and more efficient!

Related

program says it isn't a valid input when it is

I've run into a bug where the program seems to think that my input into an input statement isn't within the parameters, when it clearly is.
This is the code i'm having trouble with:
time.sleep(1.5)
print()
print()
print("You have chosen", horsechoice)
time.sleep(1)
print("How much do you want to bet?")
while True:
try:
moneyinput = int(input())
racebegin(moneyinput)
break
except:
print("Not a valid amount of money.")
continue
Even when I input an integer, it still states that I didn't input a valid amount of money.
If you only want to check the input validity, you should wrap the try/except only around the int(input()) call, not racebegin(). Your code is probably catching an error in racebegin().
It's also a good idea to narrow down the type of error you're catching with except:. Doing that might have prevented the problem in the original code, unless racebegin() was also raising ValueError.
while True:
try:
moneyinput = int(input())
break
except ValueError:
print("Not a valid amount of money.")
racebegin(moneyinput)

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.

Challenges with guessing game of integers

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

Python: Break statements for while blocks

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

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