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

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

Related

I'm having trouble with the code where the budget variable wasn't deducting throughout the loop. It instead do nothing or sometimes add up

enter image description hereI'm making an inventory system code and I'm a bit stuck finding a solution to the substraction problem, when I choose "ADD" and entering the input the formula wasn't getting the accurate outcome. For example, if I input Paper001 then its quantity, the output is fine at first but when input another item, the deduction instead becoming addition or sometimes doesn't do anything.
I tried dividing the values in the dictionary in 3 conditions but it turns out even worse.
while True:
try:
bg = float(input("Enter your budget : "))
print("-----------------------------------------------------------")
print(" Item name Item code Item price(Per set) \n")
print("1.Bond Paper : Paper001 100 PHP\n2.Yellow Paper : Paper002 50 PHP\n3.Intermediate Paper : Paper003 20 PHP\n\n")
s = bg
except ValueError:
print("PRINT NUMBER AS A AMOUNT")
continue
else:
break
a ={"name":[], "quant":[], "price":[]}
# converting dictionary to list for further updation
b = list(a.values())
# variable na value of "name" from dictionary 'a'
na = b[0]
# variable qu value of "quant" from dictionary 'a'
qu = b[1]
# This loop terminates when user select 2.EXIT option when asked
# in try it will ask user for an option as an integer (1 or 2)
# if correct then proceed else continue asking options
while True:
try:
print("-----------------------------------------------------------")
ch = int(input("1.ADD\n2.STORAGE LIST\n3.Customer purchase\n4.EXIT\nEnter your choice : "))
except ValueError:
print("\nERROR: Choose only digits from the given option")
continue
else:
# check the budget is greater than zero and option selected
# by user is 1 i.e. to add an item
if ch == 1 and s>0:
p_list={'Paper001':100,'Paper002':50,'Paper003':20}
pn = input("Enter item code : ")
if pn in p_list.keys():
q = int(input("Enter quantity : "))
else:
print("-----------------------------------------------------------")
print("Code is invalid")
continue
#checks if item name is already in the list
if pn in na:
ind = na.index(pn)
# remove quantity from "quant" index of the product
qu.remove(qu[ind])
# new value will be added to the previous value of user's quantity
qu.insert(ind, q)
tpr = (q+q)*p_list[pn]
print(f" Total product price:",tpr)
s = bg-tpr
print("\namount left", s)
else:
# append value of in "name", "quantity", "price"
na.append(pn)
# as na = b[0] it will append all the value in the
# list eg: "name"🙁"rice"]
qu.append(q)
# after appending new value the sum in price
# as to be calculated
tpr = q*p_list[pn]
print("\nTotal product price:",tpr)
s = bg-tpr
if s==0:
print("No more budget left")
print("\nAmount left :", s)
elif s>0:
print("\nAmount left :", s)
else:
print("Insufficient budget. Cannot buy item.")
print("Please restart and re-enter your budget.")
break
elif ch ==2 :
print("\n\n\nStorage list")
print("Item name Stocks ")
for i in range(len(na)):
print(f"{na[i]} {qu[i]}")
continue
elif ch == 3:
print("-----------------------------------------------------------")
p_list={'Paper001':100,'Paper002':50,'Paper003':20}
print("\n\n\nStorage list")
print("Item name Stocks ")
for i in range(len(na)):
print(f"{na[i]} {qu[i]}")
co = input("\nEnter customer's order : ")
if co in p_list.keys():
q = int(input("Enter quantity : "))
sl = qu[i]-q
print("Item is sold!")
print("Stocks left :",sl)
if sl <=0:
print("Please add new items!")
else:
print("-----------------------------------------------------------")
print("Code is invalid")
continue
elif ch==4:
print("")
print("\nThank your for shopping with us!")
break
elif s==0:
print("NO BUDGET LEFT. UNABLE TO ADD ITEMS.")
else:
print("ERROR: Choose only the digits given from the option.")

Getting the right calc for multiple if statement in tableau

I’m trying to write a if then statement on tableau but I might be missing something it’s a multiple comparison
What I have now
If {Receive campus match } = false then ‘0’
Else
If { matches lag} = true then true else false
Else
If { days difference between goods planned vs shipped} < = 0
Then { fixed .......} there’s an LOD
ELSE ‘0’
End
End
End
But it not correct ! Help will be needed
Since you have not uploaded any data/screenshot, it is very difficult to understand your problem, yet I can see a few errors in your proposed calculation.
Your proposed calculation, if broken into phrases becomes like this-
line-1 If {Receive campus match } = false
line-2 then ‘0’
line-3 Else If { matches lag} = true
line-4 then true
line-5 else false
line-6 Else If { days difference between goods planned vs shipped} < = 0
line-7 Then { fixed .......} there’s an LOD
line-8 ELSE ‘0’
line-9 End End End
Problem-1: In tableau there is ELSEIF and not ELSE IF
Problem-2: You cannot start a new else if (sic!) (line-6) once an else (line-5) has been provided
Problem-3: Why three END in line-9?
Basically the syntax of IF THEN ELSE IF ELSE END goes like this...
IF <Condition>
Then <Result 1>
ELSEIF <condition 2>
then <Result>
... Repeat ELSEIF and THEN here, if you have several conditions
ELSE <last result corresponding to last false condition>
END

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

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.

Increment issue while colliding objects in unity3d

