Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
29 views

Python Programming

Uploaded by

rehaanshaik303
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Python Programming

Uploaded by

rehaanshaik303
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Python Programming

Learning Objectives:
 Features of Python
 Writing and executing commands in Python
 How to exit Python shell
 Operators in Python
 Variables on Python
 Using input() function for user inputs
 Conditional constructs
 Using for and while loops in Python

Introduction
Python is a high-level programming language which is
open source and object oriented. Python was developed by
Guido Van Rossum in 1991. It is presently owned by Python
Software Foundation (PSF). Guido Van Rossum

Features of Python
• Python is an interactive language with simple syntax that allows developers
to write robust programs easily and efficiently.
• Python is an interpreter-based scripting language.
• It supports Graphical User Interface (GUI).
• It is loosely type object-oriented programming language with few keywords
and simple English like structure, therefore easy to learn.
• Python is case-sensitive.
• Python can be written in interactive mode (>>> prompt) or the Python
Integrated Development Learning Environment (IDLE).

Python Software
In order to write programs in Python, we can either use the online compiler or
can download Python on our system.
•Virtual Python Compiler:Click on any one of the following links:
• https://www.programiz.com/python-programming/online-compiler
• https://www.onlinegdb.com/online_python_compiler
• Download python on your system:Click on any one of the following links:
• https://thonny.org/
• https://www.python.org/downloads/
• https://code.visualstudio.com/
1
Writing and executing commands in Python
We can launch Python IDLE by clicking on its icon created on the desktop or by
clicking on the STARTIDLE (Python 3.9 64-bit) option, it always starts up in
the Python Shell.

Python Shell

Simple commands can be directly typed in front of the prompt (>>>) in the Python
shell. Python shell is used to execute single line of code.
Eg:

2
Python IDLE (Integrated Development Learning Environment)
For executing multiple lines of code, we use Python IDLE. Following are the steps
to write and execute a python program in Python IDLE :

1. In Python shell, select FileNew File to open Python Script editor.

2. Write the statements to be executed in the Python Script editor.

3. To execute the program, click on RunRun Module or press F5.

4. Save the file:

3
Note :Files in python are saved with an extension of “.py” or “.pyw”.

5. The Output is displayed on the Python Shell.

How to exit Python Shell

To exit Python Shell, simply type


>>>quit()
or
>>>exit()

A dialog box will appear asking you “Your program is still running ! Do you want
to kill it ?” Click on OK button if you want to quit otherwise click on Cancel
button.
or

Select File  Exit option.


4
Operators in Python
Operators are special symbols used in a programming language to operate on
values and variables.
Python divides the operators in four categories:

• Arithmetic Operators
These are used with numeric values to perform common arithmetic
calculations.
Operator Name Syntax Example

+ Addition x+y >>>6+9


15
- Subtraction x-y >>>9-5
4
* Multiplication x*y >>>6*9
45
/ Division x/y >>>9/2
4.5
// Floor Division x//y >>>9//2
4
% Modulus x%y >>>9%2
1
** Exponentiation x**y >>>9**2
81

• Assignment Operators
These operators are used to assign values to variables.
Operator Syntax Description Example
Let N=15
= N=15 N is assigned a value 15. >>N=15
+= N+=5 orN=N+5 Increases the value of N by 5 >>>N+=5
15
-= N+=5 orN=N+5 Decreases the value of N by 5 >>>N-=5
10

5
Operator Syntax Description Example
Let N=15
*= N*=5 orN=N+5 Multiplies the value of N by 5 >>>N*=5
75
/= N/=5 orN=N/5 Divides the value of N by 5 >>>N/=5
3
//= N//=5 Floor division of N by 5 >>>N//=5
N=N//5 3
%= N%=5 N is assigned the remainder by >>>N%=5
N=N%5 dividing the value of N by 5 0
**= N**=5 N is assigned the value of power >>>N=**5
N=N**5 of N raised to the power of 5 7,59,375

• Relational Operators
These operators are used to compare two values and return a logical value
which is either True or False.

Operator Syntax Description Example


Let x=15 , y=20
== x==y Equal to. >>>x==y
False
!= X!=y Not equal to. >>>x!=y
True
> X>y Greater than. >>>x>y
False
< X<y Less than. >>>x<y
True
>= X>=y Greater than or equal to. >>>x>=y
True
<= X<=y Less than or equal to. >>>x<=y
True

• Logical Operators
6
These operators are used to combine conditional statements and return a
result as either True or False.

Operator Syntax Description Example


