Learn Python
NeutralLite

Learn Python:

To create a variable we need to give it a name, variables need to be single words and therefore have no spaces.

If you want to use a variable with plenty of words use a snake case: _
Exp: man_with_no_heard

After naming and creating variable use = sign to store a value inside it:
Exp: city=” Miami”

Device_type=”apple”

The values we are storing Like Miami are Strings strings are words like double quotes
Strings can contain all sorts of letters and symbols. “Winter is coming

Master_Computer=” training lab”

With the special instruction print() we tell the computer to display the value of a computer called console also known as shell: print(“hello world!”)

print(“a,b,c”)

Variables are called variables because the values they store can change:
status=” watching Netflix”
status=” eating popcorn”
print(status)

W e can add the string values together by using + sign
label = "Posts:" + "13"
print( label )
number_of_likes = "40 "
print(number_of_likes + likes )

We use things like * to multiply numbers and / to divide

percent= 0.5*100
print(100)

F-strings allow us to display an expression like adding a string to a number.
Exp: print(f" {2} new messages")

player_1 = "Sam"
player_2 = "Alex"
current_round = 1

print("Game on!")
print(f"player 1: {player_1}")
print(f"player 2: {player_2}")
print("--------------------------")

print(f"Round {current_round}!")
player_1_score = 10
player_2_score = 13
print(f"{player_2} wins with {player_2_score} to {player_1_score}")
print("--------------------------")

To add a second round:
print(f"Round {current_round + 1}!")

player_1 = "Sam"
player_2 = "Alex"
current_round = 1

print("Game on!")
print(f"player 1: {player_1}")
print(f"player 2: {player_2}")
print("--------------------------")

print(f"Round {current_round}!")
player_1_score = 10
player_2_score = 13
print(f"{player_2} wins with {player_2_score} to {player_1_score}")
print("--------------------------")

print(f"Round {current_round + 1}!")
player_1_score = 20
player_2_score = 5
print(f"{player_1} defeats {player_2} by {player_1_score - player_2_score} points")

Visualization makes it easier to see patterns in data, like this pie chart of browser usage.
Pygal Makes it easier to create good looking visualizations.

import pygal
pie = pygal.Pie()
pie.title = "Time Spent on Social Networks"

pie.render_in_browser()

To begin adding some data

We can use true and false

