0% found this document useful (0 votes)
8 views11 pages

01 Python Basics

The document provides an overview of printing in Python, including the use of the print() function, string manipulation, and user input. It covers various programming problems related to variables, data types, and string formatting, as well as advanced topics like slicing and modern string formatting techniques. Additionally, it includes practical exercises to reinforce learning, such as creating a bio card and calculating simple interest.

Uploaded by

yawar ayub
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views11 pages

01 Python Basics

The document provides an overview of printing in Python, including the use of the print() function, string manipulation, and user input. It covers various programming problems related to variables, data types, and string formatting, as well as advanced topics like slicing and modern string formatting techniques. Additionally, it includes practical exercises to reinforce learning, such as creating a bio card and calculating simple interest.

Uploaded by

yawar ayub
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

 Printing in Python

The print() function is a built-in Python function that outputs data to the
standard output (usually your terminal or console).

Syntax: print(object(s), sep=' ', end='\n')

 object(s): One or more objects (like strings, numbers, variables) that


you want to print. They will be converted to a string before being
printed.

 sep=' ': (Optional) The separator to use between multiple objects.


By default, it's a single space.

 end='\n': (Optional) The character to print at the very end. By


default, it's a newline character (\n), which moves the cursor to the
next line.

# The classic first program

print("Hello, World!")

# Printing multiple items

name = "Alice"

age = 30

print("Name:", name, "Age:", age)

# Output: Name: Alice Age: 30

# Using a custom separator

print("Python", "is", "fun", sep="---")

# Output: Python---is---fun

# Using a custom end character to stay on the same line

print("Processing...", end="")

print("Done!")

# Output: Processing...Done!
How Strings, Input & Escape Sequences Work

 Strings (str): A string is a sequence of characters. In Python,


strings are immutable, which means they cannot be changed after
they are created. Any operation that looks like it's modifying a string
(like concatenation) is actually creating a new string in memory.

o They can be created with single quotes ('...'), double quotes


("..."), or triple quotes ('''...''' or """...""" for multi-line strings).

 Input (input()): This is a built-in function to get input from the


user.

o Crucial Point: input() always returns the user's input as


a string. If you need a number, you must explicitly convert
(or "cast") it using functions like int() or float().

 Escape Sequences (\): These are special combinations of


characters that have a non-literal meaning. They start with a
backslash \.

o \n: Newline - Moves the cursor to the beginning of the next


line.

o \t: Tab - Inserts a horizontal tab.

o \\: Backslash - Inserts a literal backslash character.

o \' or \": Quote - Inserts a literal single or double quote, useful


when you need a quote inside a string that is defined by the
same quote type.

Problem 1 : Write a program that takes the user's full name as input on
one line and their age on another. Then, print a bio card formatted exactly
as shown below, including the quotes and tabs.
Variables and Data Types
Think of a variable as a name or a label that you assign to a value. The
variable "points" to a location in the computer's memory where the data is
stored. In Python, you don't need to declare a variable's type beforehand.
This is called dynamic typing.

Problem 2 : A movie theatre sells tickets for Rs. 120 each. Write a
program that asks the user how many tickets they want and how
much money they have. Calculate if they can afford the tickets
and, if so, how much change they will get back.

Problem 3: Write a program that asks for the principal amount,


time period (in years), and rate of interest. Calculate and display
the simple interest.

Problem 4: Ask the user for their first name and last name. Print a
greeting that says "Hello, [Last Name], [First Name]."

Problem 5: Ask the user for the length and width of a rectangle.
Calculate and print both its area and its perimeter.

Problem 6: Ask the user for two numbers, A and B. Swap their
values and print the new values of A and B.

Slicing in Python
Slicing is the technique of extracting a portion or a "slice" of a sequence. A
sequence is any ordered data structure like a string, a list, or a tuple.
Slicing creates a new copy of the extracted elements.

The complete syntax for slicing is sequence[start : stop : step].


a. Basic Slicing

my_list = ['a', 'b', 'c', 'd', 'e', 'f']

# From index 1 up to (but not including) index 4

print(my_list[1:4]) # Output: ['b', 'c', 'd']

# From the beginning up to index 3

print(my_list[:3]) # Output: ['a', 'b', 'c']

# From index 2 to the very end

print(my_list[2:]) # Output: ['c', 'd', 'e', 'f']

# A full copy of the list

print(my_list[:]) # Output: ['a', 'b', 'c', 'd', 'e', 'f']

b. Step Slicing

my_string = "P-y-t-h-o-n"

# Start at 0, go to the end, take every 2nd character

print(my_string[0::2]) # Output: "Python" (extracts the letters)

my_numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Get every 3rd number starting from index 1

print(my_numbers[1::3]) # Output: [1, 4, 7]


c. Backward Slicing
This is where slicing becomes truly powerful. You can use negative
indices for start and stop, and a negative step to go backward.

 Negative step: A step of -1 means to iterate from right to left.

my_string = "Hello World"

# The most famous slice: Reverse a sequence

# Start at end (default), stop at beginning (default), step backwards

print(my_string[::-1]) # Output: "dlroW olleH"

my_list = [10, 20, 30, 40, 50]

# Get the last 3 elements

print(my_list[-3:]) # Output: [30, 40, 50]

# From index -2 (40) back to (but not including) index -5 (20)

