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

lower programming

The document provides an overview of Python programming, focusing on the print() function, input() function, and various arithmetic operators such as addition, subtraction, multiplication, and division. It also covers string manipulation, including concatenation, indexing, and membership tests, as well as basic control flow using if, else, and elif statements. Overall, it serves as a beginner's guide to fundamental Python concepts and operations.

Uploaded by

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

lower programming

The document provides an overview of Python programming, focusing on the print() function, input() function, and various arithmetic operators such as addition, subtraction, multiplication, and division. It also covers string manipulation, including concatenation, indexing, and membership tests, as well as basic control flow using if, else, and elif statements. Overall, it serves as a beginner's guide to fundamental Python concepts and operations.

Uploaded by

masunda
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Python

Definition and Usage

The print() function prints the specified message to the screen, or other standard output device.

The message can be a string, or any other object, the object will be converted into a string before
written to the screen.

Print more than one object:

print("Hello", "how are you?")

Print a tuple:

x = ("apple", "banana", "cherry")

print(x)

Print two messages, and specify the separator:

print("Hello", "how are you?", sep="---")

#how to print an integer

print(7)

#how to print a variable

#to just print the variable on its own include only the name of it

fave_language = "Python"

print(fave_language

How to print a variable and a string in Python using concatenation

fave_language = "Python"

print("I like coding in " + fave_language + " the most")

#output

#I like coding in Python the most

You can even add the spaces separately:


fave_language = "Python"

print("I like coding in" + " " + fave_language + " " + "the most")

#output

#I like coding in Python the most

How to print a variable and a string in Python by separating each with a comma

You can print text alongside a variable, separated by commas, in one print statement.

first_name = "John"

print("Hello",first_name)

#output

#Hello John

This method also works with more than one variable:

first_name = "John"

last_name = "Doe"

print("Hello",first_name,last_name,"good to see you")

#output

Hello John Doe good to see you

Make sure to separate everything with a comma.

So, you separate text from variables with a comma, but also variables from other variables, like shown
above.

input function

The input() function allows user input.

Ask for the user's name and print it:

print('Enter your name:')

x = input()
print('Hello, ' + x)

Use the prompt parameter to write a message before the input:

x = input('Enter your name:')

print('Hello, ' + x)

Example 2- Taking integer inputs from users. In such a case, we use int() to take the input with input().

x = int(input("Enter x:"))

print(type(x))

Why Do We Need the input Function?

The following points will explain the importance of the input() function:

It allows programmers to interact with users.

It is a method to read different inputs.

Many programs use a dialog box to collect inputs from users.

In Python programming, operators allow us to perform different operations on data and manipulate
them. We use operators for various reasons in programming, such as manipulating strings, assigning
values, performing calculations, working with data types, and comparing values.

Python includes many operators, such as Arithmetic operators, Comparison operators, Assignment
operators, Logical operators, Bitwise operators, and more.

What Is an Arithmetic Operator in Python?

Whenever we buy something at a store and have to pay a large amount, we calculate the total money to
be paid and the discount received on calculators. These calculations are run by operators such as add,
subtraction, multiplication, etc.

Similarly, Python coding also includes operators that make the job of developers easier and help them in
programming.

Addition: +

adds the two operands.


x+y

Subtraction: –

subtracts the second operand from the first operand.

x–y

Multiplication: *

multiplies two operands.

x*y

Division (float): /

divides the first operand by the second one.

x/y

Modulus: %

divides the first operand by the second one and returns the remainder.

x%y

Division (floor): //

divides the first operand by the second and finds the quotient without the remainder.

x // y

Power (Exponent): **

returns the first operand raised to the power of the second operand.

x ** y

Addition Operator (+)

The addition operator is also used to perform arithmetic operations in Python and is denoted by (+). It
adds the value of the two operands and returns the sum.

Example

x=2

y=4

print(x + y)
Output

Subtraction Operator (-)

Subtraction is one of the commonly used arithmetic operators in a Python program, which is denoted by
(-). It is used to perform subtraction, where it subtracts the second operand from the first one.

Example

x=2

y=4

print(x - y)

Output:

-2

Multiplication Operator (*)

The multiplication arithmetic operator is denoted by (*) in Python. It is used to multiply the first and
second operands and find the product of two values.

Example

x=2

y=4

print(x * y)

Output:

Division Operator (/)

The division operator is used to perform basic arithmetic operations in Python and is denoted by (/). It
divides the first operand by the second operand to find the quotient. It returns a float value even when
the result is a whole number.

Example
x=2

y=4

print(x / y)

Output:

0.5

Modulus Operator (%)

The modulus operator is denoted by (%) and divides one value by another value. It finds the remainder
by dividing the first operand by the second operand.

Example

x = 14

y=4

print(x % y)

Output:

Exponentiation Operator (**)

The exponentiation arithmetic operator in Python is denoted by (**). It performs exponentiation


operations on numerical data types, including floats, integers, and complex numbers. It raises the first
operand to the power of the second operand.

Example

logo

menu

About Us

Career Schools

Apply as Mentor

Contact Us
Login

Join for Free

Home

Icon

Resources

Icon

Python Tutorial | Learn Python Language

Icon

Python Arithmetic Operators: All Types With Example

Icon

Python Arithmetic Operators: All Types With Example

2 mins read

Last updated: 01 Feb 2025

2840 views

Icon Share

2.60%

Master Data Analytics Program

Table of Contents

Introduction

What Is an Arithmetic Operator in Python?

Types of Arithmetic Operators in Python


Precedence of Arithmetic Operators in Python

Introduction

In Python programming, operators allow us to perform different operations on data and manipulate
them. We use operators for various reasons in programming, such as manipulating strings, assigning
values, performing calculations, working with data types, and comparing values.

Python includes many operators, such as Arithmetic operators, Comparison operators, Assignment
operators, Logical operators, Bitwise operators, and more.

This blog will focus on arithmetic operators in Python, a mathematical function that performs
calculations on two operands. There are various arithmetic operators, such as addition, subtraction,
division, multiplication, modulus, exponentiation, and floor division.

What Is an Arithmetic Operator in Python?

Whenever we buy something at a store and have to pay a large amount, we calculate the total money to
be paid and the discount received on calculators. These calculations are run by operators such as add,
subtraction, multiplication, etc.

Similarly, Python coding also includes operators that make the job of developers easier and help them in
programming.

Undoubtedly, Python is one of the most sought-after programming languages and is preferred by many
programmers because of its versatility and adaptability. Moreover, its simple syntax adds to its
popularity. It is used in various domains and sectors of software development. Operators are crucial to
enhancing knowledge of Python programming and gaining proficiency in it.

We use operators to manipulate and process data in different ways. Arithmetic operators in Python
programming are used to perform basic mathematical calculations of two operands. They include
addition, subtraction, division, multiplication, and more.

Types of Arithmetic Operators in Python


We use Python arithmetic operators to perform different mathematical operations, including
subtraction, addition, multiplication, division, and more. Here are the arithmetic operators used in
Python:

Addition (+)

Subtraction (-)

Multiplication (*)

Division (/)

Modulus (%)

Floor Division (//)

Exponentiation (**)

Operator

Description

Syntax

Addition: +
adds the two operands.

x+y

Subtraction: –

subtracts the second operand from the first operand.

x–y

Multiplication: *

multiplies two operands.

x*y

Division (float): /

divides the first operand by the second one.

x/y

Modulus: %

divides the first operand by the second one and returns the remainder.
x%y

Division (floor): //

divides the first operand by the second and finds the quotient without the remainder.

x // y

Power (Exponent): **

returns the first operand raised to the power of the second operand.

x ** y

Let us discuss them in detail by taking examples:

1. Addition Operator (+)

The addition operator is also used to perform arithmetic operations in Python and is denoted by (+). It
adds the value of the two operands and returns the sum.

Example

x=2

y=4
print(x + y)

Output

2. Subtraction Operator (-)

Subtraction is one of the commonly used arithmetic operators in a Python program, which is denoted by
(-). It is used to perform subtraction, where it subtracts the second operand from the first one.

Example

x=2

y=4

print(x - y)

Output:

-2

3. Multiplication Operator (*)

The multiplication arithmetic operator is denoted by (*) in Python. It is used to multiply the first and
second operands and find the product of two values.

Example

x=2

y=4

print(x * y)

Output:
8

4. Division Operator (/)

The division operator is used to perform basic arithmetic operations in Python and is denoted by (/). It
divides the first operand by the second operand to find the quotient. It returns a float value even when
the result is a whole number.

Example

x=2

y=4

print(x / y)

Output:

0.5

5. Modulus Operator (%)

The modulus operator is denoted by (%) and divides one value by another value. It finds the remainder
by dividing the first operand by the second operand.

Example

x = 14

y=4

print(x % y)

Output:

2
6. Exponentiation Operator (**)

The exponentiation arithmetic operator in Python is denoted by (**). It performs exponentiation


operations on numerical data types, including floats, integers, and complex numbers. It raises the first
operand to the power of the second operand.

Example

x=2

y=3

print(x ** y)

Output:

7. Floor Division Operator (//)

The floor division operator is denoted by the (//) symbol in Python and is used to find the floor of the
quotient. This operator divides the first operand by the second one and returns the quotient without a
remainder, which is rounded down to the nearest integer.

Example

x=7

y=4

print(x // y)

Output:

Python Strings
In Python, a string is a sequence of characters. For example, "hello" is a string containing a sequence of
characters 'h', 'e', 'l', 'l', and 'o'.

We use single quotes or double quotes to represent a string in Python. For example,

# create a string using double quotes

string1 = "Python programming"

# create a string using single quotes

string1 = 'Python programming'

Here, we have created a string variable named string1. The variable is initialized with the string "Python
Programming".

Example: Python String

# create string type variables

name = "Python"

print(name)

message = "I love Python."

print(message)

Run Code

Output

Python

I love Python.

In the above example, we have created string-type variables: name and message with values "Python"
and "I love Python" respectively.

Here, we have used double quotes to represent strings, but we can use single quotes too.

Access String Characters in Python

We can access the characters in a string in three ways.

Indexing: One way is to treat strings as a list and use index values. For example,
greet = 'hello'

# access 1st index element

print(greet[1]) # "e"

Run Code

Negative Indexing: Similar to a list, Python allows negative indexing for its strings. For example,

greet = 'hello'

# access 4th last element

print(greet[-4]) # "e"

Run Code

Slicing: Access a range of characters in a string by using the slicing operator colon :. For example,

greet = 'Hello'

# access character from 1st index to 3rd index

print(greet[1:4]) # "ell"

Run Code

Note: If we try to access an index out of the range or use numbers other than an integer, we will get
errors.

Compare Two Strings

We use the == operator to compare two strings. If two strings are equal, the operator returns True.
Otherwise, it returns False. For example,

str1 = "Hello, world!"

str2 = "I love Swift."

str3 = "Hello, world!"


# compare str1 and str2

print(str1 == str2)

# compare str1 and str3

print(str1 == str3)

Run Code

Output

False

True

In the above example,

str1 and str2 are not equal. Hence, the result is False.

str1 and str3 are equal. Hence, the result is True.

2. Join Two or More Strings

In Python, we can join (concatenate) two or more strings using the + operator.

greet = "Hello, "

name = "Jack"

# using + operator

result = greet + name

print(result)

# Output: Hello, Jack


Run Code

In the above example, we have used the + operator to join two strings: greet and name.

Python String Length

In Python, we use the len() method to find the length of a string. For example,

greet = 'Hello'

# count length of greet string

print(len(greet))

# Output: 5

String Membership Test

We can test if a substring exists within a string or not, using the keyword in.

print('a' in 'program') # True

print('at' not in 'battle') # False

upper()

Converts the string to uppercase

name="my name is tadisa"

print(upper(name))

Output

MY NAME IS TADISA

lower()

Converts the string to lowercase

name="MY NAME IS TADISA"

print(lower(name))
Output

my name is tadisa

Extract First N Characters

mystring = "Hey buddy, wassup?"

mystring[:2]

Output

'He'

string[start:stop:step] means item start from 0 (default) through (stop-1), step by 1 (default).

mystring[:2] is equivalent to mystring[0:2]

mystring[:2] tells Python to pull first 2 characters from mystring string object.

Indexing starts from zero so it includes first, second element and excluding third

Find last two characters of string

mystring[-2:]

The above command returns p?.The -2 starts the range from second last position through maximum
length of string.

3. Find characters from middle of string

mystring[1:3]

Output

'ey'

mystring[1:3] returns second and third characters. 1 refers to second character as index begins with 0.

if…else in Python

For

selection

,
Python

uses the

statements

if and else (note the lowercase syntax that Python uses):

Consider the age-related

algorithm

using Python. The steps are:

Ask how old you are

if you are 70 or older, say “You are aged to perfection!”

else say “You are a spring chicken!”

This algorithm would be written in Python (3.x) as:

age = int(input("How old are you?"))

if age >= 70:

print("You are aged to perfection!")

else:

print("You are a spring chicken!")

The program examines the value of age. If the inputted age is 70 or over, the

program

prints one message. Otherwise (else) it prints another.

Using ELSE IF to provide more choices

In

programming
,

selection

is implemented using IF

statements

Using IF and ELSE gives two possible choices (paths) that a program can follow. However, sometimes
more than two choices are wanted. To do this, the statement ELSE IF is used.

This simple

algorithm

prints out a different message depending on how old you are. Using IF, ELSE and ELSE IF, the steps
are:

Ask how old you are

IF you are 70 or older, say “You are aged to perfection!”

ELSE IF you are exactly 50, say “Wow, you are half a century old!”

ELSE say “You are a spring chicken!”

As a flow diagram, the algorithm would look like this:

A flowchart asking for your age will output the response 'wow, you are half a century old' if the age is
under 70 years old but equal to 50 years old.

Python

uses the statement elif, which stands for ‘ELSE IF.’

This flow diagram would be implemented in Python (3.x) as:


age = int(input("How old are you?"))

if age >= 70:

print("You are aged to perfection!")

elif age == 50:

print("Wow, you are half a century old!")

else:

print("You are a spring chicken!")

The

program

examines the value of age. If the inputted age is 70 or over, the program prints a particular message.
If the inputted age is exactly 50, the program prints a different message. Otherwise (else) it prints a
third message. Using elif allowed us to include a third choice in the program.

We can keep on adding elif statements to give us as many choices as we need:

age = int(input("How old are you?"))

if age >= 70:

print("You are aged to perfection!")

elif age == 50:

print("Wow, you are half a century old!")

elif age >= 18:

print("You are an adult.")

else:

print("You are a spring chicken!")


When using an ‘if...else if’ statement, the program will stop checking as soon as it finds a positive
answer. It is therefore very important to get the ‘if’ and ‘else’ conditions in the right order to make
the program as efficient as possible.

Learn to code solving problems with our hands-on Python course! Try Programiz PRO today.

Programiz

Search...

Programiz PRO

Python while Loop

In Python, we use a while loop to repeat a block of code until a certain condition is met. For example,

number = 1

while number <= 3:

print(number)

number = number + 1

Run Code

Output

3
In the above example, we have used a while loop to print the numbers from 1 to 3. The loop runs as long
as the condition number <= 3 is True.

while Loop Syntax

while condition:

# body of while loop

Here,

The while loop evaluates condition, which is a boolean expression.

If the condition is True, body of while loop is executed. The condition is evaluated again.

This process continues until the condition is False.

Once the condition evaluates to False, the loop terminates.

Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string).

This is less like the for keyword in other programming languages, and works more like an iterator
method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

ExampleGet your own Python Server

Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]

for x in fruits:

print(x)
The for loop does not require an indexing variable to set beforehand.

Looping Through a String

Even strings are iterable objects, they contain a sequence of characters:

Example

Loop through the letters in the word "banana":

for x in "banana":

print(x)

The break Statement

With the break statement we can stop the loop before it has looped through all the items:

Example

Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]

for x in fruits:

print(x)

if x == "banana":

break

Example

Exit the loop when x is "banana", but this time the break comes before the print:

fruits = ["apple", "banana", "cherry"]


for x in fruits:

if x == "banana":

break

print(x)

The range() Function

To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.

Example

Using the range() function:

for x in range(6):

print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to specify the starting value
by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):

Example

Using the start parameter:

for x in range(2, 6):

print(x)

The range() function defaults to increment the sequence by 1, however it is possible to specify the
increment value by adding a third parameter: range(2, 30, 3):
Example

Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):

