0% found this document useful (0 votes)
36 views24 pages

Python Rock-Paper-Scissors Tutorial

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views24 pages

Python Rock-Paper-Scissors Tutorial

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd

PYTHON

DAY 1

comments are not displayed on output window


for space ___ is used
within “ ” or ' ' for string value(letters or
words)

learning: making functions, setting variables,


calling a function, print command and writing a
comment
creating fuctions, calling them
DAY 2

Dictionaries: n python they are used to


store data values in key value pairs.
Has curly braces at the beginning and end.

EXAMPLE
dict= { “name” : “robin” , “colour” : “blue”}

here, “name” is a key and “robin” is its value


similarly, “colour” is a key and “blue” is its value.
And key or the value can also be a varible.

Now under our older functions get_choices we are


goona add a variable whose value will be equal to a
dictionary in which 1st key will be player_choice and
2nd key will be computer_choice. Then we will
update the return statement to return the dictionary
choices.
NEW CODE
def get_choices():
player_choices='rock'
computer_choices='paper'
choices={ "player":player_choice ,"computer":computer_choice}
return choices

User Input
now, the player_choice here is not the player’s
actual choice its our assigned value.
So now we will see how to take user’s input using
python.
For this input function is used.
So we’ll change player_choice such that it will ask for
a input from the user.

NEW INPUT;

def get_choices():
player_choices= input("Enter a choice
(rock,paper,scissors : ")
computer_choices='paper'
choices= { "player": player_choice , "computer":
computer_choice}
return choices

choices=get_choices() #since the choices variable is


used in the function that does not mean it can’t be
reused as that one is applicable only inside function
this variable is different and independent.

print(choices)

OUTPUT;
Enter a choice (rock,paper,scissors :

after this, in the output window we will type our


input like let’s say rock
and then press enter
OUTPUT
Enter a choice (rock,paper,scissors : rock
{'player': 'rock', 'computer': 'paper'}

=== Code Execution Successful ===

DAY 3
now we are making it like so that computer can
also make a choice.
For this,
Importing libraries, creating lists and
calling method
so we want our program to choose something
randomly from the library this is done by
importing the random library for this we have
to write import random at the starting of the
programme. It lets your computer to select
random elements from sequences. It allows you to
incorporate unpredictability into your programs,
which is useful in scenarios like simulations, games,
statistical sampling, and generating test data.
Import statements are used to import libraries.
They are used at the starting of the
programme.
So we will write import random at the start.
Lists: A list in python is used to store multiple
items in a single variable. A list is surrounded
by brackets [] and each item is seperated by
comma.

Example: food=["pizza","burger","momos"]
this is a list and you can also get a random item
from the list.
By using a varible lets say dinner
dinner=[Link](food)
so then if we use a print command and write
print(dinner) and run that each time computer will
choose randomly from the list food.

INPUT
food=["pizza","burger","momos"]
dinner=[Link](food)
print(dinner)

Running the same many times:


OUTPUT1. pizza
OUTPUT2. burger
OUTPUT3. burger
OUTPUT4. momos
we can see here that each time it is randomly
giving output.
We also want the same in our rock,paper,scissors
game so we are going to create a list called options
containg the 3 options from which the computer can
choose and then using random command this will
become a whole new game.

INPUT
import random

def get_choices():
player_choice=input('Enter a
choice:rock,paper,scissors :)')
options=['rock','paper','scissors']
computer_choice= [Link](options)
choices={"player":player_choice,
"computer":computer_choice}
return choices
choices=get_choices()
print(choices)

let’s see here, we have to give input for the player


choice and computer will ch0ose randomly.

OUTPUT
[Link] a choice:rock,paper,scissors :)paper
{'player': 'paper', 'computer': 'scissors'}
2. Enter a choice:rock,paper,scissors :)paper
{'player': 'paper', 'computer': ['paper']}

[Link] a choice:rock,paper,scissors :)rock


{'player': 'rock', 'computer': ['paper']}

[Link] choice:rock,paper,scissors :)paper


{'player': 'paper', 'computer': ['rock']}

Function Arguments: Function can receive


data when they are called, the data are called
arguments. In a function we can specify
arguments inside the parantheses. The fuction
get_choices() contains empty parantheses so it
does not have any argumemt, its an empty
function.

now we will create a new function


check_win(player,computer) which when called
will give two pieces of information which is
value assigned to the varible player and
computer. We want it to return a list so
we’ll write return[player,computer]

If statements: it will allow a programme to do


different things depemding on certain
conditions. It wil first check a conditions and if
the condition is true than all lines of the code
written under the if statement will execute.

Example

INPUT:
a=3
b=2
if a>b:
print('yes')

OUTPUT:
yes

