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

Chapter 3+4

Uploaded by

mua347175
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 views13 pages

Chapter 3+4

Uploaded by

mua347175
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/ 13

Lecture 3+4

Q1. How do you break a long statement into multiple


lines?
Ans in Python, you can break a long statement into multiple lines
using one of these methods:
1. Using a Backslash (\)
Place a backslash at the end of the line to indicate the
statement continues:
Code:
total = 1 + 2 + 3 + 4 + 5 + \
6 + 7 + 8 + 9 + 10
2. Using Parentheses
Enclose the statement in parentheses. This is often preferred
as it's cleaner and more readable:
Code:
total = (1 + 2 + 3 + 4 + 5 +
6 + 7 + 8 + 9 + 10)
3. Using Square Brackets, Curly Braces, or
Parentheses
For lists, dictionaries, or tuples, Python allows implicit line
continuation without a backslash:
Code:
numbers = [
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
]
4. Using String Concatenation
For strings, break into multiple lines and use + or implicit
concatenation:
python
Code:
message = ("This is a long string that "
"is split across multiple lines.")

Q2. How would you write the following arithmetic


expression in Python?

Ans 4/(3*(r+34)))-(9*(a+b*c))+(3+d*(2+a))/(a+b*d)

Q3. What does a conversion from a float to an integer do


with the fractional part of the float value? Does the
int(value) function change the variable value?
Ans When a float is converted to an integer in Python, the
fractional part is discarded (truncated). This means the
number is rounded towards zero.
Example;
print(int(5.7)) # Output: 5
print(int(-3.9)) # Output: -3
No, the int(value) function does not change the original
variable. Instead, it creates and returns a new integer value.
Example;
num = 7.8
print(int(num)) # Output: 7
print(num) # Output: 7.8 (original
variable
remains
unchanged)

Q4. What is the UNIX epoch?


Ans The UNIX epoch is the starting point for measuring time in
many computer systems and programming languages. It is
defined as 00:00:00 (midnight), Coordinated Universal
Time (UTC), on January 1, 1970.
Key Points:
 Epoch Time: The number of seconds that have elapsed
since this reference point (ignoring leap seconds).
 Why 1970? It was chosen as a convenient reference for
the early development of UNIX systems.
 Usage: Commonly used in timestamps, like in
programming, file systems, and databases.
Example;
import time
print(time.time()) # Current time in seconds
since the
UNIX epoch
Q5. What does time.time() return?
Ans The time.time() function in Python returns the current time
as the number of seconds (including fractions) since
the UNIX epoch (January 1, 1970, 00:00:00 UTC).
The returned value is a float.
Example;
import time
print(time.time()) #
Output:1699999999.123456
(example value)

Q6. How do you obtain the seconds from the returned


value?

Ans To extract only the whole seconds from the returned value,
use the int() function to truncate the fractional part:

Example;

Import time

seconds = int(time.time())

print(seconds) # Output: 1699999999 (example


value)

Q7. What is Type conversion in python?

Ans Type conversion in Python refers to changing a value from


one data type to another. There are two types of type
conversion:

Implicit Type Conversion (Type Coercion)

Python automatically converts one data type to another


during operations when needed.

Example;

result = 5 + 3.2 # int + float -> float

print(result) # Output: 8.2

Explicit Type Conversion (Type Casting)


Typecasting is when you convert a variable value from one
data type to another using Python's built-in functions.

Common Type Conversion Functions:

Function Converts To
int(x) Integer
float(x) Float
str(x) String
bool(x) Boolean
list(x) List
tuple(x) Tuple
set(x) Set

Examples:

 Convert Float to Int (Truncates fractional part):

Code:

num = 5.6

print(int(num)) # Output: 5

 Convert Int to String:

Code:

num = 10

print(str(num)) # Output: '10'

 Convert String to Float:

Code:

num = "3.14"

print(float(num)) # Output: 3.14

 Convert List to Tuple:


Code:

my_list = [1, 2, 3]

print(tuple(my_list)) # Output: (1, 2, 3)

Important: Not all conversions are valid. For example,


trying to convert a non-numeric string to a number will result
in an error:

Example;

print(int("hello")) # Raises ValueError

Q8. Define Formatted I/O.

Ans Formatted output converts the internal binary representation


of the data to ASCII characters which are written to the
output file.

Formatted input reads characters from the input file and


converts them to internal form.

Formatted input/output is very portable. It is a simple


process to move formatted data files to various computers,
even computers running different operating systems, if they
all use the ASCII character set.

print() and input() are examples for formatted input and


output functions.

Q9. Define .split() function.

Ans It breaks the given input by the specified separator.

OR

The .split() method in Python is a way to break a string into