I am creating a basic game for test purpose in unity3D where i will counter the number of objects whenever the collision occurs on the defined object. I have created objects named birds1 upto birds8 While hitting the objects with name birds1, birds2. I am trying to increment the counter, it should increment the value of f by 1, if the hit the bird here the counter increments by random number instead of increment by 1. I have set a value that the counter should not exceed a limit of 8 so it stops at a limit of 8. Below is my code i am posting the code that i am using. Please can anyone help me with this that where is my code running wrong.
public void OnTriggerEnter2D(Collider2D target)
{
if (target.gameObject.name == "bird1" || target.gameObject.name == "bird2" || target.gameObject.name == "bird3" || target.gameObject.name == "bird4" || target.gameObject.name == "bird5" || target.gameObject.name == "bird6" || target.gameObject.name == "bird7" || target.gameObject.name == "bird8" && f < 8)
{
f++;
propPAnel8.SetActive(true);
BirdText.text = "x " + f;
if (f == 8)
{
bound8.isTrigger = true;
}
}
}
OnTriggerEnter2D will be called multiple times, especially if you have colliders with multiple contact points: That is why the increment in f it appears seemingly random, however, in this case, it is not.
You get increments as much as your contact points during the collision. What are you trying to achieve with the increment of 1? Maybe you need a boolean instead and setting isTrigger property of your Collider2D to false would help, but that depends on your game logic.

Using switch statement and while loop in conjunction

I am trying to complete the following task:
Create
a
script
that
will
repeatedly
create
a
random
integer
K
in
the
range
of
0
to
20
until
every
case
has
been
entered
at
least
once.
You
have
3
possible
cases.
Case
A
is
entered
when
the
range
of
the
random
integer
K
is
between
or
equal
to
0
and
7.
Case
B
is
entered
when
the
range
of
the
random
integer
K
is
between
or
equal
to
8
and
14.
Case
C
is
entered
when
the
range
of
the
random
integer
K
is
between
or
equal
to
15
and
20.
Rules:
When
a
case
is
entered
you
must
print
to
the
user
“Congratulations
you
entered
Case
(A,
B,
or
C)”.
You
can
only
enter
each
case
once.
If
the
program
attempts
to
enter
the
same
case
more
than
once,
you
must
print.
“Invalid,
that
case
has
already
been
entered”.
The
program
will
end
once
all
the
cases
have
been
entered
and
the
program
will
print
“Good
job,
you
have
entered
all
cases”.
If
the
program
attempts
to
enter
any
already
entered
cases
more
than
3
times
(3
total
times
not
just
for
one
specific
case),
the
program
will
end
and
print
to
the
user
“That
random
generator
wasn’t
random
enough”.
Here is the code I have so fa. It has taken me a couple hours to debug. Am I approaching this the wrong way????Please let me know.
K = round(rand*(20))
flag = 0;
counterA =0;
counterB=0;
counterC=0;
switch K
case {0,1,2,3,4,5,6,7}
fprintf('Congratulations you entered Case A\n')
flag = 1;
counterA = 1
case {8,9,10,11,12,13,14}
fprintf('Congratulations you entered Case B\n')
flag =2;
counterB = 1
case {15,16,17,18,19,20}
fprintf ('Congratulations you entered Case C\n')
flag = 3;
counterC = 1
end
while flag == 1 || flag == 2 || flag ==3
K = round(rand*(20))
if K >=0 && K<=7 && flag==1
disp ('Invalid, that case has already been entered')
counterA = counterA+1
elseif K >=8 && K<=14 && flag ==2
disp ('Invalid, that case has already been entered')
counterB=counterB+1
elseif K >=15 && K<=20 && flag==3
disp ('Invalid, that case has already been entered')
counterC =counterC+1
elseif K >=0 && K<=7 && flag ~=1
counterA =counterA+1
flag == 1;
if counterA==1&&counterB~=2 ||counterA==1&&counterC~=2
fprintf('COngrats guacamole A\n')
end
elseif K >=8 && K<=14 && flag ~=2
counterB=counterB+1
flag == 2;
if counterB ==1&&counterA~=2||counterB==1&&counterC~=2
fprintf('COngratsavacado B\n')
end
elseif K >=15 && K<=20 && flag~=3
counterC=counterC+1
flag == 3;
if counterC==1&&counterA~=2||counterC==1&&counterB~=2
fprintf ('Congratscilantro C\n')
end
end
if counterA==1 && counterB==1 && counterC==1
flag=100;
disp('DONE')
elseif counterA == 3|| counterB==3 || counterC==3
disp ('That random generator wasnt random enough')
flag =99;
elseif counterA==2||counterB==2||counterC==2
disp('Inval')
end
Some words about your code:
Don't use variable names like counterA,counterB,counterC, use a array with 3 elements instead. In this case: You need only a total limit, thus one variable is enough.
rand*20 generates random values between 0 and 20, but using round(rand*20) causes a lower probability for 0 and 20. Use randi if you need integers.
Use "Start indent" to format your code clean, it makes it easier to read.
This is not a full solution, the part with the 3 errors is missing. I think you will get this on your own.
caseNames={'A','B','C'};
caseEntered=[false,false,false];
%while there exist a case which is not entered and limit is not reached, continue
while ~all(caseEntered)
K = randi([0,20]);
switch K
case {0,1,2,3,4,5,6,7}
cs=1;
case {8,9,10,11,12,13,14}
cs=2;
case {15,16,17,18,19,20}
cs=3;
end
if caseEntered(cs)
%case has previously been entered, tdb
else
%case is entered frist time
fprintf('Congratulations you entered Case %s\n',caseNames{cs});
caseEntered(cs)=true;
end
end