UrbanPro
true

Learn Python Training from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

Python- Basic Concepts part 2

Divya S.
12/01/2017 0 0

1. Other Numerical Operations

a.  Exponentiation

  • Besides addition, subtraction, multiplication, and division, Python also supports exponentiation, which is the raising of one number to the power of another. This operation is performed using two asterisks.

            >>> 2**5
                       32
              >>> 9 ** (1/2)
                       3.0

b. Quotient & Remainder

  • To determine the quotient and remainder of a division, use the floor division and modulo operators, respectively.
  • Floor division is done using two forward slashes.
  • The modulo operator is carried out with a percent symbol (%).
  • These operators can be used with both floats and integers.
  • This code shows that 6 goes into 20 three times, and the remainder when 1.25 is divided by 0.5 is 0.25.

           >>> 20 // 6
                       3
            >>> 1.25 % 0.5
                     0.25

Ques1. Fill in the blank to make this code correct.

>>> (1 +__ )  ** 2

16

Ques2. What is the result of this code?
>>> 7%(5 // 2)

2. Strings

  • If you want to use text in Python, you have to use a string. A string is created by entering text between two single or double quotation marks.
  • When the Python console displays a string, it generally uses single quotes. The delimiter used for a string doesn't affect how it behaves in any way.

          >>> "Python is fun!"
                      'Python is fun!'
            >>> 'Always look on the bright side of life'
                     'Always look on the bright side of life'

  • Some characters can't be directly included in a string. For instance, double quotes can't be directly included in a double quote string; this would cause it to end prematurely.
  • Characters like these must be escaped by placing a backslash before them. Other common characters that must be escaped are newlines and backslashes.
  • Double quotes only need to be escaped in double quote strings, and the same is true for single quote strings.

           >>> 'Brian\'s mother: He\'s not the Messiah. He\'s a very smart boy!'
                     'Brian's mother: He's not the Messiah. He's a very smart boy!'

  • \n represents a new line.
  • Backslashes can also be used to escape tabs, arbitrary Unicode characters, and various other things that can't be reliably printed. These characters are known as escape characters.
  • Python provides an easy way to avoid manually writing "\n" to escape newlines in a string. Create a string with three sets of quotes, and newlines that are created by pressing Enter are automatically escaped for you.

          >>> """Customer: Good morning.
                     Owner: Good morning, Sir. Welcome to the National Cheese Emporium."""

                    'Customer: Good morning.\nOwner: Good morning, Sir. Welcome to the National                               Cheese Emporium.'

  • As you can see, the \n was automatically put in the output, where we pressed Enter.

Ques1. Complete the code to create a string containing “Hello world”.

>>> "Hello _____"

'Hello world'
 
Ques2. Complete the code to create a string containing a double quote.

 >>> "___"

Ques3. Fill in the missing part of the output.

 >>> """First line 

second line"""
'First line __second line'
 

3. Simple Input and Output

a. Output

  • Usually, programs take input and process it to produce output. In Python, you can use the print function to produce output. This displays a textual representation of something to the screen.
  • When a string is printed, the quotes around it are not displayed.

            >>> print(1 + 1)
                      2
             >>> print("Hello\nWorld!")
                      Hello
                      World!

b. Input

  • To get input from the user in Python, you can use the intuitively named input function.
    The function prompts the user for input, and returns what they enter as a string (with the contents automatically escaped).
  • The print and input functions aren't very useful at the Python console, which automatically does input and output. However, they are very useful in actual programs.

              >>> input("Enter something please: ")
                       Enter something please: This is what\nthe user enters!

                      'This is what\\nthe user enters!'

Ques1. What is the output of this code?
>>> print('print("print")')

Ques2. Fill in the blank to prompt for user input.

 >>> ______("Enter a number:")

4. String Operations

a. Concatenation

  • As with integers and floats, strings in Python can be added, using a process called concatenation, which can be done on any two strings.
  • When concatenating strings, it doesn't matter whether they've been created with single or double quotes.

               >>> "Spam" + 'eggs'
                         'Spameggs'

               >>> print("First string" + ", " + "second string")
                         First string, second string

  • Even if your strings contain numbers, they are still added as strings rather than integers. Adding a string to a number produces an error, as even though they might look similar, they are two different entities.

               >>> "2" + "2"
                        '22'
               >>> 1 + '2' + 3 + '4'
                        Traceback (most recent call last):
                        File "<stdin>", line 1, in <module>
                        TypeError: unsupported operand type(s) for +: 'int' and 'str'

b. String Operation

  • Strings can also be multiplied by integers. This produces a repeated version of the original string. The order of the string and the integer doesn't matter, but the string usually comes first.
  • Strings can't be multiplied by other strings. Strings also can't be multiplied by floats, even if the floats are whole numbers.

               >>> print("spam" * 3)
                        spamspamspam

               >>> 4 * '2'
                        '2222'

               >>> '17' * '87'
                        TypeError: can't multiply sequence by non-int of type 'str'

                >>> 'pythonisfun' * 7.0
                        TypeError: can't multiply sequence by non-int of type 'float'

Ques1. What is the output of this code?
>>> print(3 * '7')

Ques2. What is the output of this code?

>>>print("abc"*4)

0 Dislike
Follow 0

Please Enter a comment

Submit

Other Lessons for You

A program to determine the molecular weight of a hydrocarbon based on the number of Hydrogen,Carbon and Oxygen atoms.
import osimport math# A program to calculate Molecular Weight of a Hydrocarbon # These are the atomic weights(grams/mole) of Hydrogen,Carbon and OxygenatomicwtH = 1.0079atomicwtC = 12.011atomicwtO = 15.994Hatoms...

Python Dictionary
Python dictionary is an unordered collection of items. While other compound datatypes have only value as an element, a dictionary has a key: value pair. Dictionaries are optimized to retrieve values when...

Code: Gantt Chart: Horizontal bar using matplotlib for tasks with Start Time and End Time
import pandas as pd from datetime import datetimeimport matplotlib.dates as datesimport matplotlib.pyplot as plt def gantt_chart(df_phase): # Now convert them to matplotlib's internal format... ...
R

Rishi B.

0 0
0

Multiple Decorators
#Multiple decorators can be chained in Python.#A function can be decorated multiple times with different (or same) decorators.#We simply place the decorators above the desired function. def star(func):...

Python SubProcess
Question: As a Network Administrator, one of my trainee wants to know the below: He has certain number of Machines(IP’s). On daily basic he wants to know how many IP’s are reachable and...
X

Looking for Python Training Classes?

The best tutors for Python Training Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn Python Training with the Best Tutors

The best Tutors for Python Training Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more