correct=true
print(correct
latest_version=not True/false
print(latest_version)

To compare if 2 numbers are the same we use the ==: exp: print(10==10) and false: 0print(5==9)

To tell if a number is not equal: != exp: print(5!=8)

If a number is less than the number on the right it is true: exp 1<50 true

To check if a number is less than or equal we use the <=

battery_level = 10
low = battery_level <= 20
print("Low battery:")
print(low)

print("online" == "online")
print("online" != "offline")

print("subscribed" != "rejected") true

strings=”awesome”
float=55.00
booleans=true
integer=

We use the if statement to adapt to code in different situations
if True:
print("3 2 1 GO")

To save data for student entry we type id_1=”#4”

id_1 = "#4"
average_grade_1 = "A"
test_score_1= 90

id_2 = "#5"
average_grade_2 = "A"
test_score_2 = 70

no_duplicates = id_1 != id_2
print("No duplicate entries:")
print(no_duplicates)

same_average = average_grade_1 == average_grade_2
print("Same average grade:")
print(same_average)

higher_score = test_score_1 > test_score_2
"id_1 has a higher school:"
higher_score

Tip calculator

bill = 20
tip_percentage = 0.15
tax_percentage = 0.067

tip = bill * tip_percentage
print(f"Tip: {tip}")

tax = bill * tax_percentage
print(f"Tax: {tax}")

total = bill + tip + tax
print(f"Total: {total}"

Code Blocks

greet = True;
if greet :
print("Hello!")

paid = False
if paid:
print("Thank you for your purchase")

answer = "Picasso"
if answer == "Picasso":
print(answer + " is correct!")

age = 75
if age >= 55:
print("Discount applied")

song = "Don't stop me now"
replay_times = 345

if replay_times >= 300:
print("Your top song this week: ")
print(song)

inbox_full = True
show_alert = inbox_full == True;

if show_alert:
print("Inbox full")
print("Archive some to continue")#
inbox_full = True
show_alert = inbox_full == True;

if show_alert:
print("Inbox full")
print("Archive some to continue")

To add a backup plan when using if statement use else:
Exp

available = False

if available:
print("In stock")
else:
print("Out of stock")

points = 7600
points_needed = 8000

if points >= points_needed:
print("You're Level 2!")
else:
left = points_needed - points
print("Points till Level 2:")
print(left)

CONDITIONAL STATEMENTS

For a more specific condition if the hour is greater than 12 but less than 14 add code:
hour = 14

print("Good afternoon"

The and-operator allows us to run code only If the conditions are true:

age = 17
has_permit = True

if age > 16 and has_permit:
print("Can drive")

subway_defect = True
is_sunny = True
distance = 2

if subway_defect and is_sunny and distance <= 2:
print("Walk to work")

To run code when either one of the conditions is True we use the or operator:

average_grade = "A"
final_score = 1400

if average_grade == "A" or final_score >= 1300:
print("Certificate achieved!")

A self-assignment is when we set a variable to its value:
wallet = 3
wallet = wallet + 1

print(wallet)

You can do it with strings too.

name = "Account name: "
name = name + " Elton"
name = name + " John"

print(name)

To make it faster rather than writing the name again we can add +=:
sales = 5
sales += 1

print(sales)

To subtract: -=

We repeat lines of code by using the while loop:
while True:
print("and again")

while True:
print("To infinity,")
print("and Beyond!"
To stop a loop we create a variable outside of the loop:

keep_going = True

while keep_going == True:
print("and again")

keep_going = False

print("one more time")

To control a time a loop repeats:

counter = 1
while counter < 10:
print(counter)
counter += 1

To create a for loop we add for I in range():

for i in range(5):
print("Happy birthday to you!")

for i in range(10):
print(i)
print("cash")

for
money=[1,2,3]
for coins in money:
print(coins)

Rather than creating a variable for each activity, we can group all of the values into a list using [ ]:

todo = ["Read", "Workout", "Code"]
print(todo)

Every number in a list has a numbered position called an index:

Indices start at zero: that means the second number is [1]

temperatures = [17, 20, 26, 24]
print(temperatures[1])

You can also change the temperature like in third index:

temperatures = [17, 20, 26, 24]
temperatures[2] = 25

To add a value to a list we code list name followed by a period then the instruction like append(25):

scores = [24, 23]
scores.append(25)

print(scores)

By coding insert we can add it in any area we want instead of the end:

shopping = ["kiwis", "peas"]
shopping.insert(0, "lemon")

print(shopping)

To remove the last element of a list, we code .(pop):

todo = ["call mom", "dishes"]

todo.pop()

print(todo)

To remove a specific one we add todo.pop(1)

We can target one value to show:

todo = ["call mom", "dishes", "painting"]

removed = todo.pop(1)

print(removed)

We use len() to get the number of how many people are in a list:

users = ["Sarah", "Mike", "Ella"]

print(len(users))

We can store len in a variable to:

users = ["Sarah", "Mike", "Ella"]

number_of_users = len(users)

print(number_of_users)
We can use len to create if statements:

tasks = ["dishes", "windows", "vacuum"]

if len(tasks) > 0:
print("Ugh, more work!")

To loop through the elements in a list we wright for:

final_scores = [17, 22, 34, 13]

for score in final_scores:
print(score)

minutes_worked = [123, 100, 99, 67]

for minutes in minutes_worked:
print(minutes - 60)

number=2
if number>1:
print("Good")
print("Coco")
Elif number>2:

To begin grouping code we start with the keyword def then greet_user then ():

def greet_user():
print("Good morning Anna")
print("Welcome back")

greet_user()

We can use def to create statements:

def greet_ron():
name = "Ron"
print(f"Hello, {name}");

greet_ron()

def greet_ron():
name = "Ron"
print(f"Hello, {name}");

greet_ron()

def greet_leslie():
name = "Leslie"
print(f"Hello, {name}");

greet_leslie()

Insead of writing 2 lines of code we can store information using one function:

def greet(name):
print(f"Hello, {name}")

greet("April")
greet("Leslie")

def goodbye(name):
print(f"Goodbye,{name}")
goodbye("John")
goodbye("AAmy")

def lamp_status():
power = True
print(f"Powered On: {power}")

lamp_status()

def greet(name):
print(f"Hello, {name}")

greet("Anna")

def user_status():
status = "Active"
username = "Bob"
print(f"{username} is {status}")

user_status()

def divide_in_half(number):
parts=number/2
print(parts)
divide_in_half(10)

To return something from a function we use return label:

def age_label(age):
label = "User age: " + age
return label

(age_label("22"))

def battery_life(power):
print(f"Power at {power}")
return power

battery_life("15 Percent")

def age_label(age):
label = "User age: " + age
return label

result = age_label("29")
print(result)

def givemefive():
return 5
print(givemefive())

def half_twice(number):
half = number / 2
half_again = half / 2
return half_again

result = half_twice(12)
print(result)

To find the large st number in a list code max()

scores = [3, 6, 1, 12]
print(max(scores))

We can save them and reuse them by using them in variables

scores = [3, 6, 1, 12]
min_score = min(scores)
max_score = max(scores)

print(max_score)
print(min_score)

To sort a list like scores we code the list name a dot and then sort:

scores = [3, 6, 1, 12]
scores.sort()
print(scores)

sold_tickets = [7, 20, 12, 30]
print(sold_tickets)
sold_tickets.sort()
print(sold_tickets)

Sum adds up all the scores:

points_penalties = [-3, 10]
print(sum(points_penalties))

sugar = [120, 50]
total = sum(sugar)

print(total)

To combine datasets we use list names and the + operator:

dataset_1 = [1, 2, 3]
dataset_2 = [4, 5]

print(dataset_1 + dataset_2)

seats = [1, 2, 3]
taken = [True, True, False]

print(seats + taken)

team_1 = ["Ana", 78, "Joe", 80]
team_2 = ["Kim", 57, "Sam", 60]

print(team_1 + team_2)

We can also reuse it by putting it in a variable:

dataset_1 = [1, 2, 3]
dataset_2 = [4, 5]

combined = dataset_1 + dataset_2
print(combined)
To count how much a value appears in a list we start with list name then a dot and count:

This is how much yes appears in the list

answers = ["yes", "no", "sometimes", "yes", "no"]
print(answers.count("yes"))

We can also reuse it by using:

free_seats = [False, False, True, True, False]
seats_count = free_seats.count(True)

print(seats_count)

We can replace part of a string stored inside a variable by coding the variables name and the instruction replace():

special = "Today's special is pasta"

new_special = special.replace("pasta","pizza")

=
answer = "The answer is INcorrect"

updated = answer.replace("INcorrect","incorrect")

print(updated)

We can split strings and store the individual values by coding .split() after the variable:

new_users = "Ann Jon Alex"

users_list = new_users.split()

print(users_list)

for user in users_list:
print(f"added {user} to database")

Dictionaries are like lists except they use keys to point to values.

numbers = {"one": "un",
"two": "deux"}
numbers[3] = "trois"
numbers[True] = "quatre"
print(numbers)

n = {"one": "un", "two": "deux"}
print(n["one"])

To get a list of keys:

n = {"one": "un", "two": "deux"}
print(n.keys())

We can use the n keyword to determine if the dictionary has a key:

nicknames = {"Arthur": "Art",
"Lancelot": "Lance"}
print("Arthur" in nicknames)

A module is a file that can contain any type of code:

We use import yo bring a module into a script like import datetime;

import datetime
birthday = datetime.date(1996, 12, 23)
print("I was born on " + str(birthday))

We can also import special functions we need from a module\:

from datetime import date, time
daday = date(1952, 3, 11)
print("Douglas Adams was born on " + str(daday))

We can also rename a function by importing it with the as keyword:

from datetime import date as d
def date(birthday):
print("My birthday: " + str(birthday))
birthday = d(1994, 5, 29)
date(birthday)

We can also make custom modules too by adding a dot and py:

Import numbedr.py

We can also import something from another script without the py:
Import cost

import groceries.budget.cost
prices = [3, 5, 5]
print(groceries.budget.cost.add(prices))

A module is just a .py file and a package( a folder with modules and a init.py file:

import datetime
pyday = datetime.date(1991, 2, 20)
print("Python first appeared in this world on " + str(pyday))

We can call a function named choice from a module named random by using import random:

from random import choice
fruits = ["cherry", "mango", "pineapple"]
fruit = choice(fruits)
print("i random: " + fruit)

Classes are templates for objects of a particular kind. Self= my_car

class Car:
wheels = 4
def start_engine(self):
print("Vroom!")

my_car = Car()
my_car.start_engine()

class Car:
wheels = 4
def start_engine(self):
self.running = True
print("Vroom!")

my_car = Car()
my_car.start_engine()

Also we define a special method named init(self):

class Car:
wheels = 4
def init(self):
self.running = False
def start_engine(self):
self.running = True
print("Vroom!")

my_car = Car()

class Car:
wheels = 4
def init(self, color):
self.color = color
self.running = False
def start_engine(self):
self.running = True
print("Vroom!")

my_car = Car("red")
print(my_car.color)

To make a object move from one answer to next type import time,os

Then time.sleep(1)

time.sleep(2)
os.system('clear')

Test Codes
name=input("what is your name:\n")
print(f"How are you doing {name}")
print("------------")
last_name=input("what is your last name:\n")
print(f"nice last name { name} {last_name}")

Tpassword=input("Enter your password:\n")
print("Please Reenter your password")
if password==input():
print("thank you")
else:
print("wrong please try again")

username=input("choose a username:\n")
print(f"Nice Username " + username)
password=input("choose a password:\n")
print(f"Cool Password "+username)
print("now enter your username")
if username==input():
print("👍")
else:
print("Please try again")
print("Please Enter your Password")
if password==input():
print("👍")
else:
print("Please try again")

username=input("choose a username:\n")
print(f"Nice Username " + username)
password=input("choose a password:\n")
print(f"Cool Password "+username)
print("now enter your username")
if username==input():
print("Enter password")
if password==input():
print("Logging in")
else:
print("Try again")
if password==input():
print("logging in")
else:
print("try again")

player_1=input("Choose a name player one:\n")
player_2 =input("Choose a name player two:\n")
score=0
current_round = 1
print("Game on!")
print(f"player 1: {player_1}")
print(f"player 2: {player_2}")
print("--------------------------")
print(f"Round {current_round}!")
question_1=input("What is 4 x 5 " + player_1)
if question_1=="20":
print("Correct")
one_score=score+1
else:
print("wrong answer")
question_2=input("what does one half + one half make "+player_2)
if question_2=="whole":
print("correct")
two_score=score+1
else:
print("wrong awnser")
question_3=input("how much does 5 go into 10 "+player_1)
if question_3=="2":
print("correct awnser")
one_score=score+1
else:
print("Wrong Awnser")

question_4=input("Which country do we live in "+ player_2)
if question_4=="canada":
print("correct awnser")
two_score=score+1
print("Game Over")
player_1_score=one_score
player_2_score=two_score
if player_1_score>player_2_score:
print(f"{player_1} wins with the score of{player_1_score}")
else:
print(f"{player_2} wins with the score of {player_2_score}")

Change Calculator
print("Change Calculator")
print("--------------------\n")

#Sum input

cost=input("What is the bill\n")
owe=input("How much money did you pay\n")
change=int(cost)-int(owe)

Sum total

if cost>owe:
print("You cannot afford item")
else:
print(f"Your change is ${change}")

if cost==owe:
print("You have no change")

print("------------------------")
print(f"cost:${cost}")
print(f"Change:${change}")
print("------------------------")
print("Created by Neutral Lite")

Calculator:

#Options
operations=input("Type the number of the name down below to calculate:\n"

"\n1. Add"
"\n2. Subtract"
"\n3. Divide"
"\n4. multiply\n")
#Add
if "1"==operations:
add=input("Enter your first number\n")
add_2=input("Now enter second number\n")
awnser_1=int(add) + int(add_2)
print(f"The answer is { awnser_1}")
else:
print("Choose a number")
print("------------------------")
#Subtract
if "2"==operations:
subtract=input("Enter your first number\n")
subtract_2=input("Now enter second number\n")
awnser_2=int(subtract) - int(subtract_2)
print(f"The answer is { awnser_2}")
print("---------------------")
#Division
if "3"==operations:
division=input("Enter your first number\n")
division_2=input("Now enter second number\n")
awnser_3=int(division) / int(division_2)
print(f"The answer is { awnser_3}")
else:
print("1,2,3,4")
print("------------------------")
#Multiply
if "4"==operations:
multiply=input("Enter your first number\n")
multiply_2=input("Enter your first number\n")
awnser_4=int(multiply) * int(multiply_2)
print(f"The answer is { awnser_4}")

Salary calculators

weeks=input("What is the total number hours you worked in a week\n")
per_hour=input("Ammount earned per hour\n")
weekly_salary=int(weeks)int(per_hour)
total_number_of_weeks_in_a_year=52
annual_salary=weekly_salary
total_number_of_weeks_in_a_year
print(f"Annual Salary: ${annual_salary}\n")

print(f"Weekly Salary: ${weekly_salary}\n")

monthly_salary=int(weeks)int(per_hour)52/12

print(f"Monthly Salary: ${monthly_salary}")

print("Created by Neutral Lite")

You are viewing a single comment. View All
[deleted]