and x>5 and x<=10 Returns true if both the >>>10<25 and 5>6
conditions are true. False
or x>5 or x<=10 Returns true if any one of >>>10<25 or 5>6
the conditions is true. True
not not (y==6) Reverses the result, >>>y=15;
returns False if the result >>>not(y==6)
is True True

Variables in Python
Variables are named memory locations whose value may change during the
execution of the program. Some rules for naming variables in Python are given
below:
• A variable name can consist of alphabets, digits and underscore(_).
• A variable name can start with an alphabet/underscore(_)but not a digit.
• A variable name cannot have space in it.
• Keywords are not allowed as a variable name.
• Python is a case-sensitive language, so variables in uppercase as different to
those in lowercase.

Question 1: To display welcome message in Python.


Program :
7
print("welcome to python")

Question2:To calculate the sum of two numbers.


Program:
a=8
b=9

c=a+b

print("Sum is ",c)

Using input() function for User Input


To fetch the value for the user, input() function is used.
Syntax: input(<prompt>)
The input function in Python works as follows:
• When input() function is executed, the program flow stops until the user
submits an input value.
• The prompt is displayed on the output screen to ask a user to enter an input
value. However, this prompt is optional.
• Whatever value is entered by the user as an input, the input() function
converts it into a string. To treat the users input as a numeric value an
explicit conversion is needed, either into an integer or float.

Question3: To accept a name and display welcome message in Python


Program:
a=input("Enter your name")
print("welcome to python", a)

Question 4:To accept two numbers from the user and calculate the sum.
Program:
8
a=int(input("Enter first number"))
b=int(input("Enter second number"))

c=a+b

print("Sum is ",c)

Question 5:To accept length and breadth of a rectangle and print the area
and perimeter.
Program:
L=int(input("Enter length "))
b=int(input("Enter breadth "))

a=L*b
print("Area is ",a)

p=2*(L+b)
print("Perimeter is ",p)

Question 6: To accept two numbers from the user and print the average.
Program:
a=int(input("Enter first number "))
b=int(input("Enter second number "))

avg=(a+b)/2

print("Average is ",avg)

Question 7: To accept two numbers and print the first number raised to the
power of second number.
Program:
a=int(input("Enter a number "))
b=int(input("Enter power "))

c=a**b
print(“Answer is “,c)
Conditional Constructs

9
The order of the execution of the statements in a program is known as the flow of
control. By default, flow of control is sequential which means the statements
written first are executed first in the sequence. However, to change the flow of
control based on a condition, conditional statements are used.

There are three types of conditional statements in Python.


if statement if-else statement if -elif ladder

if statement
if statement checks if the condition given after it is true, then the statement(s)
following the if condition is/are executed. If the condition is false, then the flow of
control is transferred to the next un-idented statement(s).
Syntax :
if <condition>:
Statement(s)

Some rules need to be followed while using if condition in the program. They are:
• if statement must end with a colon (:).
• Statements with in the ‘if’ that needs to be executed if the condition is true
should be indented otherwise the control skips the block of statements inside
it.
• Condition can also be written in parenthesis () but is not mandatory.
• There is no limit of number of statements that can appear under an if block.

Question 8 :Program to accept the age and check if it is greater than or


equalto 18. If yes then print ”Eligible for voting” otherwise the program will
terminate.
Program :
age=int(input("Enter age : "))
if age>=18:
print("Eligible for voting ")
if-else statement
10
In the code given in Question 8, the statements after if will not be executed unless
the condition is true. So in such cases we can use else statement with if statement
to execute a block of code when the condition is false.
Syntax :
if <condition>:
Statement(s)
else:
Statement(s)

Question 9: Program to accept the age and check if it is greater than or equal
to 18. If yes then print ”Eligible for voting” otherwise print “Not eligible for
voting”.

Program:
age=int(input("Enter age : "))

if age>=18:
print("Eligible for voting ")

else:
print("Not Eligible for voting ")

Question 10: To accept two numbers from the user and find the greater of
two numbers.

Program :
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))

if a>b:
print("Greater no. is ",a)
else:
print("Greater no. is ",b)
Question 11: To accept a number from the user and print if it is even or odd.
11
Program :
x=int(input("enter a number"))

if x%2==0:
print("even number")
else:
print("odd number ")

Question 12: To accept a number from the user and check if it positive or
negative number.

Program:
n=int(input("Enter a number : "))

if n>0:
print("Number is positive ")
else:
print("Number is negative ")

Question 13: To accept two numbers from the user and check if they are
equal.

Program:
a=int(input("Enter first number : "))
b=int(input("Enter second number : "))

if a==b:
print("Numbers are equal.")
else:
print("Numbers are not equal.")

if-elif statement Syntax :


This construct is used in situations where a user can if <condition>:
decide among multiple conditions. As soon as one of Statement(s)
the conditions controlling the ‘if’ is true, then the elif <condition>:
statement(s) associated with that ‘if’ are executed, and
Statement(s)
the rest of the ladder is bypassed. If none of the
conditions is true, then the final ‘else’ statement will elif <condition>:
be executed. Statement(s)
12 else:
Statement(s)
Question 14: Program to accept three numbers and display greatest of them.
Program:
a=int(input("Enter first number"))
b=int(input("Enter second number"))
c=int(input("Enter third number"))

if a>b and a>c :


print("Greatest number is ",a)
elif b>a and b>c :
print("Greatest number is ",b)
else:
print("Greatest number is ",c)

Question 15: Program to accept marks in 5 subjects from the user, calculate
the percentage and display the grades based on the following criteria.
Percentage Grade
>85 A
>70 and <=85 B
>60 and <=70 C
>45 and <=60 D
<=45 E

Program:
eng=int(input("Enter marks obtained in English"))
math=int(input("Enter marks obtained in Math"))
sci=int(input("Enter marks obtained in Science"))
dl=int(input("Enter marks obtained in DL"))
soc=int(input("Enter marks obtained in Social Studies"))

per=(eng+math+sci+dl+soc)/5

if per>85:
print("Grade : A")
elif per>70 and per<=85:
print("Grade : B")
elif per>60 and per<=70:
13
print("Grade : C")
elif per>45 and per<=60:
print("Grade : D")
elif per<=45:
print("Grade : E")

Loops in Python
Sometimes there is a need to repeat a set of statements more than once based on a
certain condition. This process of repetition is called loop or iteration in
programming.
A loop, is thus used to repeat a block of statements a specific number of
times. The following loops are available in Python:
for loopwhile loop

forloop
for…. Structure is used when you
want to perform a loop a specific for loop Syntax:
number of times. It uses a counter for counter_variable in (<collection>):
variable which is incremented or
Statement(s)
decremented with each repetition of
the loop.

Here,
• The counter_variable is assigned the first value in the sequence for statement
in the beginning of the loop.
• The range() function is used to create a list containing a sequence of numbers
starting from start and ending with one less than the stop.
range([start],stop,[step])
The start and step parameters are optional. By default , the list starts from 0 and in
every iteration, it is incremented by one but we can specify a different increment
by using the step parameter.
Command Output
>>>range(10) [0,1,2,3,4,5,6,7,8,9]
>>>range(1,11) [0,1,2,3,4,5,6,7,8,9,10]
>>>range(0,30,5) [5,10,15,20,25]
>>>range(0,-9,-1) [0,-1,-2,-3,-4,-5,-6,-7,-8]

14
Question 16: Write a Python program to print all the numbers from 1 to 10.
Program:
for n in range (1,11,1):
print(n)

Question 17: Write a Python program to print first 10 natural numbers in


reverse order.
Program:
for n in range (10,0,-1):
print(n)

Question 18: Program to accept a name from the user and print it 5 times.
Program:
a=input("Enter your name : ")

for n in range (1,6,1):


print(a)

Question 19: Program to print all the even numbers less than 50.
Program:
for n in range (2,50,2):
print(n)

Question 20: Program to print all the odd numbers less than 50.
Program:
for n in range (1,50,2):
print(n)

Question 21: Program to print all the odd numbers less than 50.
Program:
for n in range (1,50,2):
print(n)

whileloop

15
A whileloop executes a block of code repeatedly as long as the test/control
condition of the loop is true. It is ideally suited when the number of iterations are
not known prior to the execution of the loop.

while loop Syntax: Here,


• ‘while’ is a reserved word.
while <collection>: • Condition is checked for true or false, the statements
Statement(s) are executed only if the condition is true.
• At least one statement must be there in the body of the
loop.

Question 22: Program to print all numbers less than 10 using while loop.
Program:
n=1
while n<10:
print(n)
n=n+1

Question 23 : Program to print the all even numbers lessthan 20.


Program:
n=2
while n<20:
print(n)
n=n+2

Question 24 : Program to print the all odd numbers less than 20.
Program:
n=1
while n<20:
print(n)
n=n+2
Question 25 : Program to find the sum of all numbers entered by the user
until the user enters -1.

Program:
n=int(input("Enter a number"))
sum=0
16
while n!=0:
sum=sum+n
n=int(input("Enter a number"))

print("Sum of the numbers is ",sum)

17

You might also like