Python Syntax, Variables and Datatypes — Numbers, Strings, Booleans

Strings and their Methods

Python Syntax

Python syntax can be executed by writing directly in the Command Line:

>>> print(“Hello, World!”)
Hello, World!

Or by creating a python file on the server, using the .py file extension, and running it in the Command Line:

D:\Python\programs>python myfile.py

Python Indentation

Indentation refers to the spaces at the beginning of a code line.In other programming languages the indentation in code is just for readability purpose, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

>>> if True:
... print("Hello World")
...
Hello World

Python gives an error if you skip the indentation:

>>> if True:
... print("Hello World")
File "<stdin>", line 2
print("Hello World")
^
IndentationError: expected an indented block
>>>

Comments

Python has commenting capability for the purpose of in-code documentation. Comments start with a ‘#’, and Python will render the rest of the line as a comment:

>>>#This is a comment.
>>>print("Hello, World!")
Hello, world!

Comments can be used to explain Python code. Comments can be used to make the code more readable. Comments can be used to prevent execution when testing code.

Comments can be placed at the end of a line, and Python will ignore the rest of the line:

>>>print("Hello, World!") #This is a comment

Comments does not have to be text to explain the code, it can also be used to prevent Python from executing code.

Multi Line Comments

Python do not have a multiline comment. Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it:

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

As long as the string is not assigned to a variable, Python will read the code, but then ignore it, and you have made a multiline comment.

Python Variables

In Python, variables are created when you assign a value to it. Python has no command for declaring a variable.

x = 5
y = "Hello, World!"

Here x and y are variables. x is an integer variable and y is an string variable.

Creating Variables

Variables are containers for storing data values. Variables are reserved memory location to store values. Unlike other programming languages, Python has no command for declaring a variable. A variable is created when we assign a value to it.

>>>a = 1000
>>>b = 10.24
>>>c = "Andhra University"

Variables do not need to be declared with any particular type and can even change type after they have been set.

>>>c = "Andhra University"
>>>c = 10000
>>>print(c)
1000

String variables can be declared either by using single or double quotes:

>>>c = "Andhra University"
#is same as
>>>c = 'Andhra University"

Variable Names

A variable can have a short name (like x and y) or a more descriptive name (age, car_name, total_vol).

Rules for Python variables:

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0–9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)
>>>s = "string"
>>>college_name = "Andhra University"

Here s is a simple variable and college_name is a more descriptive variable.

Assign Value to Multiple Variables

Python allows you to assign values to multiple variables in one line:

>>>a,b,c = 1,2,"Andhra"
>>>print(a)
1
>>>print(b)
2
>>>print(c)
Andhra

And you can assign the same value to multiple variables in one line:

>>>a = b = c = "string"
>>>print(a)
string
>>>print(b)
string
>>>print(c)
string

The Python print statement is often display the values of the variables. To combine both text and a variable, Python uses the + character:

>>>x = "I Love"
>>>print(x + "Python")
I Love Python

Python Data Types

In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories:

Text Type:str

Numeric Types:int, float, complex

Sequence Types:list, tuple, range

Mapping Type:dict

Set Types:set, frozenset

Boolean Type:bool

Binary Types:bytes, bytearray, memoryview

You can get the data type of any object by using the type() function:

>>>x = 5
>>>print(type(x))
<class 'int'>

Python Numbers

There are three numeric types in Python:

  • int
  • float
  • complex

Variables of numeric types are created when you assign a value to them:

>>>x = 1100      # int
>>>y = 2234.845 # float
>>>z = 1j # complex
>>>print(type(x))
<class 'int'>
>>>print(type(y))
<class 'float'>
>>>print(type(z))
<class 'complex'>

Type Conversion

You can convert from one type to another with the int(), float(), and complex() methods:

>>>x = 1100      # int
>>>y = 2234.845 # float
>>>z = 1j # complex
#convert from int to float:
>>>a = float(x)

#convert from float to int:
>>>b = int(y)

#convert from int to complex:
>>>c = complex(x)

>>>print(a)
1100.0
>>>print(b)
2234
>>>print(c)
1100+0j
>>>print(type(a))
<class 'float'>
>>>print(type(b))
<class 'int'>
>>>print(type(c))
<class 'complex'>