print(x)

Else in For Loop

The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

Example

Print all numbers from 0 to 5, and print a message when the loop has ended:

for x in range(6):

print(x)

else:

print("Finally finished!")

Note: The else block will NOT be executed if the loop is stopped by a break statement.

Example

Break the loop when x is 3, and see what happens with the else block:

for x in range(6):

if x == 3: break

print(x)

else:

print("Finally finished!")
Python Data Types

Python Data Types are used to define the type of a variable. In this article, we’ll list out all the data types
and discussion the functionality of each. If you are starting out in Python, don’t forget to first visit the
Python tutorial for beginners. And if you’ve already gone through the same, don’t forget to check out
our previous tutorial on Python Comments and Statements.

Different Kinds of Python Data Types

There are different types of data types in Python. Some built-in Python data types are:

Numeric data types: int, float, complex

String data types: str

Sequence types: list, tuple, range

Binary types: bytes, bytearray, memoryview

Mapping data type: dict

Boolean type: bool

Set data types: set, frozenset

Python Numeric Data Type

Python numeric data type is used to hold numeric values like;

int - holds signed integers of non-limited length.

long- holds long integers(exists in Python 2.x, deprecated in Python 3.x).

float- holds floating precision numbers and it’s accurate up to 15 decimal places.

complex- holds complex numbers.

