0% found this document useful (0 votes)
6 views29 pages

Python Programming Basics Guide

Uploaded by

sofiahmedneglur
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views29 pages

Python Programming Basics Guide

Uploaded by

sofiahmedneglur
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 1

Basics of Python
programming
Topics include
• Python Basics
• Flow Control
• Functions
Operators you can use in Python expressions,

Order Operator Operation Example Evaluates To..

1 ** Exponent 2 ** 3 8
2 % Modulus/ remainder 22 % 8 6

3 // Integer division/ Floored 22 // 8 2


quotient

4 / Division 22 / 8 2.75
5 * Mulitplication 3*5 15
6 - Subtraction 5-2 3
7 + Addition 2+2 4
Chapter-1: Python Basics

The order of operations (also called precedence) of Python math operators is similar
to that of mathematics.
• 2+3*6
• (2 + 3) * 6
• 48565878 * 578453
• 2 ** 8
• 23 // 7
• 23 % 7
• 2 + 2
• (5 - 1) * ((7 + 1) / (3 - 1))

Python will keep evaluating parts of the expression until it becomes a single value.
The Integer, Floating-Point, and String Data Types
A data type is a category for values, and every value belongs to exactly one data type.

Data type Examples


Integers -2, -1, 0, 1, 2, 3, 4, 5
Floating-point numbers -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25
Strings 'a', 'aa', 'aaa', 'Hello!', '11 cats'

