Python 3: 1.code
Python 3: 1.code
print() function
1.Code:
print("Hello")
O/P:
Hello
2.Code:
print("Hello" + "World")
O/P:
HelloWorld
3.Code:
print("Hello" + " World")
O/P:
Hello World
4.Code:
print('Hi')
O/P:
Hi
5.Code:
print("Hello" * 10)
O/P:
HelloHelloHelloHelloHelloHelloHelloHelloHelloHello
6.Code:
print(10)
print(2.7)
print(True)
print(False)
O/P:
10
2.7
True
False
Variables
Variables need not be declared first in python. They can be used directly. Variables in python are case
sensitive as most of the other programming languages.
1.Code:
a = 5
b = 10.1
c = True
d = "Python"
#note that variables are printed separated by a single space
print(a, b, c, d)
O/P:
5 10.1 True Python
2.Code:
a = "Hi"
print(a)
a = 10
print(a)
a = 2.5
print(a)
a = False
print(a)
O/P:
Hi
10
2.5
False
input() function
Syntax : input([prompt])
prompt (Optional) - a string that is written to standard output (usually screen) without trailing newline
1.Code:
x = input()
print(x)
O/P:
1
1
2.Code:
x = input("Enter a number : ")
print(x)
O/P:
Enter a number : 1
1
3. Code:
x = input("Enter your name : ")
y = input("Enter your favourite subject : ")
print(x + " likes " + y)
O/P:
Enter your name : Venkat
Enter your favourite subject : Physics
Venkat likes Physics
Basic arithmetic operators in Python
Code:
x = 10
y = 3
z = x + y
print(z)
z = x - y
print(z)
z = x * y
print(z)
z = x / y
print(z)
z = x // y
print(z)
z = x % y
print(z)
z = x ** y
print(z)
O/P:
13
7
30
3.3333333333333335
3
1
1000
Convert the input string taken with input() function
1.Code: to get two numbers from user and print sum
x = input("Enter first number : ")
y = input("Enter second number : ")
print(x+y)
O/P:
Enter first number : 2
Enter second number : 3
23
The input function takes input as a string. So "2" and "3" are concatenated, not added. To add the inputs the
string has to be converted into an integer or float. We have the functions int(), float() and bool() to convert a
string to integer, floating point and boolean data types respectively.
2.Code:
x = input("Enter first number : ")
y = input("Enter second number : ")
print(int(x)+int(y))
O/P:
Enter first number : 2
Enter second number : 3
5
Exercise 1
1. Find and print the area and the circumference of a circle, taking radius as input from the user (use 3.14 as pi
value)
2. Convert temperature in Celsius (taken as input from the user) to Fahrenheit and print
3. Print the sum of first n natural numbers, taking n (integer) as input from the user
4. Write a program that takes the numbers of overs played and runs scored so far by a team, and prints the
Run Rate or Runs Per Over
5. Write a program that takes two integers and prints the arithmetic mean, geometric mean and harmonic
mean of the two numbers (Hint: x ** 0.5 prints the square root of a number)
Solution to Exercise 1
1.
radius = float(input("Enter radius : "))
c = 2*3.14*radius
a = 3.14*radius*radius
print("Circumference is ", c)
print("Area is ", a)
2.
celsius = float(input("Enter temperature in celsius : "))
fahrenheit = (9/5)*celsius + 32
print("Temperature in fahrenheit is ", fahrenheit)
3.
n = int(input("Enter n : "))
sum = int((n*(n+1))/2)
print(sum)
4.
overs = int(input("Enter the number of overs played : "))
runs = int(input("Enter the number of runs scored : "))
runRate = runs / overs
print(runRate)
5.
a = int(input("Enter first integer : "))
b = int(input("Enter second integer : "))
am = (a + b) / 2
gm = (a * b) ** 0.5
hm = (2 * a * b) / (a + b)
print("Arithmetic mean : ", am)
print("Geometric mean : ", gm)
print("Harmonic mean : ", hm)
Operators and operator precedence
Arithmetic operators : + - * / // % **
Relational operators: > < == != >= <=
Logical operators: and or not
Bitwise operators: & | ~ ^ >> <<
Assignment operators: = += -= *= /= //= **= &= |= ^= >>= <<=
Identity operators: is is not
Membership operators: in not in
O/P:
Enter first number : 4
Enter second number : 6
a is 6, b is 4
2. Code:
a = 5
a = a<<1
print(a)
O/P:
10
3. Code:
a = 60
a = a>>1
print(a)
O/P:
30
4. Code:
#find factorial of a given number
n = int(input("Enter a number : "))
f = 1
for i in range(1, n+1, 1):
f = f * i
print(f)
O/P:
Enter a number : 5
120
continue, break and pass Statements in Loops
break statement - brings control out of the loop
Example
i = 0
for letter in 'PythonProgramming':
if letter == 'n':
break
i += 1
print('Current Letter : {0}, i : {1}'.format(letter, i))
O/P:
Current Letter : n, i : 5
continue statement - returns control to the beginning of the loop
Example
i = 0
s = 'PythonProgramming'
for letter in s:
if letter == 'o' or letter == 'm':
continue
i += 1
print(len(s),i)
O/P:
17 13
pass statement – used to write empty loops (also used for empty control statements, functions and classes)
Example
s = 'PythonProgramming'
for letter in s:
pass
print(letter)
O/P:
g
Function
Syntax:
def function_name (parameters):
#statements
A function may or may not return a value. return statement is used to return a value from a function. If there
is no return statement, or there is no value or expression followed by return keyword, then None object is
returned. The syntax of return statement is,
return [expression_list]
Example:
def is_positive(n):
if n>0:
return 1
elif n<0:
return -1
else:
return 0
print(is_positive(5))
print(is_positive(-5))
print(is_positive(0))
O/P:
1
-1
0
Formatted String Literals (f-strings)
Known as Literal String Interpolation or more commonly F-strings
To create an f-string prefix the string with the letter ‘f’.
1. Code:
first = 'venkat'
last = 'raman'
print(f'Full name is {first} {last}')
O/P:
Full name is venkat raman
2. Code:
a = int(input("Enter a : "))
b = int(input("Enter b : "))
c = a + b
print(f"Sum of {a} and {b} is {c}")
O/P:
Enter a : 3
Enter b : 5
Sum of 3 and 5 is 8
Formatted Output Using format() method
The syntax of format method is,
template.format(p0, p1, …, k0=v0, k1=v1, …)
p0, p1, … are positional arguments
k0, k1, … are keyword arguments with values v0, v1, .. respectively
format() method takes any number of parameters. But, is divided into two types of parameters,
positional parameters – list of parameters that can be accessed with index of parameter inside curly braces
{index}
keyword parameters – list of parameters of type key=value, that can be accessed with key of parameter inside
curly braces {key}
The format() method returns the formatted string
Example 1:
x = int(input("Enter first number : "))
y = int(input("Enter second number : "))
z = int(input("Enter third number : "))
max=x
if max<y:
m=y
if max<z:
m=z
print("The maximum of {0}, {1} and {2} is {3}".format(x,y,z,m))
O/P:
Enter first number : 3
Enter second number : 5
Enter third number : 8
The maximum of 3, 5 and 8 is 8
Example 2:
name = "venkat"
mobileBalance = 500.55
print("Hello {0}, your mobile balance is {1:8.2f}".format(name,mobileBalance))
O/P:
Hello venkat, your mobile balance is 500.55
Exercise 2
1. Write a program to check whether a number is even or odd
2. Print the first n prime numbers
3. Print Floyd’s triangle
Eg: for n=4,
1
23
456
7 8 9 10
4. Print the sum of digits of a given number
5. Store the reverse of a number taken as input, and print
6. Check if a number is palindrome, return True if it is, False if it is not
7. Print the total number of circular prime numbers from 2 to n, taking n as input (a number is circular prime if
it is a prime number and all its cyclic permutations are prime too. Eg: 197 is prime, 719 is prime, and 917 is
also prime, therefore 197 is a circular prime)
8. Write two functions, first one computes nCr, second one computes nPr
Advanced Exercise 1
1. A number is even if the number of 1’s in its binary form is even. Print the first n even numbers (taking n as
input from the user)
Input Format:
Single integer n
Output Format:
All even numbers up to n separated by comma
Sample Input and Output:
10
3, 5, 6, 9, 10, 12, 15, 17, 18, 20
2. Given a positive integer, find the number of occurrences of a given digit in that number.
The input shall consist of two positive numbers, say num1 and num2 such that 0<=num1<=9, and
0<=num2<=999999999.
The function findDigitOccurrence should return an integer variable with value equal to the count of the
occurrences of num1 in num2.
Function Signature:
def findDigitOccurrence(num1, num2):
Function return value:
An integer corresponding to number of occurrences of num1 in num2
Example:
If num1=2, num2=123228, then the function should return 3
If num1=5, num2=4150512505, then the function should return 4
3. Suppose an ant is trapped in a maze with only one way out. The maze is a cubic-lattice like structure of
dimension NxNxN (Length=Breadth=Height=N). The way is the left-bottom most point and the way out is the
right top-most point (along the principal diagonal). The below picture shows the maze for N=2,
Assuming the ant only moves right, forward or upwards along the grids of the maze, calculate the total
number of ways in which the ant can escape. Mathematically right, forward and upward are defined as
positive changes in co-ordinates on x, y and z axes respectively
Example: For, N=1 the grid structure and solution is shown below:
Input Output
1 6
2 90
Solution to Exercise 2
1.
def isEven(n):
if n&1==0:
print("{0} is even".format(n))
else:
print("{0} is odd".format(n))
2.
def isPrime(n):
if (n <= 1):
return False
if (n <= 3):
return True
if (n % 2 == 0 or n % 3 == 0):
return False
i = 5
while(i * i <= n):
if (n % i == 0 or n % (i + 2) == 0):
return False
i = i + 6
return True
n = int(input("Enter n : "))
i = 2
count = 0
while count!=n:
if isPrime(i)==True:
print(i, end=" ")
count += 1
i += 1
3.
def floydTriangle(n):
s = 1
for i in range(1, n+1):
j = 1
while j <= i:
print(s, end = " ")
j += 1
s += 1
print(end = "\n")
x = int(input("Enter n : "))
floydTriangle(x)
4.
def getSum(n):
sum = 0
while(n > 0):
sum += int(n % 10)
n = n // 10
return sum
5.
def reverse(n):
rev = 0
while(n > 0):
a = n % 10
rev = rev * 10 + a
n = n // 10
return rev
6.
def isPalindrome(n):
divisor = 1
while (n / divisor >= 10):
divisor *= 10
while (n != 0):
leading = n // divisor
trailing = n % 10
if (leading != trailing):
return False
n = (n % divisor) // 10
divisor = divisor / 100
return True
7.
def isPrime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i = i + 6
return True
def rotate(n):
d = countDigits(n)
rem = n % 10
rem = rem * (10 ** (d-1))
n //= 10
n += rem
return n
def countDigits(n):
digit = 0
while n != 0:
digit += 1
n //= 10
return digit
def isCircularPrime(n):
d = countDigits(n)
i = 0
while i < d:
if isPrime(n) == True:
i += 1
else:
break
n = rotate(n)
if i == d:
return True
else:
return False
n = int(input("Enter n : "))
i = 2
count = 0
while i < n:
if isCircularPrime(i) == True:
count += 1
i += 1
print(count)
8.
def fact(n):
f = 1
for i in range(1, n + 1, 1):
f = f * i
return f
def nPr(n,r):
return int(fact(n)/fact(n-r))
def nCr(n,r):
return int(nPr(n,r)/fact(r))
i = 0
c = 0
x = int(input())
while c != x:
if count(i) % 2 == 0:
print(i, end = " ")
c += 1
i += 1
2.
def findDigitsOccurence(num1, num2):
count = 0
t = num2
while t > 0:
r = t % 10
if r == num1:
count += 1
t = t // 10
return count
3.
def fact(n):
f=1
for i in range(1,n+1):
f = f * i
return f
n = int(input())
x = fact(3*n)
y = fact(n)
i = 1
while i <= 3:
x = x / y
i += 1
print(int(x))