smaller parts (pieces) and store them in a list. You can tell
Python where to break the string by giving it a specific
character or symbol (called a "separator"). If you don’t
provide a separator, Python will break the string wherever
there’s a space.

Syntax; input().split(separator)

Example;

text = "Python is fun"

result = text.split()

print(result)

Output:

['Python', 'is', 'fun']

Q10. What are the print parameters?

Ans The print() function in Python is used to display output on


the screen. It has several parameters that allow
customization of how the output is displayed.

Parameters

1. sep
o A string used to separate multiple objects.
o Default is a single space ' '.
o Example: print("Hello", "World", sep='-') will print Hello-
World.
2. end
o A string added at the end of the printed output.
o Default is a newline \n, which moves the cursor to the
next line.
o Example: print("Hello", end='!') will print Hello!.
3. file
o Specifies where to send the output.
o Default is sys.stdout, which means the output will go to
the console.
o Example: You can write to a file using
file=open('output.txt', 'w').
4. flush
o A boolean that specifies whether to forcibly flush the
output buffer.
o Default is False.
o Example: print("Loading...", flush=True) ensures the
output is immediately visible.

Q11. What happens if the user enters 5a when


executing the following code?

radius = eval(input("Enter a radius: "))

Ans It will give a SyntaxError because eval() attempts to evaluate


the input string as a Python expression, and 5a is not valid
Python syntax.

Q12. What are libraries?

Ans libraries are collections of pre-written code that provide


specific functionality. These libraries help developers avoid
reinventing the wheel and enable them to build applications
more efficiently by using ready-made modules and functions.

Types of Python Libraries

Built-in Libraries
Python has a standard library with essential tools, like:

 math: Mathematical functions.


 datetime: Working with dates and times.
 random: Generating random numbers.

Third-Party Libraries
These are created by the Python community and installed
using tools like pip. Popular examples include:

 numpy: Numerical computing.


 pandas: Data manipulation and analysis.
 matplotlib: Data visualization.

Custom Libraries
Developers can create their own libraries to organize
reusable code for specific projects.

Example;

import math #math is library

print(math.sqrt(16)) # Output: 4.0

Q13. What are selection statements?

Ans The selection statements are also known as Decision control


statements or branching statements. The selection
statement allows a program to test several conditions and
execute instructions based on which condition is true.

Python has several types of selection statements:

One-Way if Statement

The simplest form of a selection statement where a block of


code is executed only if the condition is True.

Syntax;

if condition:

# code to execute

Example;

age = 18

if age >= 18:

print("You are eligible to vote.")

Two-Way if-else Statement


Used when there are two possible outcomes — one block
executes if the condition is True, and another block executes
if the condition is False.

Syntax;

if condition:

# code to execute if condition is True

else:

# code to execute if condition is False

Example;

num = 5

if num % 2 == 0:

print("Even")

else:

print("Odd")

Multi-Way if-elif-else Statement

Used for multiple conditions. It checks each condition in


order until one evaluates to True. If none are True, the else
block is executed.

Syntax;

if condition1:

# code if condition1 is True

elif condition2:

# code if condition2 is True


else:

# code if none of the above conditions are


True

Example;

score = 85

if score >= 90:

print("Grade: A")

elif score >= 80:

print("Grade: B")

else:

print("Grade: C")

Nested if Statements

An if statement inside another if statement. Used when


decisions depend on multiple conditions.

Syntax;

if condition1:

if condition2:

# code to execute if both conditions are


True

Example;

num = 15

if num > 10:

if num % 5 == 0:
print("Number is greater than 10 and
divisible” “by 5")

Conditional Expressions (Ternary Operator)

A shorthand way of writing if-else in a single line.

Syntax;

value = true_value if condition else false_value

Example;

num = 8

result = "Even" if num % 2 == 0 else "Odd"

print(result)

Q14. What is Pascal case, Camel case and Snake case?

Ans Pascal case, camel case, and snake case are different ways
of writing compound words or identifiers, especially in
programming, to make them readable and maintainable.
Here’s what each one means:

Pascal Case:

The first letter of each word is capitalized, with no spaces or


underscores between the words.

Example;

MyVariableName = 42

Camel Case:

Similar to Pascal case, but the first letter of the first word is
lowercase, and the first letter of each subsequent word is
capitalized.

Example;
myVariableName = 42

Snake Case:

All letters are lowercase, and words are separated by


underscores (_).

Example;

my_variable_name = 42

Summary of Python's Convention:

 Snake case is the preferred convention in Python for


variables, functions, and methods.
 Camel case and Pascal case are typically used in other
programming languages, like JavaScript (camelCase) or C#
(PascalCase for classes).

Q15. How do you generate a random integer 0 or 1?

Ans You can generate a random integer that is either 0 or 1 in


Python using the random.randint() function like this:

import random

i = random.randint(0, 1)

You might also like