Random Number

Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers:

>>> import random
>>> print(random.randrange(1, 10))
9

Python Strings

Strings are sequence of characters. String literals in python are surrounded by either single quotation marks, or double quotation marks. ‘hello’ is the same as “hello”. You can display a string literal usingprint() function:

>>>a = "Hello"
>>>print(a)

Multiline Strings

You can assign a multiline string to a variable by using three quotes:

>>>a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
>>>print(a)

Or three single quotes:

>>>a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
>>>print(a)

Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.

>>>str = "Hello, World"
>>>print(str[1]) #prints a value at index 1
e

This is the format of how the string “Hello, World” is stored as a array. The space involved in the string also counts.

index---->     0 1 2 3 4 5 6 7 8 9 1011
H e l l o , w o r l d
-12...............-3-2-1

Therefore, str[1] is e.

Python also supports negative indexing.

>>>str[-1] #Prints last character
d

A slice Operator is used in python to display some of the characters or substring.

Synatx of slice operator: str [ start : end ]
start should be always less than end (start< end) where in slice operator the start is included and end is excluded.

>>>str[2:5]
llo
#Using Negative Indexing
>>>str[-4:-1]
orl

As I have already mentioned above, 2 will be included and 5 will be excluded. therefore, the characters at the index 2 to 5–1 will be printed.That means the characters at str[2],str[3],str[4] are printed. In the same way slice operator deals with negative indexing.

String Length

To get the length of a string, use the len() function.

>>>a = "Hello, World!"
>>>print(len(a))
13

String Methods

Python has a set of built-in methods that you can use on strings.

Let us check the usage of these methods.

>>>name = "python programming">>>print(name)        #prints the string
python programming
>>>print(name.upper()) #prints the sting in uppercase
PYTHON PROGRAMMING
>>>print(name.lower()) #prints the string in lowercase
python programming
>>>print(name.islower()) #checks if string is lowercase or not
TRUE
>>>print(name.isupper()) # checks if string is uppercase or not
FALSE
>>>print(name.split(" ")) #Splits the string by space
['python', 'programming']
>>>print(name.capitalize()) #First character in the string becomes capital
Python programming
#Counts number of times the character is repeated in the string
>>>print(name.count('p'))
2
#Counts the character in the string from specified index
>>>print(name.count('p',5))
1
#Counts the character in the string in between the specified index
>>>print(name.count('p',5,10))
1
#replaces the character in the string
>>>print(name.replace("p", "J"))
'Jython Jrogramming'
#returns the index of the character in the string
>>>print(name.index('p'))
0
#Returns the index of the character in the string in from specified #index
>>>print(name.index('p',5))
7
#Returns the index of the character in the string in between specified indexes
>>> print(name.index('p',5,10))
7
#checks if string consists of alphabets and numbers
>>>print(name.isalnum())
FALSE
#
>>>print(name.isdigit())
FALSE

Special Method format() is used to replace the strings in empty braces.

For example:

>>>query = "I love {} and {}"
>>>print(query.format("python","hadoop"))
I love python and hadoop

Let us see about Booleans..

Python Booleans

In programming you often need to know if an expression is True or False. You can evaluate any expression in Python, and get one of two answers, True or False. When you compare two values, the expression is evaluated and Python returns the Boolean answer:

>>>print(10 > 9)
True
>>>print(10 == 9)
False
>>>print(10 < 9)
False

The bool() function allows you to evaluate any value, and give you True or False in return,

Most Values are True

Almost any value is evaluated to True if it has some sort of content.

Any string is True, except empty strings.

Any number is True, except 0.

Any list, tuple, set, and dictionary are True, except empty ones.

>>>print(bool("Hello"))
True
>>>print(bool(15))
True
>>>bool("abc")
True
>>>bool(123)
False
>>>bool(["apple", "cherry", "banana"])
False

Some Values are False

In fact, there are not many values that evaluates to False, except empty values, such as (), [], {}, "", the number 0, and the value None. And of course the value False evaluates to False.

>>>bool(False)
False
>>>bool(None)
False
>>>bool(0)
False
>>>bool("")
False
>>>bool(())
False
>>>bool([])
False
>>>bool({})
False

--

--