NOTE: let’s say we want to check if a equals b, then


we can’t write a=b in code we have to write if a==b,
because = is assignment operator that is used to
assign values to the varibles.

DAY 4

so now by using if statement we are going to update


the check_win function.
We want to check if player == computer then we
want it to return It’s a tie!
But how will the user know which options did the
player and the computer chose,so we will make the
programme do that.
if player==computer:
return "It's a tie!"

Concatenating strings:
combining strings with other strings or strings with a
variable.
It can be done by using a + sign between a string
and a variable.
Example print("Player chose "+player+" computer chose " + computer)

this can also be done by using f strings


in this we use f” instead of quotation mark, and then
when we need to put a variable or a python code we
will write that inside curly braces {}.

Example:
Input
age=25
print(f"Jim is {age}. ")

Output
Jim is 25.
so in our code: replacing + with f”
print(f"Player chose {player}, computer chose {computer} .")
now if we call the check_win function
Input
def check_win(player,computer):
print(f"Player chose {player}, computer chose {computer} .")
if player==computer:
return "It's a tie!"
check_win("rock","paper")

Output
Player chose rock, computer chose paper .

Else and elif statements:


The statements are used in order if then elif and
then else. Else is not mandatory in python but the
order is.
Example
Input
age=20
if age>=18:
print("You are an adult.")
elif age >12:
print("You are a teenager.")
elif age>1:
print("You are a child")
else:
print("You are a baby.")

Output
You are an adult.

=== Code Execution Successful ===


so similarly in our rock,paper,scissors programme
we can do that by using these statements. To look
for 2 conditions together “and” will be used.
Like this,
if player==computer:
return "It's a tie!"
elif player=="rock" and computer=="paper":
print("Paper covers rock. You loose.")
elif player=="rock"and computer=="scissors":
print('Rock smashes scissors. You win!')

now to make it simpler,


Refactoring and nested if:
It means using an if, elif or else statements inside
another if, elif or else statement.
This makes things simpler.
So editing our code to:

def check_win(player,computer):
print(f"Player chose {player}, computer chose {computer} .")
if player==computer:
return "It's a tie!"
elif player=="rock":
if computer=="paper":
return "Paper covers [Link] loose."
else:
return "Rock smashes scissors. You win!"

elif player=="paper":
if computer=="scissors":
return "Scissors cuts paper. You loose."
else:
return "Paper covers rock. You win!"

elif player=="scissors":
if computer=="paper":
return "Scissors cuts paper. You win!."
else:
return "Rock smashes scissors.. You loose."

so now let”s play.


So for this we will call our get_choices function.
But the thing is that get_choices is a dictionary so
we are gonna learn how to access dictionary values.

Accessing dictionary values:


for this first take a varible let’s say abc and then
assign its value like that, first we will write the name
of the dictionary and then in [] brackets we will write
name of the key of the dictionary we want the value
of.
abc=choices[“player”]
so let’write the final code to play.
So we will take a varible result and assign it’s value
equals to calling the check win function, this time
the argument of check win function will be the
dictionary key value of get_choies function.
choices=get_choices()
result=check_win(choices["player"], choices["computer"])
print(result)

Output
1. Enter a choice: rock,paper,scissors :)rock
Player chose rock, computer chose paper .
Paper covers [Link] loose.

2. Enter a choice: rock,paper,scissors :)paper


Player chose paper, computer chose paper .
It's a tie!

3. Enter a choice: rock,paper,scissors :)papear


Player chose papear, computer chose rock .
None #shows what will happen if you give output out of options
4. Enter a choice: rock,paper,scissors :)paper
Player chose paper, computer chose rock .
Paper covers rock. You win!

DAY 5

Variables:
we can create a new python variable by assigning a
vlue to the label by using the assignment
operator(=).
A variable name can be composed of characters,
numbers and underscore, but it could not start with
a number.
It can be like name, HEIGHT , name123 , name__ or
__name__ etc.
But it cannot be a number or it should not contain !
Mark or % sign.

It should also not be a python keyword (keywords


used to write a python code) like for, if, else, elif,
while, import etc.

Expressions and statements:


An expression is any sort of code that returns a
value.
Example 1+1, Beau

A statement is an operation on a value. A Python


statement is an instruction that the Python
interpreter can execute.
A programme is created with a series of statement.
By default each statement takes its own seperate
line but you can use a semi-colon ; to add more than
one statement in a line.
Comments:
in python, everything after a hash mark # is
ignored. This is called comments. They really aren’t
part of the programme but programmer puts it as
some sort of special note.

A comment in Python is a line or block of text within


the code that is ignored by the Python interpreter
during program execution. Comments are primarily
used to provide explanations, notes, or
documentation within the code, making it more
readable and understandable for humans.

