Python Basics with Examples

This is my mini notebook from the crash course I watched on Programming with Mosh in preparation for my Python Assessment with WIT (Women in Technology). The tutorial was an introductory course and I found it very useful for newbies.



Print Function (prints the specified message to the screen)

#Your first Python program

print('Wemi Ibidun')


Variables (they are used to store data temporarily in a computer's memory)

Examples of Variables:

name = 'Wemi Ibidun' (String)
age = 20 (integer)
rating = 4.9 (float)
is_new_patient = True (Boolean)

#Question: We checked in a patient named John Smith. He is 20 years old and he is a new patient

name = 'John Smith'
age = 20
is_new_patient = True


Data Types (The categorization of data and also tells what particular operation can be performed on data)

Data Types: Numbers, String, List, Tuple, and Dictionary

Numbers: int, float, long & complex

Strings:  set/collection of characters represented as single or double quotes e.g Tade = 'boy'

Lists: items enclosed within square brackets and each item can be of different data types e.g [teni, 3, tade, 1]

Tuple: consists of values enclosed in parenthesis. They cannot be updated. It is read-only e.g ("teni","tade")

Dictionary: they work with keys and values. They are enclosed by {} e.g record = {'age': 18}


Getting Input (This is a function that is used to ask a user a question. It reads from the input, converts to a string, and returns it)

#Question: Ask for a person's name and favourite colour and print it

name = input ('What is your name?:')
print ('Hi'+ name)


Type Conversion (how to convert one data type to another)

#Question: Ask a person his weight in pounds. Convert the weight to kilograms and print it

weight_in-pounds = input ('What is your weight (in pounds)?:')
weight_in-kg = int(weight_in-pounds) * 0.453592
print ('You weigh'+ str(weight_in-kg) + 'kg')


If Statements (used to test if an expression is true or false)


#Question: Write a program to achieve the following:

if a buyer has good credit, they need to put down 10%
Otherwise,
they need to put down 20%
Print the down payment

#Solution

house_price = 1000000
good_down_payment = 0.1 * 1000000
bad_down_payment = 0.2 * 1000000

good_credit = False
if good_credit:
print('You need to put down 10%')
print('Your downpayment is ' + '$' + str(good_down_payment))
else:
print('You need to put down 20%')
print('Your downpayment is ' + '$' + str(bad_down_payment))


Logical Operators (They are used to combine two conditions)

There are different operators such as AND, OR, NOT

#Question: What will be printed when this program is run?

has_criminal_record = True
has_good_credit = False

if has_criminal_record and not has_good_credit:
    print("Eligible for loan")

#Here the output will be "Eligible for a loan"


Comparison Operators (They are used to compare a variable with a value)

There are different operators such as >, <, =, >=, <=, ==, !=

#Question: if name is less than 3 characters long, name must be at least 3 characters. if name is more than 50 characters long, name can be 50 characters. Otherwise, name looks good

name = input ("What is your name?")

if len(name) < 3:
    print("name must be at least 3 characters")
elif len(name) > 50:
    print("name can be a maximum of 50 characters")
else:
    print("name looks good")



While Loop (This is used to execute a block of code multiple times)

#break function is used to get out of a loop

#Question A: Print a number from 1 -5 using while loops

i = 1

While i <= 5:
    print(i)
    i = i + 1

print("done")


#Question B: Write a game program to start a car: We are building an engine for the game. Start to start, stop to stop, and quit to exit. If we type anything outside this, game will respond "I don't understand that".

#Solution

command = ""
started = False

while True: #command != "quit"
command = input("> ").lower()
if command == "start":
if started:
print("Car is already started")
else:
started = True
print("Car started...")
elif command == "stop":
if not started:
print("Car is already stopped")
else:
started = False
print("Car stopped")
elif command == "help":
print("""
start - to start the car
stop - to end the car
quit - to quit
""")
elif command == "quit":
break
else:
print("Sorry, I don't understand that")



For Loops (They are used to iterate over a collection e.g. We can use a for loop to iterate over each character in a string i.e. for each item in a string, list, tuples, etc...do....)

Range is used for creating a wide range of objects that we can iterate over
e.g 

#Question A: For item in range(10):
                    print(item)


#Output

0
1
2
3
4
5
6
7
8
9


#Question B: Write a program to calculate the total costs of all the items in a shopping cart

#Solution

prices = [10, 20, 30]

total = 0 #Initialization

for price in prices:
    total += price
print(total)

Nested for loop challenge

#Question: Write a program to output the following asterisk below using nested for loops
*****
**
*****
**
**


Method 1 (without nested loop)
numbers = [5,2,5,2,2]
for number in numbers:
print('x' * number)

Method 2 (with nested loop)

numbers = [5,2,5,2,2]
for number in numbers:
output = ''
for count in range(number):
output+='x'
print(output)


Lists (They are used to store multiple items in a single variable)

#Question: Write a program to find the largest number in a list

numbers = [3,6,2,8,4,10]
max = numbers[0]
for number in numbers:
if number > max:
max = number
print(number)

#What is a 2D List? Each item in that list is a list (e.g matrix)

matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

print(matrix[0,1]) = 2

#List Methods
e.g numbers = [5, 2, 1, 7, 4]

1. numbers.append(20)
#Output =  numbers = [5, 2, 1, 7, 4, 20] #Adds item at the end of a list

2. numbers.insert(0,2) #first number is the index you want to insert the number and second number is the number you want to add
#Output: numbers = [2, 5, 2, 1, 7, 4]

3. numbers.remove - works opposite asper numbers.insert but no need for index
number.remove(5) = [5, 2, 1, 7, 4]
#Output = [2, 1, 7, 4]

4.numbers.clear() - this removes all the items in a list. It doesn't take in any values
#Output = []

5.numbers.pop() - this removes the last item in a list. 
#Output = [5, 2, 1, 7]

6.numbers.index() - this identifies the first occurrence of item in a list. 
#print(numbers.index(5)) = 0 

# print(50 in numbers) - This will output a boolean number (False)

7.numbers.count(5) - this returns the number of occurrence of a number in a list. 
#print(numbers.count(5)) = 1

#None is an object that represents the absence of a value

8.numbers.sort() - this doesn't return any value but sorts items to be in place
numbers.sort()
print(numbers)

After sorting, we can sort the reverse order
numbers.reverse()

9.numbers.copy() - this can be used to get a copy of our list
numbers = [5, 2, 1, 7, 4]
numbers2 = numbers.copy()


#Question: Write a program to remove duplicates in a list
numbers = [2,2,4,6,3,4,6,1]
same_number = []
numbers = [2,2,4,6,3,4,6,1]
single_number = []


for number in numbers:
if number not in single_number:
single_number.append(number)
print(single_number)


Functions (They are used to place codes in a more manageable, neater, and reusable format. It's a container with a few lines of code that performs a specific task)

#Example

def greet_user():
    print("Hi there")

greet_user()



Parameters (These are placeholders for receiving information)

def greet_user(name):
print(f"Hi {name}")
print("How can I help you today?")

greet_user("John")

- Parameters are placeholders that we define in our function for receiving information
- Arguments are the information we supply to this function (the value we supply to a function)
 
#Question?
What is the difference between argument and parameters
- greet_user(name) - this is an argument
- (name) - this is a parameter


#We could also have multiple parameters:

Example:

def greet_user(first_name, last_name):
print(f"Hi {first_name} {last_name}")
print("How can I help you today?")

greet_user("Wemi", "Ibidun")



Keyword Arguments (They are used to determine the specific place we want our parameters to be placed. When we give these keywords, it allows our arguments to be placed where ever we like in our program. They help to improve the readability of our code)

def greet_user(first_name, last_name):
print(f"Hi {first_name} {last_name}")
print("How can I help you today?")

greet_user("Wemi", last_name = "Ibidun")

#Note: for the most part of your program, use positional arguments but if your program has a lot of values, use keywords argument to improve the quality of your code e.b calc_cost(total = 50, discount = 0.5)

ALWAYS USE POSITIONAL ARGUMENT FIRST, THEN KEYWORD ARGUMENT


Return Statement (This returns a value of our function)

def square(number):
return number * number


result = square(3)
print(result) or print(square(3)) 

#Note: If you don't have a return statement in your program, by default all functions in Python return None.

None is an object that represents the absence of a value
If you have to calculate something, to avoid the None being returned, add a return statement

Creating a Reusable Statement (This returns a value of our function)

def square(number):
return number * number


result = square(3)
print(result) or print(square(3)) 

#Note: If you don't have a return statement in your program, by default all functions in Python return None.

None is an object that represents the absence of a value
If you have to calculate something, to avoid the None being returned, add a return statement



That will be all for now from my introductory Python course. I hope you have learned one or two things from this piece. I did as well. Until next time, remember to stay positive

HAPPY CODING!!! ❤️