I am a beginner to coding in general and am trying to learn python and so I have been learning how to make a few basic games to figure things out and practice my basics... I have made a game to guess the number that is generate at a random interval of 0-100 and give feedback on if you guessed higher or lower to narrow it into your results. I managed to make the game work and I started trying to add a replayability framework so when you guess correct the game restarts automatically and a new number is generated to guess, however I am not able to make a new number generate. Originally I made the number generate outside the loop and made a loop that seemed effective but the number stayed the same, added it into the loop and it changed with every guess. so I tried adding a secondary def and pointing to it and making the number regenerate there but it doesnt seem to be making a new number still, and if I remove the generation outside of def replay def game no longer sees num as a valid variable. I am unsure how to accomplish this, any advise would be helpful....
import random
num = random.randint(0,100)
def Game():
print("Guess the Number: ")
guess = input()
guess = int(guess)
if guess==num:
print ("CORRECT!!!!!")
Replay()
elif guess>num:
print ("Sorry to high... Try again")
Game()
elif guess<num:
print ("Sorry to low... Try Again")
Game()
def Replay():
num = random.randint(0,100)
Game()
Replay()
This is a example of your code written more correctly according to me:
from random import *
def Game():
replay = 0
while replay == 0:
num = randint(0, 100) # if you want the number to revert every time you make a mistake, leave the line as it is otherwise put this assignment before the loop.
guess = int(input("Choose a integer number from 0 to 100: "))
if guess == num:
print(f"{guess} is mysterious number")
replay = 1
elif guess > num:
print(f"Sorry but {guess} is high, the number was {num}, try again if you want (0=yes, 1=no)")
replay = int(input())
elif guess < num:
print (f"Sorry but {guess} is low, the number was {num}, try again if you want (0=yes, 1=no)")
replay = int(input())
Game()
Related
import time
import random
# USER CHOOSES TO PLAY
play = input("Type 'Play' to play")
while play == "play":
# COMPUTER GENERATES NUMBER
number = random.randint(1,11)
# USER GOES TO GUESS THE NUMBER
print ("guess the number, the computer has picked a number between 1 and 10. You have 5 tries")
num_guess = int(input())
# CODE TELLS USER IF THEY CHOOSES THE RIGHT OR WRONG NUMBERPL
if num_guess == number:
print(f"Yes the number is {number}, good job!")
elif num_guess != number:
for numguesses in range (4, 0, -1):
num_guess = int(input(f"guess the number you have {numguesses} tries"))
play = input("Type 'Play' to play")
i have no idea whether when the computer generates a number with 'random.randint' if it is generating a new number every time i guess what number it has generated (as this is a number generating game). Please can you help and let me know.
Im trying to make it so there is only 1 number generated, from 1,11, and i have 5 guess to guess the right number, then it repeats if the user types 'play'
The first comment correctly answers the question.
the code generates a new random number every time the line random.randint(1,11) is encountered.
not only this, but you can easily prove this to yourself by adding the following to the next line:
print('the number has been generated:', number)
which will print the new number to the console each time...
This is my code so far (in PyCharm), I am writing a very simple number guessing game that has integers from 1-9. I am still trying to master thought & flow as well as loops, and I hit a roadblock:
import random
Player_Name = input("What is your name?\n")
print(f"Hello {Player_Name}!\n")
random_num = random.randint(1, 10)
guess = int(input("What is the number you want to pick? Guess one, 1-9\n"))
def number_game():
if guess == random_num:
print(f"You guessed right, the number is confirmed to be {random_num}.")
else:
print(f"You guessed the wrong number. Try again.\n")
number_game()
I called the function and ran the code... everything appears to be working except I really can't figure out how to keep the game going in a loop until the player gets the right number out of 1-9...and end it when I need to. I tried searching all my resources and am quite stuck on this beginner practice coding. Any help is appreciated.
What I wrote and tried is above... googling and stackoverflow just confused me more.
Honestly, there are many ways to do what you want. But using your code as base, this is one possible solution.
import random
Player_Name = input("What is your name?\n")
print(f"Hello {Player_Name}!\n")
random_num = random.randint(1, 10)
def number_game():
guess = int(input("What is the number you want to pick? Guess one, 1-9\n"))
if guess == random_num:
print(f"You guessed right, the number is confirmed to be {random_num}.")
return True
else:
print(f"You guessed the wrong number. Try again.\n")
return False
while True:
guessed_right = number_game()
if guessed_right:
quit()
else:
number_game()
while True:
number_game()
Replace the last line of your script with this!
I'm new to Python and I wanted to practice doing loops because I’ve been having the most trouble with them. I decided to make a game where the user will pick a number from 0-100 to see if they can win against the computer.
What I have going right now is only the beginning. The code isn’t finished. But trying out the code I got a Syntax error where the arrow pointed at the colon on the elif function.
How do I fix this? What can I do?
I accept any other additional comments on my code to make it better.
Here’s my code:
import random
min = 0
max = 100
roll_again = "yes"
quit = "no"
players_choice = input()
computer = random.randint
while roll_again == "yes":
print("Pick a number between 1-100: ")
print(players_choice)
if players_choice >= 0:
print("Your number of choice was: ")
print(players_choice)
print("Your number is high.")
if computer >= 0:
print("Computers number is: ")
print(computer)
print("Computers number is high.")
if computer >= players_choice:
print("Computer wins.")
print("You lose.")
print("Would you like to play again? ", +roll_again)
elif:
print(quit)
end
Goal:
Fix computer-player game while learning more about python. Providing additional documentation on where to start would be helpful.
The reason you are getting an error pointing to elif is because elif needs a condition to check. You need to use if elif and else like this:
if a == b:
print('A equals B!')
elif a == c:
print('A equals C!')
else:
print('A equals nothing...')
Also, Python relies on indentation to determine what belongs to what, so make sure you are paying attention to your indents (there is no end).
Your code has more errors after you fix the if statements and indentation, but you should be able to look up help to fix those.
There are a lot of problems with your code. Here is a working version, hope it helps you understand some of the concepts.
If not, feel free to ask
import random
# min and max are names for functions in python. It is better to avoid using
# them for variables
min_value = 0
max_value = 100
# This will loop forever uless something 'breaks' the loop
while True:
# input will print the question, wait for an anwer and put it in the
# 'player' variable (as a string, not a number)
player = input("Pick a number between 1-100: ")
# convert input to a number so we can compare it to the computer's value
player = int(player)
# randint is a function (it needs parentheses to work)
computer = random.randint(min_value, max_value)
# print what player and computer chose
print("Your choice: ", player)
print("Computer's choice: ", computer)
# display the results
if computer >= player:
print("Computer wins. You loose")
else:
print("you win.")
# Determine if user wants to continue playing
choice = raw_input("Would you like to play again? (yes/No) ")
if choice != 'yes':
# if not
break
There are a lot of indentiation issues and the if and elif statements are used incorrectly. Also take a look at how while loops work.
Based on the code you provided here is a working solution, but there are many other ways to implement this.
Here is some helpful tutorials for you on if/else statements as well as other beginner topics:
Python IF...ELIF...ELSE Statements
import random
minval = 0
maxval = 100
roll_again = "yes"
quit_string = "no"
while True:
players_choice = int(input("Pick a number between 1-100:\n"))
computer = random.randint(minval,maxval)
#checks if players choice is between 0 and 100
if players_choice >= 0 and players_choice <= 100:
print("Your number of choice was: ")
print(players_choice)
#otherwise it is out of range
else:
print("Number out of range")
#check if computers random number is in range from 0 to 100
if computer >= 0 and computer <= 100:
print("Computers number is: ")
print(computer)
# if computer's number is greater than players number, computer wins
if computer > players_choice:
print("Computer wins.")
print("You lose.")
#otherwise if players number is higher than computers, you win
elif computer < players_choice:
print("You won.")
#if neither condition is true, it is a tie game
else:
print("Tied game")
#ask user if they want to continue
play_choice = input("Would you like to play again? Type yes or no\n")
#checks text for yes or no use lower method to make sure if they type uppercase it matches string from roll_again or quit_string
if play_choice.lower() == roll_again:
#restarts loop
continue
elif play_choice.lower() == quit_string:
#breaks out of loop-game over
break
EDIT: Thanks for each very detailed explanations for the solutions, this community is golden for someone trying to learn coding!! #DYZ, #Rob
I'm a newbie in programming, and I'm trying to make a simple lotto guesses script in Python 3.
The user inputs how many guesses they need, and the program should run the function that many times.
But instead my code prints the same results that many times. Can you help me with this?
I'm pasting my code below, alternatively I guess you can run it directly from here : https://repl.it/#AEE/PersonalLottoEn
from random import randint
def loto(limit):
while len(guess) <= 6: #will continue until 6 numbers are found
num = randint(1, limit)
#and all numbers must be unique in the list
if num not in guess:
guess.append(num)
else:
continue
return guess
guess = [] #Need to create an empty list 1st
#User input to select which type of lotto (6/49 or 6/54)
while True:
choice = int(input("""Please enter your choice:
For Lotto A enter "1"
For Lotto B enter "2"
------>"""))
if choice == 1:
lim = 49 #6/49
break
elif choice == 2:
lim = 54 #6/54
break
else:
print("\n1 or 2 please!\n")
times = int(input("\nHow many guesses do you need?"))
print("\nYour lucky numbers are:\n")
for i in range(times):
result = str(sorted(loto(lim)))
print(result.strip("[]"))
Your loto function is operating on a global variable, guess. Global variables maintain their values, even across function calls. The first time loto() is called, guess is []. But the second time it is called, it still has the 6 values from the first call, so your while loop isn't executed.
A solution is to make the guess variable local to the loto() function.
Try this:
def loto(limit):
guess = [] #Need to create an empty list 1st
while len(guess) <= 6: #will continue until 6 numbers are found
num = randint(1, limit)
#and all numbers must be unique in the list
if num not in guess:
guess.append(num)
else:
continue
return guess
I am relatively new to programming with python (actually programming in general). I am making this 'Guess My Age' program that only has one problem:
import random
import time
import sys
print("\tAge Guesser!")
print("\t8 tries only!")
name = input("\nWhat's your name? ")
num = 80
min_num = 6
tries = 1
number = random.randint(min_num, num)
print("\nLet me guess... You are", number, "years old?")
guess = input("'Higher', 'Lower', or was it 'Correct'? ")
guess = guess.lower()
while guess != "correct":
if tries == 8:
print("\n I guess I couldn't guess your age....")
print("Closing...")
time.sleep(5)
sys.exit()
elif guess == "higher":
print("Let me think...")
min_num = number + 1 #### Here is my trouble - Don't know how to limit max number
time.sleep(3) # pause
elif guess == "lower":
print("Let me think...")
num = number - 1
time.sleep(3) # pause
number = random.randint(min_num, num) #<- Picks new random number
print("\nLet me guess... You are", number, "years old?")
guess = input("'Higher', 'Lower', or was it 'Correct'? ")
guess = guess.lower() #<- Lowercases
tries += 1 #<- Ups the tries by one
print("\nPfft. Knew it all along.")
time.sleep(10)
As you can see, I have 'num' as the max number for the random integer getting picked, but with:
elif guess == "higher":
print("Let me think...")
min_num = number + 1
it can go back up to however high it wants.
I want it to remember the last integer that 'num' was.
Say the program guessed 50 and I said 'Lower'. Then it said 30 and I said 'Higher'
I know I am probably sounding confusing, but please bear with me.
You need to define a maximum number as well as a minimum number. If they say their age is lower than a given age, you should set that age minus 1 as the maximum.
Of course, you also need to set an initial maximal age.
You might find it more useful to look into recursive functions for this kind of problem. If you define a function which takes min_age, max_age and tries_left as parameters, which comes up with a random number with between min_age and max_age and queries the user, you can then rerun the function (within itself) with a modified min_age, max_age and tries_left - 1. If tries_left is zero, concede defeat. This way you might get a better understanding of the logical flow.
I have left code out of this answer because, as you are a beginner, you will find it a useful exercise to implement yourself.
Cant you split out your guess into something like
max_num = 0
min_num = 0
elif guess =="lower":
max_num = number
if min_num!=0:
number = min_num+(max_num-min_num)/2
else:
number = max_num-1
elif guess =="higher":
min_num = number
if max_num!=0:
number=min_num+(max_num-min_num)/2
else:
number=min_num+1
Sorry it's not meant to be fully rigorous, and its a slight change on the logic you have there, but splitting out your variables so you have a higher and lower cap, that should help a lot?
Cheers
Please let me know if you need more elaboration, and I can try to write out a fully comprehensive version
It seems as though I was wrong in the fact that it did not remember the older integers. Before when running the program it would guess a number higher than the 'num' had specified. I don't know what I changed between then and now? But thank you for the help! #.#
This seems to work.
The only changes I really made:
-Variable names were confusing me, so I changed a couple.
-Note that if you try to mess with it (lower than 5, higher than 3... "Is it 4?" if you say it's higher or lower, you'll get an error).
The first time you set min and max numbers, you do it outside of the loop, so this script does "remember" the last guess and applies it to the new min, max inside of the loop. Each time it runs, the min will get higher or the max will get lower, based on the feedback from when the user checks the guess. If you had stuck the "min_num=6" and the "num=80" inside of the loop, the guesses would never get better.
import random
import time
import sys
print("\tAge Guesser!")
print("\t8 tries only!")
name = input("\nWhat's your name? ")
max_num = 10
min_num = 1
tries = 1
guess = random.randint(min_num, max_num)
print("\nLet me guess... You are", guess, "years old?")
check = raw_input("'Higher', 'Lower', or was it 'Correct'? ")
check = check.lower()
while check != "correct":
if tries == 8:
print("\n I guess I couldn't guess your age....")
print("Closing...")
time.sleep(5)
sys.exit()
elif check == "higher":
print("Let me think...")
min_num = guess + 1
time.sleep(3) # pause
elif check == "lower":
print("Let me think...")
max_num = guess - 1
time.sleep(3) # pause
guess = random.randint(min_num, max_num) # <- Picks new random number
print("\nLet me guess... You are", guess, "years old?")
check = input("'Higher', 'Lower', or was it 'Correct'? ")
check = check.lower() # <- Lowercases
tries += 1 # <- Ups the tries by one
print("\nPfft. Knew it all along.")
time.sleep(10)