03 - Variables - Strings

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Variables, Strings & Data type

Introduction & Objectives


● Understand variable naming
● Understand naming convention and restrictions in python
● Understand how to use python data types
● Understand strings extensively
Variable naming
What are variables ?
Variables are like containers used for storing data values, It is a reserved memory location that stores and
manipulates data. Values are assigned to a variable using the ‘ = ’ operator , the variable will be on the left side
while the data value is on the right side. For example;

y=5

programming_language = “Python”

NB: Variables must be assigned in python before they can be used

Variables can also be assigned like this, using variables separated by commas

all, at, once = 3, 9, 27


Variable naming
Naming conventions

There are some naming conventions in python and programming languages generally, these are ways
variable can be named that is widely accepted and known around the world.

● snake_case e.g python_programming_language


● lowercase e.g name
● CamelCase e.g PythonProgrammingLanguage
● CAPITAL_SNAKE_CASE e.g PYTHON_PROGRAMMING_LANGUAGE
Variable naming
Naming restrictions in python
There are some naming restrictions/rules in python

● Variables in python are case sensitive e.g Name is not same as name
● Variables in python can start with a letter or an underscore; must start with an
alphabet or underscore
● The rest of the name must consist of letters, numbers, or underscores
Python Special Characters
Python Special Characters
In every programming language there are some values/characters that can not be used as variables because
they have been used as constant in the built-in library of the programming language, These kind of
values/characters are referred to as special characters.

In python we have some of these characters, they are constants built-in python namespace some of them are
the names of python built in functions hence they can not be reassigned when naming a variable.

Examples of some of the special characters in python are :

True, False, None, class, def, return type, print etc.

Make more research on other python special character


Python Data Types
Python Data Types
Data Type in Python

Numeric Sequence Dictionary Boolean Set

Integer Float Complex number

Strings Lists
Tuples
Python Data Types
Integer: numbers without any fractional part. They can be 0, positive or negative
Floating point number: They are numbers with decimals or fractional part. They can either be
positive or negative. e.g -3.5, 2.0, 1.2 etc.
Complex numbers: are real numbers with imaginary part.
String: is a sequence enclosed in single, double or triple quotes. e.g ‘apple’, “apple”, “““apple”””
Lists: are an ordered sequence of one or more types of values. They are mutable, i.e their values can
be modified. The element of list are enclosed in a square bracket [ ] e.g [1, 7, “Python” True]
Tuples: are ordered sequence of one or more types of values but unlike list they are immutable i.e
there values cannot be modified.
Dictionaries: are unordered collection of pair values (key : values). The elements of a dictionary are
enclosed in a curly brackets { } e.g {“Name”: “Joe”, “Age”: 32}
Python Data Types
Boolean: is a data type that has one of two possible values, True or False. They are mostly used in
conditional statements or creating the control flow.
Sets: are unordered collection of elements. They contain unique data only. They are mutable i.e there
values can be modified. The are enclosed in curly brackets. e.g {‘a’, ‘e’, ‘i’, ‘o’, ‘u’}
Data type conversion
You can convert from one data type to another using the conversion functions
list ( ) #convert tuples to list; list((1,4,”good”, True))
str ( ) #convert any value to string; str(123)
tuple ( ) #convert list to tuple([1,2,3,5])
int ( ) #convert floating point number to integer; int(5.0)
float ( ) #convert integers to floating point numbers; float(7)
String escape sequence
String escape sequence
String: is a sequence enclosed in single, double or triple quotes.
Escape characters or sequences are illegal characters for Python and never get printed as part of the output. When
backslash is used in Python programming, it allows the program to escape the next characters.

An escape character is a backslash \ followed by the character you want to insert.

An example of an illegal character is a double quote inside a string that is surrounded by double quotes, for example

sentence = "These are the so called “Genius” from our country." # this would flag an error

To avoid this flagging an error we have to use \”

sentence = "These are the so called \“Genius\” from our country."


String escape sequence
Examples of some of the escape sequence in python

Code Result

\’ Single quote

\n New line

\\ Backslash

\t Tab

\r Carriage return
String concatenation
String concatenation
String concatenation is the addition of two or more strings together, it can be done using the ‘+’
operator

txt = “Hello ” + “world” # Hello world

greeting = “Welcome home ”

name = “John”

txt = greeting + name # Welcome home John

NB: You can also make use of comma “ , ” for string concatenation

txt = “Hello” , “world”


String formatting
String formatting
String formatting is the process of infusing things in the string dynamically and presenting the string.

There are four different ways to perform string formatting in Python:

● Formatting with % Operator.


● Formatting with format( ) string method.
● Formatting with string literals, called f-strings.
● Formatting with String Template Class

But we are going to be looking at the format() string method & the f-strings method in this lesson
String formatting
String format( ) method
This method was introduced with Python3 for handling complex string formatting more efficiently. Formatters work
by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and
calling the str.format( ). The value we wish to put into the placeholders and concatenate with the string passed as
parameters into the format function.

Syntax: ‘String here { } then also { }’.format(‘something1′, ’something2’)

print('Good morning, { }.' .format('John')) # Good morning, John

num = 20

txt = "There are {} eggs in the basket”

print(txt.format(num)) # “There are 20 eggs in the basket”


String formatting
String format( ) method
quantity = 3

item_no = 567

price = 49.95

myorder = "I want to pay {2} dollars for {0} pieces of item {1}."

print(myorder.format(quantity, item_no, price))

f string method

To create an f-string, prefix the string with the letter “ f ”.

name = 'John'

print(f"My name is {name}.")


String Indexing
String Indexing
Often in programming languages, individual items in an ordered set of data can be accessed directly using a numeric index or
key value. This process is referred to as indexing.

In Python, strings are ordered sequences of character data, and thus can be indexed in this way. Individual characters in a
string can be accessed by specifying the string name followed by a number in square brackets ([]).

String indexing in Python is zero-based: the first character in the string has index 0, the next has index 1, and so on. The
index of the last character will be the length of the string minus one.

For example:

-5 -4 -3 -2
-1

b r a i n
0 1 2 3 4
index
String Indexing
NB: Each character in the string can be assessed by its index

txt = “brain”

txt [0] # b

txt [2] # a etc.

NB: we can get the length of a string using the len ( ) function

len(txt) # 5

String indices can also be specified with negative numbers, in which case indexing occurs from the end of the string
backward

txt[-1] # n

txt[-3] # a
String Slicing
String Slicing
Python also allows a form of indexing syntax that extracts substrings from a string, known as string slicing. If txt is a string,
an expression of the form txt[m:n] returns the portion of txt starting with position m, and up to but not including position n:

For example:

txt = “brain”

txt[2 : 5] # “ain”

txt[0 : 6] # “brain”

Negative indices can be used with slicing as well.

txt[:] # “brain”

txt[: : -1] “niarb” # [start : end : step]

txt[: : -2] “nab”

txt[1 : -2] # “ra”


End of Lecture
Quizz
Write a Python program to calculate the length of a string.

Write a Python script that takes input from the user and displays that input back in upper and lower cases.

Write a Python program to count the occurrences of each word in a given sentence.

Write a Python program to reverse a string.

Given : input str_y = "python”

Output: “nohtyp”

Write a Python program to remove spaces from a given string.

Write a program to accept a string from the user and display characters that are present at an even index number.

Write program to return True if the first and last number of a given list is same. If numbers are different then return False.

Given: x = [10,15,20,5,10]

y = [5,10,20,25,10]

Write a program to count the number of times “Emma” appears in a string.

Given : str_x = "Emma is good developer. Emma is a writer"

You might also like