0% found this document useful (0 votes)
1 views

Introduction to Python

This document serves as an introduction to Python, covering its definition, advantages, and installation methods. It outlines Python basics such as variable types, printing methods, conditional statements, and user input handling. Additionally, it provides resources for further learning and homework questions to practice Python skills.

Uploaded by

Kapaw Say
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Introduction to Python

This document serves as an introduction to Python, covering its definition, advantages, and installation methods. It outlines Python basics such as variable types, printing methods, conditional statements, and user input handling. Additionally, it provides resources for further learning and homework questions to practice Python skills.

Uploaded by

Kapaw Say
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Introduction

to Python
2

Agenda

❏ What is Python? Why Python? How to use it?


❏ Python basics
❏ Lists
❏ Tuples
❏ Dictionary and sets
❏ Functions
❏ Classes
❏ Try-Catch exception
3

What is Python? Why Python? How to use it?

Python is an interpreted, object-oriented, high-level


programming language with dynamic semantics.

Its high-level built-in data structures, make it very attractive


for Rapid Application Development, as well as for use as a
scripting or glue language to connect existing components
together.
4

Why Python?

● Readability and Maintainability


● It supports Multiple Programming Paradigms
● Compatibility with Major Platforms and Systems
● Robust Standard Library
● Versatility
5

How to use it?

Firstly, you need to have a Python interpreter installed on your computer.

To download, follow https://www.python.org/downloads/ which will provide a


button to download an installer for your particular system.

The Python documentation also has a detailed guide on how to install and setup
Python here: https://docs.python.org/3/using/index.html

Or you can download Anaconda and coding:


https://www.anaconda.com/download

Or you can use Google collab for easy approach:

https://colab.research.google.com/
6

How to use it?

If you install either Python interpreter or Anaconda on your computer, you may
also want to install an IDE (Integrated development environment) software on
your computer.

IDE makes it easier for you to build, edit, or debug your Python code.

One of the most popular IDE used is Visual Studio Code (VSCode):
https://code.visualstudio.com/download

Alternatively, you can also try out JupyterLab:


https://jupyter.org/install
7

What do you need to do?

1 Listen and be interactive


2 Install Python interpreter or Anaconda
3 Install either VSCode or Jupyter Notebook IDE
4 Open your preferred IDE and go to File > Open Folder… to select your
coding workspace
5 Create .ipynb file and try out the simple code shown to get the most
out of it
6 Ask questions if you have any doubt…
8

Python Basics

Assigning variables

By convention, variable names start with a lowercase letter.

# is used to keep the comments


x = 3
y = 4
# print(x+y) also works
x+y

Output: 7
9

Variable types

In Python, there are four primitive data type: Integer, Float, Boolean, and
String

x = 3 # integer Output:
y = 4.5 # float
z = “Hello” # string <class 'int'>
w = True # boolean
<class 'float'>
print(type(x))
print(type(y)) <class 'str'>
print(type(z))
print(type(w)) <class 'bool'>
10

a, b, c = 1, 2, 3 # multiple assignments
print(a) # output: 1
print(a+b-c) # output: 0

a, b = “Hello ”, “World”
print(a+b) # output: “Hello World”

# Constants are variables that you DO NOT want to


change the value #by convention/practice, we like to
assign constant UPPERCASE
PI = 3.14
11

Various ways to print

These are some basic ways to print:

x = 3
print(x)
print("hello world")
print("hello world:", x) #comma way
print("hello world: ", x, x, x, x, x, x, x, x, x, "hello again")

Output:
3
hello world
hello world, 3
hello world: 3 3 3 3 3 3 3 3 3 hello again
Another interesting way to print called f-string 12

What it is exactly?

f-strings, also known as formatted Literal String Interpolation, were introduced in Python 3.6

It is a feature in some programming languages that allows you to embed expressions within string
literals, using a special syntax:

name = “Parun”

age = 24

