Python-Lec-1
Python-Lec-1
https://peps.python.org/pep-0020
Reasons to learn Python
1. Simplicity
…………………………………..
Application Areas
Getting started
Finding an Interpreter
Before we start Python programming, we need to have an
interpreter to interpret and run our programs.
• There are many interpreters available freely to run
Python scripts like IDLE (Integrated Development
Environment) that comes bundled with the Python
software downloaded from http://python.org.
Examples: Spyder, Pycharm, Jupyter Notebook, etc.
• Online interpreters like https://ide.geeksforgeeks.org
that can be used to run Python programs without
installing an interpreter.
• Anaconda (https://www.anaconda.com) – a distribution
of the Python and R programming languages for
scientific computing, that aims to simplify package
management and deployment.
Visual Studio Code (VS Code)
print(“Hello World")
Fundamentals of Python
Python Comments
Comments are useful information that the developers
provide to make the reader understand the source code.
It explains the logic or a part of it used in the code. There
are two types of comment in Python:
• Single line comments: Python single line comment
starts with hashtag symbol with no white spaces.
# This is Comment
Fundamentals of Python
Python Comments
Comments are useful information that the developers
provide to make the reader understand the source code.
It explains the logic or a part of it used in the code. There
are two types of comment in Python:
• Multi-line string as comment:
Python multi-line comment is a piece of text enclosed in
“””a delimiter (“””) on each end of the comment.
This would be a multiline comment
in Python that
spans several lines,
Hanji
“””
Fundamentals of Python
Built-in types
There are many kinds of information that a computer can
process, like numbers and characters. In Python (and
other programming languages), the kinds of information
the language is able to handle are known as types. Many
common types are built into Python – for example
integers, floating-point numbers and strings.
Fundamentals of Python
Built-in types
There are many kinds of information that a computer can
process, like numbers and characters. In Python (and
other programming languages), the kinds of information
the language is able to handle are known as types. Many
common types are built into Python – for example
integers, floating-point numbers and strings.
Integers
An integer (int type) is a whole number such as 1, 5, 1350
or -34.
1.5 is not an integer because it has a decimal point.
Numbers with decimal points are floating-point numbers.
Even 1.0 is a floating-point number and not an integer.
Fundamentals of Python
Built-in types
There are many kinds of information that a computer can
process, like numbers and characters. In Python (and
other programming languages), the kinds of information
the language is able to handle are known as types. Many
common types are built into Python – for example
integers, floating-point numbers and strings.
Floating-point numbers
Floating-point numbers (float type) are numbers with a
decimal point or an exponent (or both). Examples are 5.0,
10.24, 0.0, 12. and .3
Fundamentals of Python
Built-in types
There are many kinds of information that a computer can
process, like numbers and characters. In Python (and
other programming languages), the kinds of information
the language is able to handle are known as types. Many
common types are built into Python – for example
integers, floating-point numbers and strings.
Strings
A string (type str) is a sequence of characters.
Strings in python are surrounded by either single
quotation marks, or double quotation marks.
print("Hello")
print('Hello')
Fundamentals of Python
Exercise
Which of the following numbers are valid Python integers?
110, 1.0, 17.5, -39, -2.3, “-1”, 11.0
Fundamentals of Python
Variables
Variable is a label for a location in memory.
It can be used to hold a value.
To define a new variable in Python, we simply assign a
value to a label. For example, this is how we create a
variable called count, which contains an integer value of
zero:
# define variable count
count = 0
Fundamentals of Python
Variables
Variable is a label for a location in memory.
It can be used to hold a value.
To define a new variable in Python, we simply assign a
value to a label. For example, this is how we create a
variable called count, which contains an integer value of
zero:
# define variable count
count = 0
# redefine variable count
count = 2
Fundamentals of Python
Variables
Variable is a label for a location in memory.
It can be used to hold a value.
Python has some rules that you must follow when forming
an identifier:
• it may only contain letters (uppercase or lowercase),
numbers or the underscore character (_) (no spaces!).
• it may not start with a number.
• it may not be a keyword.
Fundamentals of Python
Variables
Variables in Python are not “statically typed”. We do not
need to declare variables before using them or declare
their type. A variable is created the moment we first
assign a value
# An integer to it.
assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
print(age)
print(salary)
print(name)
Fundamentals of Python
Operators
Operators are the main building block of any
programming language. Operators allow the programmer
to perform different kinds of operations on operands.
These operators can be categorized based upon their
different functionality.
Fundamentals of Python
# Examples of Arithmetic Operator
a=9
Operators b=4
• Arithmetic operators: # Addition of numbers
Arithmetic operators are add = a + b
# Subtraction of numbers
used to perform sub = a - b
mathematical operations # Multiplication of number
like addition, subtraction, mul = a * b
# Division(float) of number
multiplication and division. div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulus (remainder)
mod = a % b
# Exponent (power)
pwr = a ** b
Fundamentals of Python
# Examples of Arithmetic Operator
a=9
Operators b=4
• Arithmetic operators # Addition of numbers
Operator precedence add = a + b
• Python has a specific and predictable # Subtraction of numbers
way to determine the order in which it sub = a - b
performs operations. For integer # Multiplication of number
operations, the system will first handle mul = a * b
brackets (), then **, then *, // and %, # Division(float) of number
and finally + and -. div1 = a / b
# Division(floor) of number
• If an expression contains multiple div2 = a // b
operations which are at the same level # Modulus (remainder)
of precedence, like *, // and %, they mod = a % b
will be performed in order, either from # Exponent (power)
left to right (for left-associative pwr = a ** b
operators) or from right to left (for
right-associative operators).
All these arithmetic operators are left-
associative, except for **, which is
right-associative.
Fundamentals of Python
# Examples of Relational Operators
a = 13
Operators b = 33
# Print a or b is True
print(a or b)
if university == ‘CU’:
print(‘Hi, CU student!')
else:
print(‘The university is not CU')
print('All set !')
Fundamentals of Python
Selection
Selection in Python is made using the two keywords ‘if’
and ‘elif’ and else (elseif)
# Python program to illustrate
# selection statement
mark = 34
if mark >= 80:
print(“Grade is A”)
elif mark >= 65:
print(“Grade is B”)
elif mark >= 50:
print(“Grade is C”)
else:
print(“Grade is D”)
Fundamentals of Python
Selection
Selection in Python is made using the two keywords ‘if’
and ‘elif’ and else (elseif)
# Python program to illustrate
# selection statement
mark = 34
if mark >= 80:
print(“Grade is A”)
elif mark >= 65:
print(“Grade is B”)
else:
if mark >= 50:
print(“Grade is C”)
else:
print(“Grade is D”)
Fundamentals of Python
Selection
Selection in Python is made using the two keywords ‘if’
and ‘elif’ and else (elseif)
# Python program to illustrate
# selection statement
mark = 34
if mark >= 80:
print(“Grade is A”)
elif mark >= 65:
print(“Grade is B”)
else:
if mark >= 50:
print(“Grade is C”)
else:
print(“Grade is D”)
Recommended Books and Materials
3.https://www. w3schools.com
Let’s Calculate for basic arithmetic operations
Perimeter of a half-circle: +
Let’s Calculate using Python..in a ways
def test1():
pi=3.14
r=float(input("enter the value: "))
area=pi*r*r
print("your area of a circle is:",area)
test1()
import math
def test2():
r=float(input("Enter the second valus of radius: "))
circum=math.pi*2*r
print("The circumference of a circle is:",circum)
test2()
Let’s Calculate using Python..in a ways
def myfunc():
x = "awesome" x = "fantastic"
print("Python is " + x)
def myfunc():
print("Python is " + x) myfunc()
def myfunc(): Also, use the global keyword if you want to change
global x a global variable inside a function.
x = "fantastic"
x = "awesome"
myfunc()
def myfunc():
print("Python is " + x) global x
x = "fantastic"
myfunc()
print("Python is " + x)
Python Numbers, Type Conversion
You can convert from one type to another with
the int(), float(), and complex() methods:
There are three
x = 1 # int
numeric types in y = 2.8 # float
Python: z = 1j # complex
• int #convert from int to float:
a = float(x)
• float
• complex #convert from float to int:
b = int(y)
import random
print(random.randrange(1, 10))
Python Strings
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
You can assign a multiline string to a variable by using three quotes ””” Or
three single quotes ’’’
a = """Lorem ipsum dolor sit
amet,
consectetur adipiscing elit,
Python does not have a character data type, a
sed do eiusmod tempor incididunt
single character is simply a string with a length
ut labore et dolore magna
of 1.
aliqua."""
Square brackets can be used to access elements
print(a)
of the string.
b = '''Lorem ipsum dolor sit
amet,
consectetur adipiscing elit, a = "Hello, World!"
sed do eiusmod tempor incididunt print(a[1])
ut labore et dolore magna
Strings
we can loop through the characters in a for x in "banana":
string, with a for loop. print(x)
By leaving out the start index, the range will b = "Hello, World!"
start at the first character: print(b[:5])
By leaving out the end index, the range will b = "Hello, World!"
go to the end: print(b[2:])
The strip() method removes any whitespace a = " Hello, World! "
from the beginning or the end: print(a.strip())
a = "Hello"
To add a space between them, add a " ": b = "World"
c = a + " " + b
print(c)
Python: Format Strings
we cannot combine strings and numbers.
But we can combine strings and numbers by using f-strings or
the format() method!
To specify a string as an f-string, simply put an f in front of the string literal and
add curly brackets {} as placeholders for variables and other operations.
age = 36
txt = f"My name is John, I am {age}"
print(txt)
# Sample Output
# Enter your first name: James
# Enter your last name: Bond
# Output: Hello, Agent Bond James!
# Sample Output
# Favorite food: Pizza
# Lucky number: 7
# Output: Your password is: 🍔Pizza#7!
Let’s have some fun exercise
🤯 3. "Mind Reader"
Problem:
Ask the user to enter a sentence. Show the first word, last word, and the number of words in
the sentence.
# Input:
# Enter your favorite color: Blue
# Enter your favorite animal: Dragon
reversed_name = name[::-1]
ghost_name = f"{reversed_name}👻{reversed_name}👻{reversed_name}"
def myFunction() :
return True
You can execute code based on the
Boolean answer of a function: if myFunction():
print("YES!")
else:
print("NO!")
Python also has many built-in functions
that return a boolean value, like
the isinstance() function, which can be x = 200
used to determine if an object is of a print(isinstance(x, int
certain data type: ))
Python Operators
Tasks:
Tasks:
•Add a "Yellow" sock to the list.
•Remove one "Red" sock from the list.
•Check if "Pink" sock is in the list. Print a happy face if yes, sad face if no.
•Print out all socks one by one with the message:
"Found a [Color] sock!"
🥉 3. Magical Number Game
Let's have some funny You are a wizard and you have a list of magic
numbers:
magic_numbers = [2, 5, 8, 11, 14, 17, 20]
Tasks:
•Print only the numbers which are divisible by 2.
problem!
# Add laundry
messy_items.append("laundry")