In Python, we need not declare a datatype while declaring a variable like C or C++. We can simply just
assign values in a variable. But if we want to see what type of numerical value is it holding right now, we
can use type(), like this:
#create a variable with integer value.

a=100

print("The type of variable having value", a, " is ", type(a))

#create a variable with float value.

b=10.2345

print("The type of variable having value", b, " is ", type(b))

#create a variable with complex value.

c=100+3j

print("The type of variable having value", c, " is ", type(c))

If you run the above code you will see output like the below image.python data types, use of type
function

Python String Data Type

The string is a sequence of characters. Python supports Unicode characters. Generally, strings are
represented by either single or double-quotes.

a = "string in a double quote"

b= 'string in a single quote'

print(a)

print(b)

# using ',' to concatenate the two or several strings

print(a,"concatenated with",b)
#using '+' to concate the two or several strings

print(a+" concated with "+b)

The above code produces output like the below picture-python data type, python string data type
example

Python List Data Type

The list is a versatile data type exclusive in Python. In a sense, it is the same as the array in C/C++. But
the interesting thing about the list in Python is it can simultaneously hold different types of data.
Formally list is an ordered sequence of some data written using square brackets([]) and commas(,).

#list of having only integers

a= [1,2,3,4,5,6]

print(a)

#list of having only strings

b=["hello","john","reese"]

print(b)

#list of having both integers and strings

c= ["hey","you",1,2,3,"go"]

print(c)

#index are 0 based. this will print a single character

print(c[1]) #this will print "you" in list c

The above code will produce output like this-

Python List Data Type Example


Example of a python list data type

Python Tuple

The tuple is another data type which is a sequence of data similar to a list. But it is immutable. That
means data in a tuple is write-protected. Data in a tuple is written using parenthesis and commas.

tuple having only integer type of data.

a=(1,2,3,4)

print(a) #prints the whole tuple

tuple having multiple type of data.

b=("hello", 1,2,3,"go")

print(b) #prints the whole tuple

#index of tuples are also 0 based.

The output of this above python data type tuple example code will be like the below image.Python Data
Type - tuple example output

Python Dictionary

Python Dictionary is an unordered sequence of data of key-value pair form. It is similar to the hash table
type. Dictionaries are written within curly braces in the form key:value. It is very useful to retrieve data
in an optimized way among a large amount of data.

#a sample dictionary variable

a = {1:"first name",2:"last name", "age":33}

#print value having key=1


print(a[1])

#print value having key=2

print(a[2])

#print value having key="age"

print(a["age"])

If you run this python dictionary data type example code, the output will be like the below image.Python
Data Type - python dictionary example output