print(f"Hello, My name is {name} and I'm {age} years old."

Output: Hello, My name is Parun and I’m 24 years old.

Use f-string to control how many decimals:

PI = 3.14159

print(f"The value of Pi is: {PI:.2f}")

Output: The value of Pi is: 3.14


13

# I want to print double quotes as a string

print("He said, \"Nice weather today\"")

#this action of slashing is called "escaping characters“

Output: He said, "Nice weather today"

Source: https://www.w3schools.com/python/ref_func_print.asp
14

Booleans

print("True and False: ", True and False) print("True or False: ", True or False)

print("True and True: ", True and True) print("True or True: ", True or True)

print("False and True: ", False and True) print("False or True: ", False or True)

print("False and False: ", False and False) print("False or False: ", False or False)

Output: Output:

True and False: False ???


True and True: True
False and True: False
False and False: False
15

If… Elif… Else… and Logical Operators

Python supports the usual logical conditions from mathematics:


● Equals: a == b
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b

An If statement relies on these conditions to determine whether or not a piece of code


should be executed or not:
Caution!!!
a = 10
Python relies on indentation (whitespace
b = 5
at the beginning of a line) to define the
if a > b:
scope of the code.
# Use the Tab key to indent code
Other programming languages often use
print(“a is greater than b”)
curly brackets for this purpose.
Output: a is greater than b

What if we assign a = 2 and b = 3 instead? What will be the output?


16
In addition to if…, elif and else are used to execute alternate code when the if condition was
not true:

a = 10
b = 10
if a > b:
print(“a is greater than b”)
elif a == b:
print(“a and b are equal”)
else:
print(“b is greater than a”)

# Output: a and b are equal

You can also use and or or logical operators to check multiple conditions simultaneously:

today = “Saturday”
weather = “Sunny”
if (today == “Saturday”) and (weather != “Rainy”):
print(“Let’s go outside!”)
else:
print(“Staying home again today…”)

# Output: Let’s go outside!


17

=== Quick Quiz ===


Time: 2 Minutes
Do the following steps:
1 Define x = 3, y = 4, z = 5
2 Use the If... Elif… Else… statements to print out the largest number
among the three variables
3 Experiment with different values for x, y, z to make sure that the code
is correct
18

Solution #1:

x, y, z = 3, 4, 5

if (x >= y) and (x >= z):


largest = x
elif (y >= x) and (y >= z):
largest = y
else:
largest = z

print(“The largest number is:”, largest)

Is there another way to find the largest number among three?


19

Solution #2:

x, y, z = 3, 4, 5

if x >= y:
if x >= z:
largest = x
else:
largest = z
elif y >= z:
largest = y
else:
largest = z

print(“The largest number is:”, largest)

Using nested if… else…, to compare x with z,


when x is greater than or equal to y
20

Arithmetic operations

3 + 3 # = 6
3 / 3 # = 1.0
3 // 3 # = 1

Did you notice something?

/ operator is used for floating-point division


// operator is known as the floor division operator.

If you want to perform integer division, where the result is an


integer, you can use this:

# modulo or mod (remainder)


5 % 3 # = 2
# 5 squared
5 ** 2 # = 25
# 5 cubed
5 ** 3 # = 125
Importing libraries 21

You may want to exactly use some libraries to solve some specific problems.
For example, a library called math provides access to extra mathematical functions:

import math
a = math.cos(2 * math.pi)
b = math.sqrt(25)
print(a)
print(b)

Output:
1.0
5.0

Another way:

# * means everything in the library


from math import *
sqrt(25) # = 5.0

Another way:

# use ‘as’ to give the library a nickname


import math as m
m.sqrt(25) # = 5.0
22
User Input

We can also receive user input as value to be used in our program:

name = input("Please give me your name:")


print(“Your name is:”, name)

A prompt will appear after executing this code.


After the user entered their name, it gets printed on the screen.

Try this code…

num = input("Give me a random number:")


print(“I will add this number with 10”)
new_num = num + 10
print(new_num)

What is the result you get?


23

Didnʼt work??? Why is that?

Answer: Because the input() method receives user input as a string, and string can not be added
directly with an integer value.

To solve this problem, a type conversion is needed.

Type Conversion
num = input("Give me a random number:")
● int(x) converts x to integer print(“I will add this number with 10”)
● float(x) converts x to float # Here we convert num to integer type
● str(x) converts x to string new_num = int(num) + 10
● bool(x) converts x to boolean print(new_num)

Try…

x = True
int_x = int(x)
print(int_x)

Output: ???
24

While Statement

while ⟹ as long as the condition is met, keep doing it

pwd = input(“Enter password:”)


correct_pwd = “Hello world”

while pwd != correct_pwd: # as long as the password is incorrect


# keep on doing this until it is correct
print("Wrong password! Try again")
pwd = input(“Enter password:”)
print("Correct password")

Just like the If… Else… Statement, make sure your code is indented properly.
25

=== Homework Questions ===


1. Get input from user using input(). If the number is less than 5, print "less than".
Otherwise, print "higher than". Note: input() always returns as string

2. Write a simple number guessing game.The program generates a random integer


between 1 to 100 (both included). It then accepts input from users as an integer.
After the user input, the system outputs one of the three possible states whether
the number is higher, lower or equal to the target integer. If it is wrong, it will keep
asking users for input. Feel free to make any assumption for anything not stated.
Note: Look up random.randint() method
26

Resources:

https://www.programiz.com/python-programming/first-program
https://wiki.python.org/moin/BeginnersGuide
https://www.geeksforgeeks.org/python-programming-language/
27

Any doubts?
Contact me via Line or
[email protected]

You might also like