Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- #Asks for name
- name = input("What is your name? ")
- #Greeting
- print("Hello ", name)
- #generate random number
- random_num = random.randint(1,20)
- guess = int(input("Take a guess"))
- attempts = 1
- while (guess != random_num and attempts < 5):
- if (guess > random_num):
- print("Too high")
- else:
- print("Too low")
- guess = int(input("Guess again"))
- attempts = attempts + 1
- if (guess == random_num):
- print("You win")
- else:
- print("You lose")
- #Multiplication calculator
- #retrieving user input always stores as strings
- print("Multiplication calculator")
- x = int(input("Enter the first number: "))
- y = int(input("Enter the second number: "))
- answer = x * y
- print("The answer is: {}".format(answer))
- #Conditionals
- #Integer
- age = int(input("What is your age: "))
- # Operators: <, <=, >, >=, ==, !=
- #if 'variable' 'operator' 'variable'
- if age >= 18:
- print("You are an adult!")
- elif age>=13:
- print("You are a teengaer!")
- else:
- print("You are a child!")
- #additional conditions by using and, & or
- if age>=13 and age<=18:
- print("Teenager")
- if age<=13 or age>=13:
- print("Not a teenager")
- colors =["red", "blue", "black"]
- color = input("What is your favorite color? ")
- if (color == "black" or color == "white"):
- print("You like shades")
- elif (color in colors):
- print("Cool!")
- else:
- print("You have not put in a valid color")
- #Looping
- #For loops - pre determined number of times you want to loop something
- '''
- for i in range(1,10,2):
- print(i)
- '''
- #While loops - runs until condition is not met
- #Important to increment conditional variable
- counter = 1
- while counter <= 5:
- print(counter)
- counter = counter + 1
- #Boolean variable = True or False
- profitable = True
- profit = 50
- while profitable != True:
- if (profit < 0):
- profitable = False
- #Integers, doubles, lists, dictionaries
- #Integer
- first_variable = 5
- #Double
- x = 5.5
- #Strings
- name = "Jason"
- #List - associated with multiple values of a variable type... square brackets
- colors = ["red", "blue", "green"]
- scores = [80, 90, 75]
- #indexes start from 0 in Python
- #print(colors[2])
- #print(colors[1:3])
- #Dictionary - keys paired with values...curly brackets
- student1 = {"name" : "Jason", "grade" : 80, "school" : "wlu"}
- student2 = {"name" : "Bob", "grade" : 85, "school" : "wlu"}
- print(student1["name"])
- print(student1.keys())
- print(student1.values())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement