Week 1 Python Practice Assignment - IITM BS Degree

Week-1, PPAs

This document has hints and answers to questions.

PPA-3

Hint

The input function always returns a string. If you want to accept an integer from the console, you have to first accept a string and then convert it into an integer.

Example

You could of course do it in a single line as:

x = int(input())

Explanation

In the snippet above, the input will be accepted as a string and then converted to an integer using int().

Note

Do not get confused between the exponentiation and the multiplication operator:

  • * : multiplication
  • ** : exponentiation

Answer

The correct approach to accepting an integer input is using x = int(input()).

PPA-5

Hint

String concatenation is a good place to start.

Example

first = 'one'
second = 'two'
print(first + second)

Output

onetwo

Question

Now, how do you modify the code so that there is a space between one and two? This is something for you to think about.

Answer

To add a space between the two words, modify the print statement as follows: print(first + ' ' + second)

PPA-6

Hint

Slice a string. You know the syntax. Where to start the slice and where to end it? This is something you have to figure out after looking at the test cases.

Answer

The syntax for slicing a string is string[start:end]. The start index is inclusive, and the end index is exclusive. Experiment with different indices to see the results.

PPA-7

Hint

Sometimes, it may be more beneficial to accept a string as input and not convert it into an integer right away.

Question

What do you think the variable first contains in the above snippet of code? Do you see how you can use this idea for other inputs?

Answer

The variable first will contain the string input directly. This allows you to manipulate or process the string before deciding whether to convert it into an integer.
Post a Comment (0)
Previous Post Next Post