Storing random integer - python

I have recently started to program in Python. Now im working on a number guessing game. I have a proplem with understanding how does storing a random number works.I have looked around here, found some answer but couldnt make it work. The code works fine, but my answer (random number) is always different, so its imposible to guess it.
If anybody could help me or improve my code i would be glad.
Here is the part of that code where i have it:
def game(self):
import random
answer = random.randint(0, 1000)
guess = int(input("Your tip is:"))
while True:
if guess < answer:
print ("Your tip is lower, than the answer! Try again.")
self.game()
elif guess > answer:
print ("Your tip is bigger than the answer! Try again.")
self.game()
elif guess == answer:
print ("Good job! You have found the answer!")
self.replay()

That's because you are calling self.game() inside each if statement, which brings the execution flow back to the start of the function and generates a new number each time with answer = random.randint(0, 1000).
So simply remove self.game() and let the function reach the end:
import random
def game(self):
answer = random.randint(0, 1000)
while True:
guess = int(input("Your tip is:"))
if guess < answer:
print ("Your tip is lower, than the answer! Try again.")
elif guess > answer:
print ("Your tip is bigger than the answer! Try again.")
elif guess == answer:
print ("Good job! You have found the answer!")
self.replay()
break
EDIT 1:
You should also move the line where the user inputs his guess inside the while loop so that the user can guess until he gets the correct answer. I also added break statements to exit the loop when he gets the correct answer instead of only print statements. You can read more about break here (answer code above now updated)
EDIT 2:
Another small detail since you're new to Python: you should place all your import statements at the top of your python module, it's python coding guidelines that you should follow to make your code more clear. You can read more here

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

Manipulating a global variable in a function in python

Okay so ill apologize in advance if this question has previously been answered but I've looked thoroughly and cant seem to find anything that works. Im making a very simple game where you pretty much just have to guess a number between 1 and 1000 and if its incorrect the computer guesses a number either 1 above or below your guess. here is a function I've made to determine if the guess was too low
def numLow(userInput, low, high):
while userInput < num:
print ("The guess of {0} is low".format(userInput))
compGuess = (userInput + 1)
print ("My guess is {0}".format(compGuess))
low = (userInput + 1)
if compGuess < num:
print("The guess of {0} is low".format(compGuess))
userInput = int(input("Enter a value between {0} and
{1}:".format(low, high)))
else:
print("The guess of {0} is correct!".format(compGuess))
print("I WON!!!")
showTermination()
return (userInput, low)
now my issue is that i want to change the global variables userInput, low and high in the function. ive tried inserting
global userInput
global high
global low
before the function but it doesnt seem to work and if i put the globals inside the function i get "name 'userInput' is parameter and global". now im guessing the while loop is causing the problem but i cant seem to troubleshoot it. Im totally new to coding so i apologize if im breaking any coding rules or anything. Thanks for the help.
userInput for example is an input parameter to your function. The error message says exactly what the problem is here. You wanna use a global variable called userInput and you have an input parameter called userInput which are two different things for python. When userInput should be global then just define it somewhere globally like userInput = None and then instead of reaching it into the function as parameter just write in the function global userInput and python will know you are referencing to the globally instantiated variable. Both at the same time does not work.
Use globals() like this:
globals()['userInput'] = ...

converting string to int crashing the program

I have this code running in a number guessing game I have written, it runs perfectly fine if the player follows the instructions, but as we all know users never do. If the user enters just a space or any string thats not the word hint then it crashes saying invalid literal for int() with base 10: when trying to convert the value of guess to an integer. Is there any way around this or am I just going to have to live with the crashes?
while repeat==1:
repeat=0
level1number=str(level1number)
guess=input("What is your guess? ")
guess=guess.lower()
if guess==level1number:
print("Well done, You have guessed my number!")
elif guess=="hint":
print("Hints are not available until level 3")
repeat=1
elif guess!=level1number:
print("Sorry that is not my number, you have lost a life. :(")
lives=lives-1
repeat=1
if lives<=0:
print("You have lost all your lives, so this means I win")
print("The program will now end")
exit()
input("")
level1number=int(level1number)
guess=int(guess)
if guess<level1number:
print("The target number is higher")
else:
print("The target number is lower")
Use something as
if guess.isdigit() ...
(method isdigit() returns true if and only if all characters of a given string are digits, i.e. 0 to 9).
while repeat==1:
repeat=0
level1number=str(level1number)
guess=input("What is your guess? ")
guess=guess.lower()
if guess==level1number:
print("Well done, You have guessed my number!")
elif guess=="hint":
print("Hints are not available until level 3")
repeat=1
elif guess!=level1number:
print("Sorry that is not my number, you have lost a life. :(")
lives=lives-1
repeat=1
if lives<=0:
print("You have lost all your lives, so this means I win")
print("The program will now end")
exit()
input("")
level1number=int(level1number)
try:
guess=int(guess)
if guess<level1number:
print("The target number is higher")
else:
print("The target number is lower")
except:
print("Try again. Not a number")
Using try/except block would solve your problem. Have a look
Edit: In the question. you mentioned that you get an error when something other than a number is entered. Actually, it is an exception that is thrown when your code tries to convert your input string to a number when it is not possible(guess = int(guess)) due to the input not being a number, just like a space. So, what my code does, is that it catches the exception, and does not allow the program to terminate with the exception.
Just try it once. I know you are beginner but it is better to learn about exception handling as soon as possible, before you write more and more complex codes and applications.
Hope it helps!!

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

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.")

Categories

Resources