L2:Python
L2:Python
as elif if or yield
1] Static initialization
2] Input/Enter any two numbers from user
3] Swap using function
In python programming, there is a simple direct construct to swap variables. The following code
does the same as other programming language without the use of any temporary variable. In
Python, the simultaneous assignment statement offers an elegant alternative.
Same technique also works for swap three numbers.
Swapping is very common operation in sorting and other problems.
30/07/2018 Debajyoti Ghosh, Asst. Prof, BML Munjal University 5
Swap two numbers without temporary/third variable
The left side are variables; the right side are values. Each value is
assigned to its respective variable in the same sequence they appear.
All the expressions on the right side are evaluated before any of the
assignments. So when we write x, y = 2, 3, then 2 is assigned to x and
3 is assigned to y.
31/07/2018 Debajyoti Ghosh, Asst. Prof, BML Munjal University 6
Temperature conversion from Celsius to Fahrenheit
Write and run a Python program that asks the user(from the console) for a temperature in
Celsius degree and converts and displays the temperature in Fahrenheit.
The formula for the conversion is as follows:
fahrenheit = (9 / 5) * celsius + 32
Here is sample runs of the program:
>>> temp_conv()
Input the temperature in Celsius: 0
0 C = 32.0 F
>>> temp_conv()
Input the temperature in Celsius: 100
100 C = 212.0 F
>>> temp_conv()
Input the temperature in Celsius: 43
43 C = 109.4 F
7
31/07/2018 Debajyoti Ghosh, Asst. Prof, BML Munjal University
Temperature conversion from Celsius to Fahrenheit
def temp_conv():
tempC = eval(input("Input the temperature in Celsius: "))
tempF = tempC * (9.0/5.0) + 32.0
# tempF = 9/5 * tempC + 32 also works
print (tempC, " C = ", tempF, " F")
Another built-in Python function eval is "wrapped around" the input function.
The built-in function eval returns a result of the evaluation of a Python
expression. eval is short for "evaluate“. One need to eval the input when you
want a number instead of some text (a string).
A sample run
>>> circle()
Enter a value for radius: 20
The area for the circle of radius 20 is 1256.6370614359173
30/07/2018 Debajyoti Ghosh, Asst. Prof, BML Munjal University 9
Computes area and circumference of circle
import math
def circle(r):
#r=eval(input("Enter a value for radius: ")) - no need, the line start with # is
a comment line
circumference = 2 * math.pi * r
area = math.pi * r * r
print (circumference, area)
A sample run
>>> circle(20)
125.66370614359172 1256.6370614359173
30/07/2018 Debajyoti Ghosh, Asst. Prof, BML Munjal University 10
Home work
Write a complete Python program that takes as input the coordinates of
two points in the 2D plane and then compute and prints out the
Euclidian distance between them.