0% found this document useful (0 votes)
47 views4 pages

Python Basics: Q&A and Code Examples

The document discusses print functions in Python and provides examples of programs that: 1. Use the print function to output text with different end arguments, demonstrating how the end argument determines the end character printed. 2. Provide code snippets that take user input for variables like name, numbers, etc. and then perform calculations like calculating the sum, area, BMI index through simple arithmetic operations and output the results. 3. Explain concepts like dynamic typing in Python and show code to handle type conversion from one data type to another while performing calculations like converting between distance units.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views4 pages

Python Basics: Q&A and Code Examples

The document discusses print functions in Python and provides examples of programs that: 1. Use the print function to output text with different end arguments, demonstrating how the end argument determines the end character printed. 2. Provide code snippets that take user input for variables like name, numbers, etc. and then perform calculations like calculating the sum, area, BMI index through simple arithmetic operations and output the results. 3. Explain concepts like dynamic typing in Python and show code to handle type conversion from one data type to another while performing calculations like converting between distance units.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COMPUTER SCIENCE

186 WITH PYTHON X


print()function then the print) will
Ifyouexplicitly give anend argument witha argument, c.g., the code print the line
and end it with the string specified with the end
end = $')
print("Myname isAmit. ",
print("Iam 16 years old. ")

will print output as This time the print(0ended the line with
given end character. which is'S here
old.
My name is Amit. $I am 16 years
NOTE
So theend argumentdetermines the
end character that will be
printed at the endof print line. In print() function, the default
value of end
Code fragment 1
newline argument is
character (\n') and of
a, b= 20, 30 sep argument, it is space ()
Notice first print
statement has end
print ("a =", a, end = )
set as a space
print ("b =", b)

Now the output produced will be like:


a = 20 b= 30 This spaceis becaUse of end=''in print( )

Check
Point
The reason for above output is quite clear. Since there is
end character given as a space (1.e., end = ) in first print
74 statement, the newline (\n') character is not appended at
1. What is a variable ?
the end of output generated by first print statement.
Thus the output-position-cursor stays on the same line.
2. Why is a variable called symbolic
variable ? Hence the output of second print statement appears in the
3. Create variables for the following
same line. Now can you predict the output of following
() to hold a train number code fragment ?
(ii) to hold the name of a subject Name ='Enthusiast'
(iii) to hold balance amount in a bank print ("Hello", end = )
accournt
print (Name)
(iv) to hold a phone number print ("How do you find Python ")
4. What do you mean by dynamic typing
of avariable ? What is the caution you Well, youguessed it right. O It is:
must take care of ?
Hello Enthusiast
5. What happens when you try to access
the value of an undefined variable ? How do youfind Python ?
6. What is wrOng with the following
statement ?
In Python you can break any statement by putting a \ i5
the end and pressing Enter key, then completing he
Number = input ("Number") statement in next line. For example, following statement is
Sqr = Number*Number
perfectly right.
7. Write Python code to obtain the
balance amount. print ("Hello", \ The backslaslh at theend means
that the statement is still
8. Write code to obtain fee amount and end= ) continuing in next line
then calculate fee hike as 10% of fees
(i.e., fees x 0.10). Nowconsider following sample programs.
Chopter7: PYTHON FUNDAMENTALS

187
7.1 Write a program to input a welcome message and print it.

Irogram message = input (""Enter


welcome message : ")
print("Hello,, message)
Sample Run
Fnter elcome message : Python we lComes you to its
uello. Python welcomes you to its beautiful world
beautiful world.

7.2 Proaram to obtain three numbers and print their sum.


# to input 3 numbers and print their sum
rogram num1 = int( input("Enter number 1: "))
num2 = int( input("Enter number 2: "))
num3 = int( input("Enter number 3: "))
Sum = num1 + num2 + num3 Enter number 1:7
print(""Three numbers are :", num1, num2, num3) Enter number 2 : 3

print("Sumis : ", Sum) Enter number 3: 13


Three numbers are : 73 13
The output produced by aboveprogram is as Sum is : 23
shown on right.

7.3 Program to obtain length and breadth of a rectangle and calculate its area.
am
grar # to input length and breadth of a rectangle and calculate its area
length = float( input("Enter length of the rectangle: "))
breadth = float( input ("Enter breadth of the rectangle:"))
area = length * breadth

print ("Rectangle specifications ")


print ("Length =", length, end = ') Enter length of the rectangle : 8.75
print ("breadth = ", breadth) Enter breadth of the rectangle : 35.0
print ("Area =", area) Rectangle specifications
Length = 8.75 Breadth = 35.0
The output produced by above program is as Area = 306.25
shown here.

7.4 Program to calculate BMI (Body Mass Index) of aperson.


Body Mass Index is asimple calculation using a person's height and weight.
The formula is BMI = kg/m where kg is a person's weight in kilograms and m´ is their height in
rogram
metres squared.
# to calculate BMI = kg /m square
weight_in kg = float (input ("Enter weight in kg : "))
meters : "))
height_ in meter = float (input ("Enter height in
(OMPUTER SCIENCE WTH PIHCi
188
height_in meter)
(height in meter
bmi =weight in kg /
print ("BMI is : ", bmi)
is as shown below:
The outpul produced by above program
Enter weight in ka : 66
Enter height in meters : 1.6
BMI is: 25.781249999999996

and print its cube.


7.5 Writea program to input a number
:"))
rogram num = int(input ("Enter a number
cube =num num * num Enter a number : 7
print("Number is", num) Number is 7
print ("Its cube is", cube) Its cube is 343

here.
Theoutput produced by above program is as shown
miloc)
7.6 Write a program to input a value in kilometres and convert it into miles (1 km = 0.621371

rogram km = int( input ("Enter kilometres: ")) Sample Run :


miles = km *.621371 Enter kilometres: 20
print("Kilometres :", km) Kilometres : 20
print ("Miles :", miles) Miles : 12.42742

7.7 Write a program to input a value in tonnes and convert into quintals and kilograms.
(1 tonne 10 quintals 1tonne =1000kgs, 1quintal = 100kgs)
rogram

tonnes =float( input("Enter tonnes :"))


quintals= tonnes * 10
Sample Run :
kgs = quintals * 100
print("Tonnes:", tonnes) Enter tonnes:2.5
print ("Quintals :", quintals) Tonnes: 2.5

print( "Kilograms:", kgs) Quintals: 25.0


Kilograms : 2500.0
7.8 Write aprogram to enter a small poem or poem verse and
print it.
poem = input ("Enter a small poem: ")
Irogram
print ("The poem youentered")
print (poem)
Sample Run :
Enter a small poem :
sings the tune without"Hope"
is the thing with
the words- And never feathers- That perches in the soul- Ald
The poem you entered stops at al| -EMILY
DICKINSON
"Hope" is the
thing wi th feathers- That
out the words- And perches in the soul- And sings the
never stops at all -EMILY tune
DICKINSON
Chapter 7
PYTHON FUNDAMENTALS

189
7.9 Write a program to input two
numbers and swap them.
n1 = int( input ("Enter
rogram number 1 :"))
n2 = int( input ("Enter
number :"))2 Sample Run:
print ("Original numbers :", n1, n2)
n1, n2 = n2, n1 Enter number 1: 17
Enter number 2: 28
print("After swapping :", n1, n2) Original numbers : 17 28
After Swapping : 28 17
r 10 Writea program to input three numbers and
swap them as this : 1st
nd number becomes the 3rd
number and the 3rd number becomesnumber becomes the 2nd number,
the first number.
rogram
X= int (input("Enter number 1:"))
y =int( input("Enter number 2 :") ) Sample Run :
z = int( input("Enter number 3 :")) Enter number 1:6
print("Original numbers:", x, y, z) Enter number 2: 11
X, y, z = y, Z, x Enter number 3: 9

print("After swapping :", x, y, z) Original numbers : 6 11 09


After Swapping: 11 9 6

VARIABLES, SIMPLE I/0


Progress In Python 7.3
Start a Python IDE of your choice

Please check the practical component-book - Progress in Computer


Science with Python and fill it there in PriP 7.3 under Chapter 7 after
practically doing it on the computer.
>>><K<

LET US REVISE
APython program cancontain various components like expressions, statements, comments, functions, blocks and indentation.
* Anexpression is a legal combination of symbols that representS a value.
Astatement is aprograming instruction.
* Comments are non-executable, additional information added in program for readability.
* In Python, comments begin with a # character.
* Comments can be single-line comment. multi-line comments and inline commnents.
* Function is anamed code that can be reused with a program.
A block/suitelcode-block is aaroun of statements that are part of another statemen.
*Blocks are represented through indentation.
Avariable in Python is defined only when some value is assigned to t.
hold values of different types at different times.
. osupporIS dynamic tvping ie.. a varigble can
always returns a string type of value.
pu s used to obtain input from user : it
Ouput is generated throuah printí )(by callingprint function) statenen.

Common questions

Powered by AI

Inline comments in Python, written with a '#' character, add single-line annotations next to code, providing explanations or clarifications. These comments can improve code readability by explaining non-obvious parts of the code or indicating the purpose of complex operations directly alongside the code, which is particularly useful for collaborative environments or when revisiting code after time has passed. However, excessive or redundant comments could clutter the code, and incorrect comments might mislead future developers. Therefore, it's crucial to ensure that comments are concise, accurate, and genuinely add value to understanding the code .

In Python, a code block, also known as a suite, is a group of statements that execute as a unit or are part of a control structure like loops or conditional statements. Code blocks are defined by indentation levels rather than braces or keywords, making correct indentation critical for Python’s structure and execution. Blocks enhance readability and organization, delineating scope and structure of code logic, which can prevent errors and improve maintainability. This structural clarity aids in ensuring code behaves correctly as intended without accidental misalignment or execution errors .

Accessing an undefined variable in Python results in a NameError, as the variable has no value or type until it is defined with an assignment. To mitigate issues, always initialize variables before use. Use descriptive variable names and ensure there is a controlled flow that avoids premature access. For error handling, try-except blocks can capture mistakes gracefully. Also, proactively using tools like static code checkers can flag potential issues in variable handling before they become runtime errors .

In Python, input is typically received as a string type. To handle input as different data types, explicit type conversion is necessary. This involves using functions like int(), float(), or other conversion functions to cast the input string to the required data type before using it in operations that require that type. For example, if a program requires numeric calculations, convert the string input to an integer or a float. It is also good practice to validate and handle exceptions for type conversion to avoid runtime errors .

Python's print() function can produce structured output by using the 'sep' and 'end' arguments. The 'sep' argument allows specifying a separator between arguments, defaulting to a space, which can be customized for structured data output. For instance, using sep=',' will separate printed arguments with a comma. The 'end' argument customizes what is printed at the line end, defaulting to a newline but could be a space or any string to control line continuation or format multiple lines in one. For example, print('Name:', name, 'Age:', age, sep=', ', end='\n---\n') would produce a comma-separated list with a custom line end .

To calculate the Body Mass Index (BMI) in Python, first prompt the user to input their weight in kilograms and their height in meters. Use these inputs to compute BMI with the formula: BMI = weight / (height^2). Convert the inputs to appropriate numeric types if necessary, such as using 'float'. The program would look like this: weight_in_kg = float(input('Enter weight in kg: ')), height_in_m = float(input('Enter height in meters: ')), followed by bmi = weight_in_kg / (height_in_m ** 2). Finally, print the BMI value using print('BMI is:', bmi).

The 'end' argument in the Python print() function determines the character or string that ends a printed line. By default, the 'end' character is a newline ('\n'), which causes each print call to output on a new line. However, you can specify a different string for the 'end' argument to change this behavior. For example, specifying end=' ' will result in the following print statement appearing on the same line as the previous one, separated by a space. This can be used to create continuous output within the same line instead of breaking into separate lines for each print statement .

Swapping three variables in Python can be done simultaneously using sequence unpacking. For instance, if you have variables x, y, and z, you can swap them such that x becomes y, y becomes z, and z becomes x by writing the swap as x, y, z = y, z, x. This differs from swapping two variables, where you would write x, y = y, x. Simultaneous assignment allows for these swaps to occur in a single line without needing a temporary variable, leveraging Python's tuple assignment to handle the value swap efficiently .

Python's dynamic typing means that variables do not require a fixed data type at the time of their creation. They can hold values of different types at different times during program execution. This flexibility, while convenient, requires caution to avoid errors from unexpected type changes, especially when performing operations that expect operands of a specific type. It also emphasizes the importance of proper documentation and testing to ensure that code behavior remains consistent even when variable types change dynamically .

To convert a length from kilometres to miles in Python, prompt the user for the kilometre input, convert it to a float, and multiply by the conversion factor 0.621371. Example code: km = float(input('Enter kilometres: ')), miles = km * 0.621371, print('Miles:', miles). The conversion factor 0.621371 translates kilometres to miles, allowing the computation to output the equivalent distance in miles .

You might also like