Day 6
Importance of indentation in python:

In Python, indentation is used to define the

structure and hierarchy of the code .


There are different languages in which the white
space is not meaningful but in python if a line is
indented below the other line it means it is under
that.

Data types:
In Python, a data type is a classification that
specifies which type of value a variable can hold. It
defines the operations that can be performed on that
data and how the data is stored in memory.
Python has some built in data types like str (string),
int(integer), float(decimal values), etc.
i.) You can check type of variable using the type
function.
Example:
name="Beau"
print(type(name))
Output:
<class 'str'>

To test that:
Input 1
name="Beau"
print(type(name)==str)
Output
True
Input 2
name="Beau"
print(type(name)==int)

Output
False

We can also test that isinstance.


For example, to check if name is an instance of a
string;
INPUT
name="Beau"
print(isinstance(name,str))
OUTPUT
True
We can also create a variable of a specific type by
using the class constructor.
For example;
age=2
print(isinstance(age,float))
so now, it will shows false, but we can make it a float
by using the class constructor.

For this,
age= float(2)
print(isinstance(age,float))
so here, bydefault the number 2 is not a float but it
will be converted into a float by this and it shows true

in the output.
So we can basically convert one data type into
another by using the class constructor.
We can also convert a string into an integer,
age= "20"
print(isinstance(age,int))

now it shows false at the console but when we will do


this;
age= int("20")
print(isinstance(age,int))
it shows true
when we do somethimg like this it’s called casting,
it’s basically trying to extract an integer from a
string, but it’s not always possible like if we;
age= int("test")
print(isinstance(age,int))

so there are some common data types like;


complex for complex numbers,
bool for booleans,
list for lists,
tuple for tuples,
dict for dictionaries,
range for ranges,
set for sets. We’ll learn about them in detail.
Day 7

Operators: In Python, an operator is a special


symbol or keyword that performs an operation on
one or more values or variables, known as
operands. Operators are used to manipulate data,
perform calculations, make comparisons, and control
program flow.

Types:
1. Assignment Operators:
Used to assign values to variables. Examples include
simple assignment (=), and compound assignments
like +=, -=, *=, etc
+= means ;
age=8
age+=8 #output=age+8 means 16
age*=8 #means age*8 means output=64

Example:
age=4
age+=4
print(age) #output=8

age=4
age*=4
print(age) #output=16

age=4
age-=4
print(age) #output=0

age=4
age/=2
print(age) #output=1.0
Arithmetic operators:
Used for mathematical operations like addition (+),
subtraction (-), multiplication (*), division (/),
modulus (%), exponentiation (**), and floor division
(//).
floor divison=basically fuctions like greatest integer
function it rounds down, means after division it
returns the largest integral value less than or equal
to the quotient.
Modulus operator(%) performs the division and
returns the integral reminder.
Examples
Input
print(1+1)
print(3**3)
print(5//2)
print(5%2)
print(1*8)
Outputs
2
27
2
1
8
import random
def get_choices():
player_choice= input("Enter a choice: rock, paper,
scissors :")
options=["rock", "paper", "scissors"]
computer_choice= [Link](options)
choices= { "player": player_choice, "computer":
computer_choice}
return choices
def check_win(player,computer):
print(f" Player chose {player} , computer chose
{computer}. ")
if player==computer:
return ("It's a tie!")
elif player=="rock":
if computer=="paper":
return "Paper covers rock. You lose."
else:
return " Rock smashes scisssors. You win!"

elif player== 'paper':


if computer== 'rock':
return "Paper covers rock. You win!"
else:
return "Scissors cuts paper. You lose."

elif player== 'scissors':


if computer== 'rock':
return "Rock smashes scisssors. You lose"
else:
return "Scissors cuts paper. You win!"

choices=get_choices()
result= check_win( choices["player"],
choices["computer"])
print(result)

self created game:


import random
def choose_number():
player_choice=input(" Guess a number between 1 to 10")
number=[1,2,3,4,5,6,7,8,9,10]
secret_number=[Link](number)
choice={"player":player_choice,"secretno":secret_number}
return choice
print(choose_number())

def check_the_guess(x:int,y:int):
if x==y:
return "You got it right."

elif x>y:
return "Too high!"
else:
return "Too low."

choices= choose_number()
result=check_the_guess(int(choices["player"]),choices["secretno"]) #as input
function always returns string value you have to make it an int

print(result)

shortening the code


import random
player=int(input("Choose a number between 1 to 10"))
number=[1,2,3,4,5,6,7,8,9,10]
computer=[Link](number)
if player==computer:
print ("You got it right!")
elif player>computer: # as input returns only string values..
print ("Too high!")
else:
print ("Too low.")

You might also like