In [3]:
# First, let the player choose Rock, Paper or Scissors by typing the letter ‘r’, ‘p’ or ‘s’
# first create a prompt and explain
input('what is your name?')
# for python to do anything with the result we need to save it in a variable which we can name anything but this is informative
player = input('rock (r), paper (p) or scissors (s)?')
# what did we just do? we used a built-in function in Python to prompt the user to input a letter in the console
# and we assigned the input to a variable called 'player'. the = symbol indicates that what is on the right is assigned to the variable name on the left
# what is a function like input or print? They let us do things with objects that we've made, like the player variable
# Now print out what the player chose:
#print(player)
#print('you chose', player)
# mention object type as string or integer
#print(player, 'vs')
print(player, 'vs', end=' ')
# Second: Computer's Turn
# Use 'randint' function to generate a random number to decide whether the computer has chosen rock, paper or scissors.
# we need to import it from 'random' library
from random import randint
chosen = randint(1,3) # search google for how to use via documentation
#print(chosen)
#print('computer chose',chosen)
# we like to print the letters not numbers. let's say 1 = rock, 2 = paper, 3=scissors
# we can use if statement to assign letters to whatever number that is selected
if chosen == 1:
computer = 'r' # 'O'
elif chosen == 2:
computer = 'p' #'__'
else:
computer = 's' #'>8'
print(computer)
# run a few times to show the random nature of the function
# notice that we are not inside the if statement because we don't use indentation
# a nicer output:
#print(player, 'vs', computer)
# let's add a code for determining the winner
# we need to compare the 'player' and 'computer' variables
# explain briefly booleans to compare
if player == computer:
print('Draw!')
elif player == 'r' and computer == 's':
print('player wins!')
elif player == 'r' and computer =='p':
print('Computer wins!')
elif player == 'p' and computer == 'r':
print('Player wins!')
elif player == 'p' and computer == 's':
print('Computer wins!')
elif player == 's' and computer == 'p':
print('Player wins!')
elif player == 's' and computer == 'r':
print('Computer wins!')
# Challenge: Instead of using the letters r, p and s to represent rock, paper and scissors, can you use ASCII art?
# O for rock, __ for paper, and >8 for scissors
# so now change the lines you print the choices of the player and the computer in ASCII art
#if player == 'r':
# print('O', 'vs', end=' ')
#elif player == 'p':
# print('__', 'vs', end=' ')
#else:
# print('>8', 'vs', end =' ')
if player == 'r':
print('O', 'vs', computer)
elif player == 'p':
print('__', 'vs', computer )
else:
print('>8', 'vs', computer)
In [ ]:
name = 'Sara'
year = 2017
# we can check the type of our variable using the type(variable_name) function
print(type(name))
#str is a string: a sequence of characters.
In [4]:
7 + 8
Out[4]:
In [2]:
7*8
Out[2]:
In [3]:
8%7
Out[3]:
In [4]:
2**4
Out[4]:
Python's order of operations works just like math's:
In [ ]:
16 ** 0.5
16 ** (1/2)
16 ** 1/2
In [5]:
6 > 0
Out[5]:
In [6]:
4 == 6
Out[6]:
In [7]:
4 <= 6
Out[7]:
In [8]:
4 != 6
Out[8]:
you can continue here https://docs.trinket.io/getting-started-with-python#/logic/combining-boolean-expressions
In [9]:
fruits = ['apple', 'banana', 'mango', 'lychee']
print(fruits)
In [11]:
fruits.append('orange')
print(fruits)
In [12]:
# lists don't need to comprise of all the same type
misc = [29, 'dog', fruits]
In [13]:
print(misc)
In [14]:
print(fruits + fruits)
The second is called a "tuple", which is an immutable list (nothing can be added or subtracted) whose elements also can't be reassigned.
In [15]:
tup1 = (1,2)
print(tup1)
In [ ]:
#indexing in Python starts at 0, not 1 (like in Matlab or Oracle)
print(fruits[0])
In [ ]:
print(fruits[1])
In [ ]:
# strings are just a particular kind of list
s = 'This is a string.'
In [ ]:
print(s[0])
In [ ]:
# use -1 to get the last element
print(fruits[-1])
In [ ]:
print(fruits[-2])
In [ ]:
# to get a slice of the string use the : symbol
print(s[0:4])
In [ ]:
print(s[:4])
In [ ]:
print(s[4:7])
In [16]:
print(s[7:])
print(s[7:len(s)])
In [17]:
nums = [23, 56, 1, 10, 15, 0]
In [ ]:
# in this case, 'n' is a dummy variable that will be used by the for loop
# you do not need to assign it ahead of time
for n in nums:
if n%2 == 0:
print('even')
else:
print('odd')
In [ ]:
# for loops can iterate over strings as well
vowels = 'aeiou'
for vowel in vowels:
print(vowel)
In [18]:
# always use descriptive naming for functions, variables, arguments etc.
def sum_of_squares(num1, num2):
"""
Input: two numbers
Output: the sum of the squares of the two numbers
"""
ss = num1**2 + num2**2
return(ss)
# The stuff inside """ """ is called the "docstring". It can be accessed by typing help(sum_of_squares)
In [ ]:
print(sum_of_squares(4,2))
In [19]:
# the return statement in a function allows us to store the output of a function call in a variable for later use
ss1 = sum_of_squares(5,5)
print(ss1)
In [ ]:
# use a package by importing it, you can also give it a shorter alias, in this case 'np'
import numpy as np
array = np.arange(15)
lst = list(range(15))
print(array)
print(lst)
In [ ]:
print(type(array))
print(type(lst))
In [ ]:
# numpy arrays allow for vectorized calculations
print(array*2)
print(lst*2)
In [ ]:
array = array.reshape([5,3])
print(array)
In [ ]:
# we can get the mean over all rows (using axis=1)
array.mean(axis=1)
In [ ]:
# max value in each column
array.max(axis=0)
In [23]:
import pandas as pd
In [24]:
# this will read in a csv file into a pandas DataFrame
# this csv has data of country spending on healthcare
data = pd.read_csv('health.csv', header=0, index_col=0, encoding="ISO-8859-1")
In [25]:
# the .head() function will allow us to look at first few lines of the dataframe
data.head()
Out[25]:
In [26]:
# by default, rows are indicated first, followed by the column: [row, column]
data.loc['Canada', '2008']
Out[26]:
In [27]:
# you can also slice a dataframe
data.loc['Canada':'Denmark', '1999':'2001']
Out[27]:
In [28]:
%matplotlib inline
import matplotlib.pyplot as plt
In [29]:
# the .plot() function will create a simple graph for you to quickly visualize your data
data.loc['Denmark'].plot()
data.loc['Canada'].plot()
data.loc['India'].plot()
plt.legend(loc='best')
plt.savefig("countries_healthexpenditure.png")
Out[29]:
In [ ]:
In [1]:
import random
number = random.randint(1, 10)
tries = 0
win = False # setting a win flag to false
name = input("Hello, What is your username?")
print("Hello " + name + "." )
question = input("Would you like to play a game? [Y/N] ")
if question.lower() == "n": #in case of capital letters is entered
print("oh..okay")
exit()
elif question.lower() == "y":
print("I'm thinking of a number between 1 & 10")
while not win: # while the win is not true, run the while loop. We set win to false at the start therefore this will always run
guess = int(input("Have a guess: "))
tries = tries + 1
if guess == number:
win = True # set win to true when the user guesses correctly.
elif guess < number:
print("Guess Higher")
elif guess > number:
print("Guess Lower")
# if win is true then output message
print("Congrats, you guessed correctly. The number was indeed {}".format(number))
print("it had taken you {} tries".format(tries))
In [ ]: