lower programming
lower programming
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 a tuple:
print(x)
print(7)
#to just print the variable on its own include only the name of it
fave_language = "Python"
print(fave_language
fave_language = "Python"
#output
print("I like coding in" + " " + fave_language + " " + "the most")
#output
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
first_name = "John"
last_name = "Doe"
#output
So, you separate text from variables with a comma, but also variables from other variables, like shown
above.
input function
x = input()
print('Hello, ' + x)
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))
The following points will explain the importance of the input() function:
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.
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: +
Subtraction: –
x–y
Multiplication: *
x*y
Division (float): /
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
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 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
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:
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
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:
Example
logo
menu
About Us
Career Schools
Apply as Mentor
Contact Us
Login
Home
Icon
Resources
Icon
Icon
Icon
2 mins read
2840 views
Icon Share
2.60%
Table of Contents
Introduction
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.
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.
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%)
Exponentiation (**)
Operator
Description
Syntax
Addition: +
adds the two operands.
x+y
Subtraction: –
x–y
Multiplication: *
x*y
Division (float): /
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
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 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
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
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
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 (**)
Example
x=2
y=3
print(x ** y)
Output:
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,
Here, we have created a string variable named string1. The variable is initialized with the string "Python
Programming".
name = "Python"
print(name)
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.
Indexing: One way is to treat strings as a list and use index values. For example,
greet = 'hello'
print(greet[1]) # "e"
Run Code
Negative Indexing: Similar to a list, Python allows negative indexing for its strings. For example,
greet = 'hello'
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'
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.
We use the == operator to compare two strings. If two strings are equal, the operator returns True.
Otherwise, it returns False. For example,
print(str1 == str2)
print(str1 == str3)
Run Code
Output
False
True
str1 and str2 are not equal. Hence, the result is False.
In Python, we can join (concatenate) two or more strings using the + operator.
name = "Jack"
# using + operator
print(result)
In the above example, we have used the + operator to join two strings: greet and name.
In Python, we use the len() method to find the length of a string. For example,
greet = 'Hello'
print(len(greet))
# Output: 5
We can test if a substring exists within a string or not, using the keyword in.
upper()
print(upper(name))
Output
MY NAME IS TADISA
lower()
print(lower(name))
Output
my name is tadisa
mystring[:2]
Output
'He'
string[start:stop:step] means item start from 0 (default) through (stop-1), step by 1 (default).
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
mystring[-2:]
The above command returns p?.The -2 starts the range from second last position through maximum
length 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
algorithm
else:
The program examines the value of age. If the inputted age is 70 or over, the
program
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:
ELSE IF you are exactly 50, say “Wow, you are half a century old!”
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
else:
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.
else:
Learn to code solving problems with our hands-on Python course! Try Programiz PRO today.
Programiz
Search...
Programiz PRO
In Python, we use a while loop to repeat a block of code until a certain condition is met. For example,
number = 1
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 condition:
Here,
If the condition is True, body of while loop is executed. The condition is evaluated again.
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.
for x in fruits:
print(x)
The for loop does not require an indexing variable to set beforehand.
Example
for x in "banana":
print(x)
With the break statement we can stop the loop before it has looped through all the items:
Example
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:
if x == "banana":
break
print(x)
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
for x in range(6):
print(x)
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
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
print(x)
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.
There are different types of data types in Python. Some built-in Python data types are:
float- holds floating precision numbers and it’s accurate up to 15 decimal places.
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
b=10.2345
c=100+3j
If you run the above code you will see output like the below image.python data types, use of type
function
The string is a sequence of characters. Python supports Unicode characters. Generally, strings are
represented by either single or double-quotes.
print(a)
print(b)
print(a,"concatenated with",b)
#using '+' to concate the two or several strings
The above code produces output like the below picture-python data type, python string data type
example
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(,).
a= [1,2,3,4,5,6]
print(a)
b=["hello","john","reese"]
print(b)
c= ["hey","you",1,2,3,"go"]
print(c)
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.
a=(1,2,3,4)
b=("hello", 1,2,3,"go")
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.
print(a[2])
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
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.
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:
num = int(float_val,2)
Output 1:
string = "11110"
num = int(string,2)
Output 2:
string = "56"
num = 44
str_num = int(string)
Output 3:
Sum: 100
salary = float(payment)
Copy code
Output:
We can use the str() method for the conversion of a specified object into a string. The syntax is:
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:
num = 420
string = str(num)
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.
Variable names can only contain letters, digits and underscores (_).
Avoid using
Python keywords
Valid Example:
1age = 21
2_colour = "lilac"
3total_score = 90
Basic Assignment
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 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
We can assign different values to multiple variables simultaneously, making the code concise and easier
to read.
2print(x, y, z)