Typecast

Explicit Type Casting

In explicit type conversion, Python needs user intervention to convert variable data type into the
required data type for performing a certain operation. This type casting in Python is mainly performed
on the following data types:

int(): takes a float or string object as an argument and returns an integer-type object.

float(): takes int or string object as an argument and returns a float-type object.

str(): takes float or int object as an argument and returns a string-type object.

Examples of Explicit Type Casting


Type Casting into Integer Data Types

We can use the int() method for the conversion of a specified value into an integer object. The syntax is:

int(value, base)

Where,

Value: Required parameter that specifies the value that has to be converted into an integer object.

Base: Optional parameter that denotes the base address. If not given, the default value considered is 10
i.e., a decimal number. Other than that, the following values can be specified:

2: convert a binary number into an equivalent decimal number.

8: convert an octal number into an equivalent decimal number.

16: convert a hexadecimal number into an equivalent decimal number.

Consider the below examples –

Example 1: Converting a float into an integer

#Explicit Type Casting


float_val = 705.23

#Converting the float into integer

num = int(float_val,2)

print("The floating-point number converted into integer: ", num)

Output 1:

Example 2: Converting a string into an integer

#Explicit Type Casting

string = "11110"

#Converting the string into integer

num = int(string,2)

print("The string converted into integer base-2: ", num

Output 2:

Example 3: Adding a string and an integer

string = "56"

num = 44

#Converting string into integer

str_num = int(string)

sum = num + str_num

print("Sum: ", sum

Output 3:

Sum: 100

Type Casting into Float Data Types

Consider the below example to convert an integer into a floating-point number:

#Explicit Type Casting


payment = 25650

TDS = payment * (0.15)

#Converting integer into float

salary = float(payment)

print("Salary after tax deduction: ", salary - TDS)

Copy code

Output:

Type Casting into String Data Types

We can use the str() method for the conversion of a specified object into a string. The syntax is:

str(object, encoding=’utf-8′, errors=’strict’)

Where,

Object: Required parameter that specifies the value that has to be converted into a string object. If no
value is given, the str() function returns an empty string.

Encoding: Optional parameter that stores the encoding of the specified object. If not given, the default
value i.e., UTF-8 is considered.

Errors: This is the response of the str() function if the decoding fails. It is an optional parameter that
stores the specified action to be performed in case of conversion/decoding failure.

Let’s consider the below example of converting an integer into a string object:

#Explicit Type Casting

num = 420

string = str(num)

print("The given number converted into string: ",string)

type(string)
Declare in python

we don't declare variables, we simply assign them. In short, we can think of a variable in Python as a
name for an object.

Rules for Naming Variables

To use variables effectively, we must follow Python’s naming rules:

Variable names can only contain letters, digits and underscores (_).

A variable name cannot start with a digit.

Variable names are case-sensitive (myVar and myvar are different).

Avoid using

Python keywords

(e.g., if, else, for) as variable names.

Valid Example:

1age = 21

2_colour = "lilac"

3total_score = 90

Basic Assignment

Variables in Python are assigned values using the =operator.

x=5

y = 3.14
3

z = "Hi"

Dynamic Typing

Python variables are dynamically typed, meaning the same variable can hold different types of values
during execution.

1x = 10

2x = "Now a string"

Multiple Assignments

Python allows multiple variables to be assigned values in a single line.

Assigning the Same Value

Python allows assigning the same value to multiple variables in a single line, which can be useful for
initializing variables with the same value.

1a = b = c = 100

2print(a, b, c)

Output

100 100 100

Assigning Different Values

We can assign different values to multiple variables simultaneously, making the code concise and easier
to read.

1x, y, z = 1, 2.5, "Python"

2print(x, y, z)

You might also like