Python programs can also have text values called strings, or strs (pronounced
“stirs”). Always surround your string in single quote (') characters (as in 'Hello' or 'Goodbye
cruel world!') so Python knows where the string begins and ends. You can even have a string
with no characters in it, ‘’, called a blank string.
String Concatenation and Replication
In Python, you can manipulate strings using concatenation and replication. These operations allow you to
combine strings or create multiple copies of a string.
String Concatenation: It is the process of combining two or more strings together to create a
new string. In Python, you can use the + operator to concatenate strings.
str1 = "Hello, "
str2 = "world!"
result = str1 + str2
print(result) # Output: Hello, world!
String replication: involves creating multiple copies of a string by repeating it a certain number
of times. You can use the * operator for string replication.

original = "ABC"
replicated = original * 3
print(replicated) # Output: ABCABCABC
Storing Values in Variables
• A variable is like a box in the computer’s memory where you can store a single value.
• If you want to use the result of an evaluated expression later in your program, you can save it
inside a variable.
Assignment Statements:
• You’ll store values in variables with an assignment statement. An assignment statement consists
of a variable name, an equal sign( = ) (called the assignment operator), and the value to be
stored.
• If you enter the assignment statement
spam = 42, then a variable named spam will have the integer value 42 stored in it.
• When a variable is assigned a new value, the old value is forgotten, which is why spam evaluated
to 42 instead of 40 at the end of the example. This is called overwriting the variable.
>>>spam = 'Hello'
>>> spam
'Hello' The spam variable in this example stores 'Hello' until you
>>> spam = 'Goodbye' replace it with 'Goodbye’.
>>> spam
'Goodbye'
Variable Names:
You can name a variable anything as long as it obeys the following three rules:
1. It can be only one word.
2. It can use only letters, numbers, and the underscore (_) character.
3. It can’t begin with a number.

Valid variable names Invalid variable names


balance current-balance (hyphens are not allowed)
currentBalance current balance (spaces are not allowed)
current_balance 4account (can’t begin with a number)
_spam 42 (can’t begin with a number)
SPAM total_$um (special characters like $ are not
allowed)
account4 'hello' (special characters like ' are not
allowed)

Variable names are case-sensitive, meaning that spam, SPAM, Spam, and sPaM are four different
variables. It is a Python convention to start your variables with a lowercase letter.
Your First Program
print('Hello world!')
print('What is your name?')
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
print('What is your age?')
myAge = input()
print('You will be
Dissecting the Program
Comments: Python ignores comments, and you can use them to write notes or remind yourself what the code is trying to do.
Any text for the rest of the line following a hash mark (#) is part of a comment.
Ex: print('What is your name?') # ask for their name
The print() function: The print() function displays the string value inside the parentheses on the screen.
Ex: print('Hello world!')
print('What is your name?') # ask for their name
The input() function: The input() function waits for the user to type some text on the keyboard and press ENTER.
Ex: myName = input()
Printing the user’s name: The following call to print() actually contains the expression 'It is good to meet you, ' + myName
between the parentheses.
Ex: print('It is good to meet you, ' + myName)
The len() function: You can pass the len() function a string value (or a variable containing a string), and the function
evaluates to the integer value of the number of characters in that string.
Ex: print('The length of your name is:')
print(len(myName))
The str(), int() and float() functions: If you want to concatenate an integer such as 29 with a string to pass to print(), you’ll
need to get the value '29', which is the string form of 29. The str() function can be passed an integer value and will evaluate to
a string value version of it, as follows:
Ex: >>> str(29) The str(), int(), and float() functions will evaluate to the string,
'29’ integer, and floating-point forms of the value you pass,
>>> print('I am ' + str(29) + ' years old.’) respectively
I am 29 years old.
FLOW CONTROL
Flow control in Python refers to the mechanisms and constructs that allow you to control the
order in which your code is executed based on conditions and loops. Python provides several flow
control structures, including if statements, loops, and function calls, which enable you to create more
dynamic and responsive programs

Boolean Values:
• While the integer, floating-point, and string data types have an unlimited number of possible values,
the Boolean data type has only two values: True and False.
• When typed as Python code, the Boolean values True and False lack the quotes you place around
strings, and they always start with a capital T or F, with the rest of the word in lowercase.
is_sunny = False
has_umbrella = True

if is_sunny and not has_umbrella:


print("Enjoy the sunny day!")
elif not is_sunny and has_umbrella:
print("Stay dry with your umbrella!")
else:
print("Weather conditions are mixed.")
Comparison Operators:
Boolean values are often used in comparison operations to evaluate whether a certain condition is true or false.
Comparison operators include:
== (equal to) 1. x = 5
!= (not equal to) y = 10
< (less than) result = x == y # False
> (greater than)
<= (less than or equal to) 2. age = 25
>= (greater than or equal to) is_teenager = age != 20 # True/

[Link] = 28 4. score = 85
is_cool = temperature < 30 # True is_high_score = score > 90 # False

5. count = 100 6. quantity = 15


is_small_count = count <= 50 # False is_sufficient = quantity >= 10 # True

Difference between == and = Operators


The == operator (equal to) asks whether two values are the same as each other.
The = operator (assignment) puts the value on the right into the variable on the left.
Boolean Operators
• The three Boolean operators (and, or, and not) are used to compare Boolean values.
• Like comparison operators, they evaluate these expressions down to a Boolean value. Let’s explore
these operators in detail, starting with the and operator.
• Binary Boolean Operator: The and or or operators always take two Boolean values (or expressions), so
they’re considered binary operators.
• The and operator evaluates an expression to True if both Boolean values are True; otherwise, it
evaluates to False.
The and Operator’s Truth Table The or Operator’s Truth Table
Expression Evaluates to… Expression Evaluates to…
True and True True True or True True
True and False False True or False True
False and True False False or True True
False and False False False or False False

The not Operator’s Truth Table


Expression Evaluates to…
not True False
not False True
Mixing Boolean and Comparison Operators:
• Since the comparison operators evaluate to Boolean values, you can use them in expressions
with the Boolean operators.
• Recall that the and, or, and not operators are called Boolean operators because they always
operate on the Boolean values True and False.
• While expressions like 4 < 5 aren’t Boolean values, they are expressions that evaluate down to
Boolean values. Try entering some Boolean expressions that use comparison operators into the
interactive shell
>>> (4 < 5) and (5 < 6) (4 < 5) and (5 < 6)
True
>>> (4 < 5) and (9 < 6) True and (5 < 6)
False
>>> (1 == 2) or (2 == 2) True and True
True
True
• The computer will evaluate the left expression first, and then it will evaluate the right
expression.
• When it knows the Boolean value for each, it will then evaluate the whole expression
down to one Boolean value.
• You can think of the computer’s evaluation process for (4 < 5) and (5 < 6) as shown
in Figure.
Elements of Flow Control
• Flow control statements often start with a part called the condition, and all are followed by a block of
code called the clause.
• Conditions: The Boolean expressions you’ve seen so far could all be considered conditions, which are
the same thing as expressions; condition is just a more specific name in the context of flow control
statements.
• Conditions always evaluate down to a Boolean value, True or False.
• A flow control statement decides what to do based on whether its condition is True or False, and
almost every flow control statement uses a condition.
• Blocks of Code: Lines of Python code can be grouped together in blocks.
• You can tell when a block begins and ends from the indentation of the lines of code. There are three
rules for blocks.
1. Blocks begin when the indentation increases.
2. Blocks can contain other blocks.
3. Blocks end when the indentation decreases to zero or to a containing block’s indentation.
Flow Control of Statements
if Statements:
▪ The most common type of flow control statement is the if statement.
▪ An if statement’s clause (that is, the block following the if statement) will execute if the
statement’s condition is True. The clause is skipped if the condition is False.
▪ In Python, an if statement consists of the following:
1. The if keyword
2. A condition (that is, an expression that evaluates to True or False)
3. A colon
4. Starting on the next line, an indented block of code (called the if clause)
Ex: if name == 'Alice’:
print('Hi, Alice.')
else Statements:
• An if clause can optionally be followed by an else statement. The else clause is executed only when
the if statement’s condition is False.
• An else statement doesn’t have a condition, and in code, an else statement always consists of the
following:
1. The else keyword
2. A colon
3. Starting on the next line, an indented block of code (called the else clause)

Ex:
if name == 'Alice':
print('Hi, Alice.’)
else:
print('Hello, stranger.')
• While only one of the if or else clauses will execute, you may have a case where you want one
of many possible clauses to execute.
• The elif statement is an “else if” statement that always follows an if or another elif statement.
• It provides another condition that is checked only if any of the previous conditions were False.
• In code, an elif statement always consists of the following:
1. The elif keyword
2. A condition (that is, an expression that evaluates to True or False)
3. A colon
4. Starting on the next line, an indented block of code (called the elif clause)
while loop Statements
• You can make a block of code execute over and over again with a while statement.
• The code in a while clause will be executed as long as the while statement’s condition is True.
• In code, a while statement always consists of the following:
1. The while keyword
2. A condition (that is, an expression that evaluates to True or False)
3. A colon
4. Starting on the next line, an indented block of code (called the while clause)
• while statement looks similar to an if statement. The difference is in how they behave.
• At the end of an if clause, the program execution continues after the if statement. But at the end of a
while clause, the program execution jumps back to the start of the while statement.
• The while clause is often called the while loop or just the loop.
• Let’s look at an if statement and a while loop that use the same condition and take the same actions
based on that condition.
Ex: Ex:
spam = 0 spam = 0
if spam < 5: while spam < 5:
print('Hello, world.') print('Hello, world.')
spam = spam + 1 spam = spam + 1
The flowchart for the while statement code
An Annoying while loop
• An "annoying" while loop typically refers to a loop that keeps executing its code block repeatedly as long
as a certain condition is true.
• In programming, a while loop is a control structure that repeatedly executes a block of code as long as a
specified condition remains true.
Ex:
name = ‘ '
while name != 'your name':
print('Please type your name.')
name = input()
print('Thank you!')
OUTPUT:
Please type your name.
Al
Please type your name.
Albert
Please type your name.
%#@#%*(^&!!!
Please type your name.
your name If you never enter your name, then the while loop’s condition will never be
Thank you! False, and the program will just keep asking forever.
Break Statements:
• There is a shortcut to getting the program execution to break out of a while loop’s clause early.
• If the execution reaches a break statement, it immediately exits the while loop’s clause. In code, a break
statement simply contains the break keyword.
• Here’s a program that does the same thing as the previous program, but it uses a break statement to
escape the loop.
Ex:
while True:
print('Please type your name.')
name = input()
if name == 'your name':
break
print('Thank you!')
Continue statement
• Like break statements, continue statements are used inside loops.
• When the program execution reaches a continue statement, the program execution immediately jumps back to the
start of the loop and reevaluates the loop’s condition. (This is also what happens when the execution reaches the
end of the loop.)
• Let’s use continue to write a program that asks for a name and password.
Ex:
while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('Access granted.')
For loops and range() functions
• The while loop keeps looping while its condition is True (which is the reason for its name), but what if you
want to execute a block of code only a certain number of times. we use a for loop statement and the range()
function.
• In code, a for statement looks something like for i in range(5): and always includes the following:
• The for keyword
• A variable name
• The in keyword
• A call to the range() method with up to three integers passed to it
• A colon
• Starting on the next line, an indented block of code (called the for clause)
Ex:
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
OUTPUT:
My name is
Jimmy Five Times (0)
Jimmy Five Times (1)
Jimmy Five Times (2)
Jimmy Five Times (3)
Jimmy Five Times (4)
The Starting, Stopping, and Arguments to range():
• Some functions can be called with multiple arguments separated by a comma, and range()
is one of them.
• This lets you change the integer passed to range() to follow any sequence of integers,
including starting at a number other than zero.
for i in range(12, 16):
print(i)
The first argument will be where the for loop’s variable starts, and the second argument will be up to,
but not including, the number to stop at.
12
13
14
15
• The range() function can also be called with three arguments. The first two arguments will be the start and stop
values, and the third will be the step argument. The step is the amount that the variable is increased by after
each iteration

for i in range(0, 10, 2):


print(i)
Cont…

• The range() function is flexible in the sequence of numbers it produces for loops. you can even use a
negative number for the step argument to make the for loop count down instead of up.

for i in range(5, -1, -1):


print(i)

Running a for loop to print i with range(5, -1, -1) should print from five down to zero.
5
4
3
2
1
0
Importing Modules
• All Python programs can call a basic set of functions called built-in functions, including the print(),
input(), and len() functions you’ve seen before.
• Python also comes with a set of modules called the standard library.
• Each module is a Python program that contains a related group of functions that can be embedded in
your programs.
• For example, the math module has mathematics related functions, the random module has random
number–related functions, and so on.
• Before you can use the functions in a module, you must import the module with an import statement.
In code, an import statement consists of the following:
• The import keyword
• The name of the module
• Optionally, more module names, as long as they are separated by commas.
• Once you import a module, you can use all the cool functions of that module.

import random OUTPUT:


for i in range(5): 4
print([Link](1, 10)) 1
8
which will give us access to the [Link]() function 4
1
• The [Link]() function call evaluates to a random integer value between the two integers that you
pass it.
• Since randint() is in the random module, you must first type random. in front of the function name to tell
Python to look for this function inside the random module.
• Here’s an example of an import statement that imports four different modules:

import random, sys, os, math

• An alternative form of the import statement is composed of the from keyword, followed by the module
name, the import keyword, and a star;
for example: from random import *.
• With this form of import statement, calls to functions in random will not need the random. prefix.
Ending a Program Early with [Link]()
• The last flow control concept to cover is how to terminate the program.
• This always happens if the program execution reaches the bottom of the instructions.
• However, you can cause the program to terminate, or exit, by calling the [Link]() function. Since this
function is in the sys module, you have to import sys before your program can use it.
Ex:
import sys

while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
[Link]()
print('You typed ' + response + '.')

This program has an infinite loop with no break statement


inside. The only way this program will end is if the user enters
exit, causing [Link]() to be called. When response is equal to
exit, the program ends.

You might also like