print(my_list[-2:-5:-1]) # Output: [40, 30]

# What happens if start is left of stop with a negative step?

print(my_list[1:4:-1]) # Output: [] (an empty list, as it can't go backward


from 1 to 4)

Problem 7

 Statement: Given a string s, determine if it is a palindrome,


considering only alphanumeric characters and ignoring cases. An
empty string is considered a valid palindrome.

 Example 1: s = "A man, a plan, a canal: Panama" -> True

 Example 2: s = "race a car" -> False


 Example 3: s = " " -> True

Problem 8

Write a function that takes a filename as a string and returns its


extension. If there is no extension, return an empty string.

 Concepts Tested: Finding a character, slicing from a found


index to the end.

Problem 9

Write a function that rotates a list to the left by k positions. For


example, rotating [1, 2, 3, 4, 5] by 2 positions results in [3, 4, 5,
1, 2].

 Concepts Tested: Combining two slices with concatenation.


This is a very elegant and efficient way to solve this common
problem.

Problem 10

Write a function that rotates a list to the left by k positions. For


example, rotating [1, 2, 3, 4, 5] by 2 positions results in [3, 4, 5,
1, 2].

 Concepts Tested: Combining two slices with concatenation.


This is a very elegant and efficient way to solve this common
problem.

 Also consider the condition if k is greater than array size

Problem 11

Given a sentence as a string, reverse each word in the sentence


but maintain the original order of the words.

 Example: "Hello World" -> "olleH dlroW"

 Concepts Tested: split(), join(), and applying backward


slicing in a loop or list comprehension.
String Operators & Legacy Formatting

Before we get to modern formatting, it's important to understand the


basic operators and the "old way" of formatting strings.

# Concatenation

first_name = "John"

last_name = "Doe"

full_name = first_name + " " + last_name

print(full_name) # Output: John Doe

# Repetition

separator = "-" * 20

print(separator) # Output: --------------------

Important Note:

 Concatenation Trap: An interviewer might ask about the


performance of building a long string using the + operator
in a loop.

o Bad: result = ""; for char in my_list: result += char

o Why it's bad: This is O(n²) because strings are


immutable. Each += creates a new string and copies
the contents of the old string and the new character.

o The Right Way: Use "".join(my_list). This is optimized


and runs in O(n). Knowing this distinction is a huge
plus.
Modern String Formatting (.format() and f-
strings)
1. The str.format() Method:
This method is called on a string and uses curly braces {} as
placeholders.

# Positional arguments

print("My name is {0} and I am {1} years old. {0} is a nice


name.".format("Bob", 35))

# Output: My name is Bob and I am 35 years old. Bob is a nice name.

# Keyword arguments (more readable)

print("My name is {name} and I am {age} years


old.".format(name="Carol", age=25))

# Output: My name is Carol and I am 25 years old.

# Combination

name = "Dave"

age = 42

print("My name is {} and I am {} years old.".format(name, age))

# Output: My name is Dave and I am 42 years old.

Formatting with Precision & Alignment


(Replacement Fields):

 Precision (.precision): For floats, this controls the number of


decimal places.

 Alignment (<, ^, >): Left, center, or right alignment within a given


width.
 Width: The total minimum characters the field should occupy.

 Type (f, d, s, ,): Specifies the type, like float, decimal (integer), or
string. The comma , adds a thousands separator.

pi = 3.14159265

price = 4500.5

# Precision

print("The value of pi is approximately {:.2f}".format(pi))

# Output: The value of pi is approximately 3.14

# Width and Alignment

print("Product: {:<10} | Price: {:>8.2f}".format("Apples", 120.5))

print("Product: {:<10} | Price: {:>8.2f}".format("Oranges", 85))

# Output:

# Product: Apples | Price: 120.50

# Product: Oranges | Price: 85.00

# Thousands separator

print("The price of the car is ${:,.2f}".format(1234567.89))

# Output: The price of the car is $1,234,567.89

f-strings (Formatted String Literals)


Introduced in Python 3.6, f-strings are the preferred, modern, and
most efficient way to format strings. You prefix the string with an f and
place variables or any valid Python expression directly inside the {}.

name = "Eve"

age = 28

pi = 3.14159265
# Simple and clean

print(f"My name is {name} and my age is {age}.")

# Expressions are allowed directly inside!

print(f"Next year, I will be {age + 1} years old.")

# Formatting specifiers work exactly the same way

print(f"The value of pi is approximately {pi:.2f}.")

# Combined with other expressions

items = ["apple", "banana"]

print(f"{name} has {len(items)} items in her basket.")

Problem 12

 You are building a checkout system for an online store. A customer


has purchased several units of a single item and has a discount
code. You need to generate a formatted text receipt.

 Task: Write a script that:

1. Asks for the item name (e.g., "Wireless Mouse").


2. Asks for the price of one unit (e.g., 450.50).
3. Asks for the quantity purchased (e.g., 3).
4. Asks for the discount percentage (e.g., 15).
5. Calculates the subtotal, the discount amount, and the final
total.
6. Prints a neatly formatted receipt with all values aligned and
currency formatted to two decimal places.
 Concepts Tested: input(), type casting, arithmetic, and applying f-
string formatting for alignment and precision.
 Final output should be like this

You might also like