Adding a new name/item to a list and calling that variable globally? - numbers

I'm pretty much brand new to coding and decided to start with Python. I have been working on a simple "Number Guessing Game" and have evolved it a bit more each iteration.
I decided that I want to make it a little bit more robust that just finishing after the number is guessed.
I want the user/player to enter their name, have that name stored, and then used throughout... until the end, when they're asked if they want to play again and if it's the 'same user?" and if they say, "No.", I want it to append a new name to the list and then go through the game again.
This is what I've got so far... please be gentle... I know there's some errors :(
import sys
import os
import random
global player
while True:
def GuessingGame():
player = []
player.append(input("Please Enter Your Name:\n")),
# player_name = input("Please enter your name: \n")
print(f"Hello, {player[0]}! Let's get started!\n")
number = 500
count = 1
guess = int(input("Guess a number between 1 and 1000: \n"))
while guess != number:
count += 1
if guess > (number + 10):
print("TOO HIGH, a little lower...")
elif guess < (number - 10):
print("TOO LOW... guess higher!")
elif guess > (number + 5):
print("You're getting warmer, but still TOO HIGH, a little lower...")
elif guess < (number - 5):
print("You're getting warmer, but still TOO LOW... higher!")
elif guess < number:
print("You're REALLY warm, but still a bit TOO LOW")
elif guess > number:
print("You're REALLY, but still a bit TOO HIGH")
guess = int(input("Try again...\n"))
if guess == number:
print(f"You got it!!! It took you {count} tries to guess {number}\n")
response1 = str(input("Would you like to try again? Y or N\n"))
if response1 == ("y" or "Y"):
sameplayer = str(input("Is this still {player[0]}? Y1 or N1\n"))
if sameplayer == ("y1" or "Y1"):
GuessingGame()
else:
newplayer = player.extend(str(input("Please Enter New Player's Name:\n")))
print(f"Hello, {player[1]}!, Let's Get Started!")
return
GuessingGame()
Again, this is the first time I'm sharing anything I've done... so please don't just wreck me :)

Here i copy the same code you wrote, but with a little bit of modifications that i felt were needed to be made.
from random import randint
player = None
def GuessingGame():
global player
if player is None:
player = input("Please Enter Your Name:\n")
print(f"Hello, {player}! Let's get started!\n")
number = randint(1, 1000)
guess = int(input("Guess a number between 1 and 1000: \n"))
count = 1
while guess != number:
if guess > (number + 10):
print("TOO HIGH, a little lower...")
elif guess < (number - 10):
print("TOO LOW... guess higher!")
elif guess > (number + 5):
print("You're getting warmer, but still TOO HIGH, a little lower...")
elif guess < (number - 5):
print("You're getting warmer, but still TOO LOW... higher!")
elif guess < number:
print("You're REALLY warm, but still a bit TOO LOW")
elif guess > number:
print("You're REALLY, but still a bit TOO HIGH")
if guess == number:
break
else:
count += 1
guess = int(input("Try again...\n"))
print(f"You got it!!! It took you {count} tries to guess {number}\n")
response1 = str(input("Would you like to try again? Y or N\n"))
if response1.lower() == 'y':
sameplayer = str(input(f"Is this still {player}? Y or N\n"))
if sameplayer.lower() == 'n':
player = None
return
else:
return
while True:
GuessingGame()
Let me know if you got any questions.

Related

Basic Tally and Tracking

Hi thank you to anyone looking, I'm new in a beginners class. I have a game where a dealer and a player each guess a number and a random number is generated. Whoever is closest wins the round. After 5 rounds print("Dealer wins: Player wins: ") and the number of rounds won will populate in that print statement. If dealer tallied 3-5 wins print("Sorry Try Again") if player tallied 3-5 wins print("Congrats you win") I have have it looped but not set to end after five rounds and then can't figure out the tally which counts the rounds and prints the results.
while True:
player = int(input("Guess a Number:"))
print(player)
dealer = int(input("Dealer Guess:"))
print(dealer)
import random
num1 = random.randint(0, 100)
print("Random Number:")
print(num1)
playerdist = abs(player - num1)
dealerdist = abs(dealer - num1)
if (playerdist > dealerdist):
print("Dealer Wins")
if (playerdist < dealerdist):
print("Player Wins")
if (playerdist == dealerdist):
print("Draw")
Maybe you can add a iterator to count the rounds, if the rounds reached 5, then exits.
for i in 5:
# rest of the codes

Incorrect results in the Rock-paper-scissors game on Python

I want to write a Rock-paper-scissors game in Python. I wrote the code, but I have a problem. When there should be a total of the game I have the program just lists the possible answers of the program. Not the ones that should be. Who doesn't mind, take a look please. I'm a beginner and it's hard for me to find the error.
I already tried to change the code by playing with the while loop, if else conditions. Nothing works. Below is all the code I wrote. Help me out here please.
import random
#Список КНБ
knb = ["stone", "scissors", "paper"]
print('Welcome to the familiar "Rock, Paper, Scissors" game! The rules are quite simple and I think everyone understands. Today your opponent will be a computer.')
print('Here we go! If you want to choose a stone, enter the letter "1", for scissors and paper "2" and "3" respectively.')
comp = random.choice(knb)
user = input('Please choose. Stone, scissors or paper? ')
while True:
if comp == "stone" and user == 1:
print(f"Tie! The computer picked {comp}")
break
elif comp == "scissors" and user == 2:
print(f"Tie! The computer picked {comp}")
break
elif comp == "paper" and user == 3:
print(f"Tie! The computer picked {comp}")
break
while True:
if comp == "stone" and user == 3:
print(f"You win! The computer has chosen {comp}")
break
elif comp == "scissors" and user == 1:
print(f"You win! The computer has chosen {comp}")
break
elif comp == "paper" and user == 2:
print(f"You win! The computer has chosen {comp}")
break
while True:
if comp == "stone" and user == 2:
print(f"You lose! The computer has chosen {comp}")
break
elif comp == "scissors" and user == 3:
print(f"You lose! The computer has chosen {comp}")
break
elif comp == "paper" and user == 1:
print(f"You lose! The computer has chosen {comp}")
break
Im a bit late for the answer but if you are still looking for one here it is.
import random
knb = ["stone", "scissors", "paper"]
comp = random.choice(knb)
user = int(input("Choose stone(1), scissors(2) or paper(3)\n")) #inputs are taken as strings and you are comparing integers so use int()
if (user == 1 and comp == "stone") or (user == 2 and comp == "scissors") or (user == 1 and comp == "paper"):
print("tie") #This is an example to show if you got a tie
print(comp) #This will show what the comp picked

Micro:bit - Accelerometer - (Micro python) make microbit count downward movements - only works with gestures

The following code works just fine:
# Add your Python code here. E.g.
from microbit import *
score = 0
display.show(str(score))
while True:
if accelerometer.was_gesture('face down'):
score += 1
if score < 10:
display.show(score)
else:
display.scroll(score)
continue
'''But when I try to replace was_gesture('face down') with get_Z i get an error:'''
# Add your Python code here. E.g.
from microbit import *
score = 0
display.show(str(score))
z = accelerometer.get_z()
while True:
if z < accelerometer.get_z(-500)
score += 1
if score < 10:
display.show(score)
else:
display.scroll(score)
continue
I get an error? But why? I just want to get the microbit to count every time I move the device below a certain point?
The accelerometer.get_z() statement needs to be inside the while loop so that it is updated. The loop also needs a sleep statement so that there is not a backlog of detections to display.
I tested the code below on a micro:bit using the mu editor. When the microbit is LED side up, the count increments. When it is face down, the count stops.
from microbit import *
uart.init(baudrate=115200)
score = 0
display.show(str(score))
while True:
z = accelerometer.get_z()
if z < -500:
score += 1
if score < 10:
display.show(score)
else:
display.scroll(score)
sleep(1000)
continue
You've missed a colon at the end of this line:
if z < accelerometer.get_z(-500)
Also, the get_z() method doesn't take any arguments:
https://microbit-micropython.readthedocs.io/en/latest/accelerometer.html#microbit.accelerometer.get_z

Program not running with error unsupported operand type(s) for +: 'function' and 'int'

Im creating a program for NIM for my Python Intro class, and am having a problem with trying to get the program to finish.
I am at a loss...
def main():
import random
#User random to generate integer between 10 and 100 for random pile size of marbles.
ballCount = random.randint(10, 100)
print("The size of the pile is: ",ballCount)
#Generate a random integer between 0 and 1, this will tell if the human or computer takes first turn.
def playerTurn(ballCount):
playerTurn = random.randint(0, 1)
if playerTurn == 0:
print("Its the computers turn...")
else:
print("Its your turn...")
#Generate a random integer between 0 and 1, to determine if the computer is smart or dumb.
computerMode = random.randint(0, 1)
def computerDumbMode(ballCount):
computerMode = random.randint(0, 1)
if computerMode == 0:
print("This computer is very dumb, no need to stress")
def computerSmartMode(ballCount):
computerMode = random.randint(0, 1)
if computerMode == 1:
print("This computer is very intelligent, beware")
#In dumb mode the computer generates random values (between 1 and n/2),
#you will use a random integer n for ballCount, when it is the computers turn.
while ballCount != 1: #This will compile untill you are left with only one marble.
if playerTurn == 0: #This will initiate computers turn.
if computerMode == 1: #This will initiate Smart Mode.
temp = random.randint(1, ballCount/2) #Pick a random number between 1, and n/2.
else: # Pick your own number of Marbles for your ballCount (n).
if ballCount - 3 > 0 and ballCount - 3 < ballCount/2:
temp = ballCount - 3
elif ballCount - 7 > 0 and ballCount - 7 < ballCount/2:
temp = ballCount - 7
elif ballCount - 15 > 0 and ballCount - 15 < ballCount/2:
temp = ballCount - 15
elif ballCount - 31 > 0 and ballCount - 31 < ballCount / 2:
temp = ballCount - 31
else:
temp = ballCount - 63
print("The computer has chosen: %d marbles." % temp) #Print the number of marbles the computer has chosen.
ballCount -= temp #Then subtract the number of marbles chosen by the computer.
else:
ballCountToPick = int(input("It is now your turn, Please pick the number of marbles in the range 1 - %d: " % int(ballCount/2))) #Reads the number of marbles to be picked by user.
while ballCountToPick < 1 or ballCountToPick > ballCount/2: #If computer reads this invalidly, it will try repeatedly.
ballCountToPick = int(input("The number you chose, is incorrect. Try again, and pick marbles in the range 1 - %d: " % int(ballCount/2)))
ballCount -= ballCountToPick #Subtract the marbles that were chosen by user.
playerTurn = (playerTurn + 1) % 2 #Changes the turn of player.
print("Now the pile is of size %d." % ballCount)
if playerTurn == 0: #Show the outcome.
print("You came, you saw, and you won... CONGRATULATIONS!!!")
else:
print("Once again... You lost and the computer wins!!!")
main()
Trying to get the program/game to run and print end result if the computer or person wins!
Your "playerTurn" variable is a function in the following line:
playerTurn = (playerTurn + 1) % 2 #Changes the turn of player.
Have a separate "playerTurn" function and "player_turn" variable will resolve your problem.

Scala dice program

I've just started Scala at University and we're currently just doing the basics but I'm moved ahead and want to try making some basic programs to get ahead. I'm currently trying to make a basic dice role guessing program.
I want to add in a feature to replay the game, the counter is to tell the user how many attempts to guess. I know I can add it in somewhere with counter += 1 just not sure where in the program to put it.
Currently compiling does nothing until I input something and I'm unsure why, then when I input something I don't get any results from the if statements it just terminates the program.
import scala.io.StdIn.readInt
import scala.util.Random
object GuessTheNumber {
def main(args: Array[String]): Unit = {
var play = true
var counter = 0 //Allows counting input
var responseGuess = readInt()
val numRange = Random.nextInt(12)
println("Enter your guess of the result of 2, 6 sided dice.")
while(play) {
if (responseGuess == numRange)
println ("You got it right!")
else if (numRange < responseGuess)
("Your guess was too large by" + (responseGuess - numRange) + " the corrrect answer was " + numRange)
else if (numRange > responseGuess)
( "Your guess was too small by" + (numRange - responseGuess) + " the correct answer was " + numRange)
else if (responseGuess < 1)
("Your guess is too small enter 2-12")
else if (responseGuess > 12)
("You entered an invalid number, 2 dice can only equate to a maximum of 12")
}
}
}
A couple things:
You should ask for a guess (the println) before you go get it from the input
All of your else if blocks were missing println statements
You aren't using your counter
Your numRange is incorrect, right now it would return 0 to 11 inclusive
I made those changes, and moved the readInt() inside the while loop to give people multiple chances to guess, once they guess the answer then the loop exited.
var play = true
val numRange = 2 + Random.nextInt(11)
while(play) {
println("Enter your guess of the result of 2, 6 sided dice.")
var responseGuess = readInt()
if (responseGuess == numRange) {
println ("You got it right!")
play = false
}
else if (numRange < responseGuess)
println("Your guess was too large")
else if (numRange > responseGuess)
println( "Your guess was too small")
else if (responseGuess < 2)
println("Your guess is too small enter 2-12")
else if (responseGuess > 12)
println("You entered an invalid number, 2 dice can only equate to a maximum of 12")
}
You can build off of this to get the functionality you need.
You had a few basic errors, but, a really good first attempt. I have included most of the comments in context for clarity. Here is a quick summary of some of the things that needed minor corrections
You forgot to include println in every else clause
You didn't reset the value of play variable causing your program to be stuck in an infinite loop. The while loop kept executing without asking user for any input giving the illusion that nothing was printing
The counter needs to be updated after every attempt within the loop
import scala.io.StdIn.readInt
import scala.io.StdIn.readChar
import scala.util.Random
object GuessTheNumber {
def main(args: Array[String]): Unit = {
var play = true
var counter = 1 //Allows counting input
// Start a loop. As long as the user says he wants to continue, we keep entering the loop
while (play) {
// The game is slightly more clear in my humble opinion if you ask him/her this question after every attempt.
// Otherwise you just have a blinking cursor on screen, without prompting user for input
println("Enter your guess of the result of 2, 6 sided dice.")
// Read his current response
val responseGuess = readInt()
// If you don't have `1 +`, then, 0 could be a potential result
val numRange = 2 + Random.nextInt(11)
if (responseGuess == numRange)
println(s"You got it right! in $counter attempts")
// You were missing println in each of the following cases. Hence the lack of response from your program, since,
// it didn't know you wanted it to print that response
else if (numRange < responseGuess)
println("Your guess was too large by " + (responseGuess - numRange) + " the correct answer was " + numRange)
else if (numRange > responseGuess)
println( "Your guess was too small by " + (numRange - responseGuess) + " the correct answer was " + numRange)
else if (responseGuess < 1)
println("Your guess is too small enter 2-12")
else if (responseGuess > 12)
println("You entered an invalid number, 2 dice can only equate to a maximum of 12")
println("Do you want to continue? (Y/N)")
// Now you are reading a character instead of an integer. Basically a Y or an N
play = readChar() match { // Not sure if you have gotten this far in your course. This syntax is referred to as pattern matching.
// Its basically the same as using if / else
case 'Y' | 'y' => true // If he enters Y or y, we assume he wants to continue.
case _ => // For any other input we abort
println(s"You tried $counter times") // When he does decide to quit, lets tell him how many times he tried
false
}
// After every attempt increment counter within your loop
counter += 1
}
}
}
Hope this helps.