Basics and String¶

Introduction¶

  • Python is a dynamic, interpreted (bytecode-compiled) language.
  • There are no type declarations of variables, parameters, functions, or methods in source code
In [5]:
a_number = 12
a_string = 'hello' # Strings must be within quotations
a_pi = 3.14
In [6]:
# shows how to print a string message template
# prints variables separated by a new line

print(a_number, a_string, a_pi, sep="\n")
12
hello
3.14

Let's try to mix types and see what happens

In [8]:
# The below line will raise a 'TypeError'
a_number + a_string
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-82ebd5d786b4> in <module>
      1 # The below line will raise a 'TypeError'
----> 2 a_number + a_string

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Since we do not declare types, runtime checks for types and does not allow invalid operations. TypeError is a type of expection, we will comeback to it when we learn about exception handling

Python source code¶

  • Python source files use the .py extension and are called modules.
  • With a Python module hello.py, the easiest way to run it is with the shell command python hello.py Alice which calls the Python interpreter to execute the code in hello.py, passing it the command line argument Alice.
  • Here we will use an notebook to learn the basics of python. Notebooks provide an easy way to play with the python interpreter. Later we will create python files in exercises.

Importing modules and packages¶

  • To import a python module we use the import statement
  • We will import the os builtin module and print the current working directory
  • Python documentation provides the language reference
  • Reference to OS module
In [37]:
import os

curr_working_dir = os.getcwd()
print("Current Working Directory -", curr_working_dir)
Current Working Directory - d:\Users\Krishna_Alagiri\projects\Misc\CBSE-Computer-Science
  • from keyword can be used to import specific item within a module
  • item could be a variable, sub-module or a function
In [38]:
from sys import version
print(version)
3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]

We're using python3 for learning python. You don't have to worry about the os and sys right now.

User defined functions¶

  • A function is a set of statements that take inputs, do some specific computation and produce output.
  • The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call the function.
  • Let's write a simple function to greet the user
  • greet_user() function accepts a variable username as argument/input and it prints a message.
  • format() function used inside print function,is a predefined function used to replace {} with a data. Thats' why you see John Doe in the place of {} in the output string
In [9]:
def greet_user(username):
  print("Hello {}. You're Awesome!".format(user))
In [10]:
greet_user('John Doe')
Hello John Doe. You're Awesome!

Indentation¶

  • Whitespace indentation of a piece of code affects its meaning.
  • A logical block of statements such as the ones that make up a function should all have the same indentation.

Python Strings¶

  • Strings are just like Arrays. Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
  • The len(string) function returns the length of a string.
  • Characters in a string can be accessed using the standard [ ] syntax, and like Java and C++, Python uses zero-based indexing, so if s is 'hello' s[1] is 'e'.
In [11]:
s = 'Hi'
print(s[1])         # Returns the second character
print(len(s))        # Finds length of the string variable.
print(s + ' there')  # Concatenates value stored in variable `s` and ' there'
i
2
Hi there
In [16]:
pi = 3.14

# The below line will raise an exception/error.
# You cannot concatenate sting and float
# text = 'The value of pi is ' + pi

# You can do it by converting float to string by using str()
text = 'The value of pi is '  + str(pi)
print(text)
The value of pi is 3.14

String methods¶

  • Python has a built-in string class named "str" with many handy features.
  • Documentation: https://docs.python.org/3/library/stdtypes.html#string-methods
In [17]:
# Return a copy of the string with all the cased characters converted to lowercase. 
text.lower()
Out[17]:
'the value of pi is 3.14'
In [20]:
# Return a copy of the string with all the cased characters converted to uppercase.
text.upper()
Out[20]:
'THE VALUE OF PI IS 3.14'
In [21]:
# Return True if all characters in the string are alphabetic and there is at least one character, 
# False otherwise.
text.isalpha()
Out[21]:
False
In [22]:
# Return True if all characters in the string are numeric characters, and there is at least one character, 
# False otherwise.
text.isnumeric()
Out[22]:
False
In [24]:
# Return True if string starts with the prefix, otherwise return False. 
text.startswith('T')
Out[24]:
True
In [27]:
# Returns True if the text contains a substring, otherwise return False. 
# The below will return True since 'pi' is substring of text.

'pi' in text
Out[27]:
True
In [29]:
# Return the lowest index in the string where substring sub is found.
# Returns -1 if not found.
text.find('pizza')
Out[29]:
-1
In [30]:
csv = "abc,ced,def,hij"

# Return a list of the words in the string, using `sep` (argument) as the delimiter string.
csv.split(",")
Out[30]:
['abc', 'ced', 'def', 'hij']

Conditonal Statements¶

IF...ELIF...ELSE Statements

The syntax of the if...else statement is −

if expression:
   statement(s)
else:
   statement(s)

Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if.

The syntax of the if..elif..else statement is −

if expression1:
   statement(s)
elif expression2:
   statement(s)
elif expression3:
   statement(s)
else:
   statement(s)
In [31]:
if 'pi' in text.lower():
  print("Text contains the substring 'pi'")
  pi_index = text.find('pi')
  print(pi_index)
Text contains the substring 'pi'
13
In [32]:
if 4 < 3:
  # pass is a command to do nothing
  pass 
elif 'pi' in text.lower():
  print('Text contains the substring \'pi\'')
else:
  pass
Text contains the substring 'pi'