0% found this document useful (0 votes)
140 views24 pages

Python Programming Basics and Examples

Python is an interpreted, interactive and object-oriented programming language. It incorporates modules, exceptions, dynamic typing and classes. The document then discusses key benefits of Python including its interpretive nature and availability on major operating systems. It also provides examples of writing Python programs to perform tasks like adding numbers, finding the largest number and calculating factorials.

Uploaded by

ashish620516
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)
140 views24 pages

Python Programming Basics and Examples

Python is an interpreted, interactive and object-oriented programming language. It incorporates modules, exceptions, dynamic typing and classes. The document then discusses key benefits of Python including its interpretive nature and availability on major operating systems. It also provides examples of writing Python programs to perform tasks like adding numbers, finding the largest number and calculating factorials.

Uploaded by

ashish620516
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

Python

Python is an interpreter, interactive, object-oriented programming language. It incorporates


modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python
has packages that encapsulate different categories of functionality in libraries (also called
packages). For applying the statistical analysis one often needs sample data.

One of the key benefits of Python Programming is its interpretive nature. The Python interpreter
and standard library are available in binary or source form from the Python website and can run
seamlessly on all major operating systems. Python Programming language is also freely
distributable, and the same site even has tips and other third-party tools, programs, modules and
more documentation.

Benefits of Python Programming Language

 Interpreted language: the language is processed by the interpreter at runtime, like PHP or
PERL, so you don’t have to compile the program before execution.
 Interactive: you can directly interact with the interpreter at the Python prompt for writing
your program.
 Perfect for beginners: for beginner-level programmers, Python is a great choice as it
supports the development of applications ranging from games to browsers to text
processing.

Developed By: Guido Van Rossum

Download Link: [Link]/download/

Writing python program

 Open the editor


 Write the Instruction
 Save it as a file with the file name having the extension .py
 Run the interpreter with the command python program name .py or use idle to run
the program.

Q. Write a program display the message “Hello World”

print("Hello World")

Q. Write a prog. in Python to add two number.

a=int(input("Input the 1st Number"))

b=int(input("Input the 2nd Number"))

c=a+b

1|P ag e ISHWAR PRAKASH


print("Add="+str(c)

or

def add(x,y):

return(x+y)

a=int(input("Input the 1st Number"))

b=int(input("Input the 2nd Number"))

c=add(a,b)

print("Add="+str(c))

Q. Write a program to add two number by function.

def add(x,y):

return(x+y)

a=int(input("Input the 1st Number"))

b=int(input("Input the 2nd Number"))

c=add(a,b)

print("Add="+str(c))

Q. Write a program to input two number and check them which is biggest by if-else.

a=int(input("Input the a"))

b=int(input("Input the b"))

if(a>b):

print("A is biggest")

else:

print("B is biggest")

Q. Write a program to input three number and check them which is biggest by if-else.

a=int(input("Input the a"))

b=int(input("Input the b"))

2|P ag e ISHWAR PRAKASH


c=int(input("Input the c"))

if(a>b and a>c):

print("A is biggest")

else:

if(b>c):

print("B is biggest")

else:

print("C is biggest")

Q. Write a program to input three number and check them which is biggest by using function.

def biggest(a,b,c):

if(a>b and a>c):

print("A is biggest")

else:

if(b>c):

print("B is biggest")

else:

print("C is biggest")

a=int(input("Input the a"))

b=int(input("Input the b"))

c=int(input("Input the c"))

biggest(a,b,c)

Switch Case

def add(a,b):

c=a+b

return c

3|P ag e ISHWAR PRAKASH


def sub(a,b):

c=a-b

return c

def mul(a,b):

c=a*b

return c

def div(a,b):

c=a/b

return c

def default(a,b):

return"INVALID CHOICE"

switcher = {

1:add,

2:sub,

3:mul,

4:div

def switch(choice):

return [Link](choice ,default)(a,b)

print("You can perform \n [Link], \n [Link], \n [Link], \n


[Link]")

choice=int(input("Select Opeartion From: 1,2,3,4:"))

a=int(input("Enter the 1st Number:"))

b=int(input("Enter the 2nd Number:"))

print(switch(choice))

4|P ag e ISHWAR PRAKASH


Loop: A loop statement allows us to execute a statement or group of statements multiple times.

The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of
the program so that instead of writing the same code again and again, we can repeat the same
code for a finite number of times. For example, if we need to print the first 10 natural numbers
then, instead of using the print statement 10 times, we can print inside a loop which runs up to 10
iterations.

Advantage of loops

1) It provides code reusability.

2) Using loops, we do not need to write the same code again and again.

3) Using loops, we can traverse over the elements of data structures (array or linked lists).

Q. Write a program to input a number and get it's factorial.

num=int(input("Input the number"))

count=1

while(count<=10):

t=num*count

print(t,end="\t")

count=count+1

Q. Write a program to input a number and get it's factorial.

num=int(input("Input the number"))

fact=1

count=2

while(count<=num):

fact=fact*count

count=count+1

5|P ag e ISHWAR PRAKASH


print(fact)

Q. Write a program to input a number and get it's factorial by using function.

def factorial(num):

fact=1

count=2

while(count<=num):

fact=fact*count

count=count+1

print(fact)

num=int(input("Input the number"))

factorial(num)

Q. Write a program input the number and displays the message Armstrong or not.

num=int(input("Input the Number"))

arm=0

org=num

while(num>0):

rem=num%10

arm=arm+(rem**3)

num=num//10

if(org==arm):

print("Armstrong")

else:

print("Not Armstrong")

Q. Write a program to input a number and get it's factorial by using for loop.

6|P ag e ISHWAR PRAKASH


num=int(input("Input the number"))

for i in range(1,11):

t=num*i

print(t,end="\n")

Q. Write a program to input a character and convert it into vertical form.

for letter in "ISHWAR":

pass

print(letter)

Continue:

for i in range(1,11):

if(i==5):

continue

print(i, end="\n")

Using recursion

def GCD(x,y):

rem= x%y

if(rem==0):

return y

else:

return GCD(y,rem)

n=int(input("Input the number"))

m=int(input("Input the 2nd Number"))

print("GCD", GCD(n,m))

7|P ag e ISHWAR PRAKASH


Q. Write a program of Fibonacci series using recursion.

def fibonacci(n):

if(n<2):

return 1

else:

return (fibonacci(n-1)+fibonacci(n-2))

n=int(input("Enter the number of terms"))

for i in range(n):

print(fibonacci(i))

Python module:-

Python module is a file that contain some definition and statement. When a
python file is executed directly, it is considered the main module of a program. The main module

may input any number of other modules which may in term import other modules.
But the main module of a Python program can not be imported into other module.

Example:-

# module1

def repeat_x(x):

return x*2

# module2

def repeat_x(x):

return x**2

import module1

import module2

result = repeat_x(10)

8|P ag e ISHWAR PRAKASH


Q. Write a program to show calender.

import calendar

print([Link](2021,6))

Python String:-

The python string data type is a sequence made up of one or more individual
character, where a character could be a letter, digit, white space or any other symbol.

Python trick string and contiguous series of character delimited by single,double


or even triple codes.

Example:-

message= "Ishwar"

for i in message:

print(i)

->For print three times:-

message= "Ishwar"

print(message *3)

->For print one times:-

print("Hello", end= ' ')

print("World")

Search function:-

In the search function we see that when the pattern was present in the stiring, non
was return because the match was done only at the beginning of the string. Such function

store in the RE-module that searches for a pattern anywhere in the string. RE
stands for regular expression. It is a domain specific language that is present as a library

in most of the modern programming language.

9|P ag e ISHWAR PRAKASH


Example:-

import re

string="Ishwar Prakash"

pattern="Prakash"

if [Link](pattern,string):

print("Match Found")

else:

print(pattern, "is not present in the string")

Match Function

import re

string ="She sells sea shells on the sea shore"

pattern1="sells"

if [Link](pattern1, string):

print("Match found")

else:

print(pattern1, " is not present in the string")

pattern2="She"

if [Link](pattern2, string):

print("Match Found")

else:

print(pattern2,"is not present in the string")

Constructor in Python

The constructor is a method that is called when an object is created. This method is defined in
the class and can be used to initialize basic variables.

If you create four objects, the class constructor is called four times. Every class has a constructor,
but its not required to explicitly define it. The constructor is created with the function init.

10 | P a g e ISHWAR PRAKASH
1. Default Constructor

class GeekforGeeks:

# default constructor

def __init__(self):

[Link] = "Default Constructor in Python"

# a method for printing data members

def print_Geek(self):

print([Link])

# creating object of the class

obj = GeekforGeeks()

# calling the instance method using the object obj

obj.print_Geek()

2. Argument Constructor

class ABC():

def __init__(self,val):

print("In Class Method-----")

[Link]=val

print("The value is :",val)

obj=ABC("10")

print([Link])

Destructor in Python

The __del__() method is a known as a destructor method in Python. It is called when all
references to the object have been deleted i.e when an object is garbage collected.
class ABC():

class_var =0 # class Variable

11 | P a g e ISHWAR PRAKASH
def _init_(self,var):

ABC.class_var +=1

[Link]= var

print("The object value is :",var)

print("The value of class variable is :", ABC.class_var)

def _del_(self):

ABC.class_var -=1

print("Destructor")

obj1 = ABC(10)

obj2 = ABC(20)

obj3 = ABC(30)

del obj1

del obj2

del obj3

TURTLE

Turtle is a pre-installed library in Python that is similar to the virtual canvas that we can draw
pictures and attractive shapes. It provides the onscreen pen that we can use for drawing.

The turtle Library is primarily designed to introduce children to the world of programming.
With the help of Turtle's library, new programmers can get an idea of how we can do
programming with Python in a fun and interactive way.

It is beneficial to the children and for the experienced programmer because it allows designing
unique shapes, attractive pictures, and various games. We can also design the mini games and
animation. In the upcoming section, we will learn to various functionality of turtle library

 [Link]( ) It moves the turtle forward by specified steps.


 [Link]( ) It moves the turtle backward by specified steps.

Q. Program to move the turtle forward and then backward after a delay of 2 seconds.

import turtle

12 | P a g e ISHWAR PRAKASH
import time

[Link](50)

[Link](2)

[Link](30)

 turtle. shape( ) It changes the shape of the turtle.


 [Link]( ) It takes a number of degrees which we want to rotate to the left.

Q. Program to change the shape of the turtle, turn it left, and then move forward.

import turtle

import time

[Link]("square")

[Link](45)

[Link](50)

[Link]()

Q. Program to draw the square.

import turtle

import time

[Link](100)

[Link](90)

[Link](2)

[Link](100)

[Link](90)

[Link](2)

[Link](100)

[Link](90)

[Link](2)

13 | P a g e ISHWAR PRAKASH
[Link](100)

[Link](90)

Q. Program to draw a red color rectangle.

import turtle

import time

[Link]("red")

[Link](100)

[Link](90)

[Link](1)

[Link](50)

[Link](90)

[Link](1)

[Link](100)

[Link](90)

[Link](1)

[Link](50)

[Link](90)

Q. Program to draw a green color equilateral triangle.

import turtle

import time

[Link]("green")

[Link](70)

[Link](120)

[Link](2)

[Link](70)

14 | P a g e ISHWAR PRAKASH
[Link](120)

[Link](70)

 pendown () : It draws a line while moving the turtle.


 Penup(): It does not draw the line while moving the turtle.

Q. Program to demonstrate the use of setposition ( ) , pendown( ), and penup( ) method.

import turtle as t

[Link](50,-70)

[Link](50)

[Link]()

[Link](50)

[Link]()

[Link](150)

Q. Program to draw a circle

import turtle

[Link]("red")

[Link](50)

Q. Program to draw a red color thick pen on a yellow background

import turtle

[Link]("yellow")

[Link]("red")

[Link](10)

for angle in range(0,360,30):

[Link](angle)

[Link](100)

Q. Program to draw a circle and fill it with orange color

15 | P a g e ISHWAR PRAKASH
import turtle

[Link]("orange")

turtle.begin_fill()

[Link](100)

turtle.end_fill()

[Link]()

Q. Program to draw car in turtle programming

import turtle

car = [Link]()

# Below code for drawing rectangular upper body

[Link]('#008000')

[Link]('#008000')

[Link]()

[Link](0,0)

[Link]()

car.begin_fill()

[Link](370)

[Link](90)

[Link](50)

[Link](90)

[Link](370)

[Link](90)

[Link](50)

car.end_fill()

16 | P a g e ISHWAR PRAKASH
# Below code for drawing window and roof

[Link]()

[Link](100, 50)

[Link]()

[Link](45)

[Link](70)

[Link](0)

[Link](100)

[Link](-45)

[Link](70)

[Link](90)

[Link]()

[Link](200, 50)

[Link]()

[Link](49.50)

# Below code for drawing two tyres

[Link]()

[Link](100, -10)

[Link]()

[Link]('#000000')

[Link]('#000000')

car.begin_fill()

[Link](20)

17 | P a g e ISHWAR PRAKASH
car.end_fill()

[Link]()

[Link](300, -10)

[Link]()

[Link]('#000000')

[Link]('#000000')

car.begin_fill()

[Link](20)

car.end_fill()

[Link]()

Tkinter Widgets

There are various controls, such as buttons, labels, scrollbars, radio buttons, and text boxes
used in a GUI application. These little components or controls of Graphical User Interface
(GUI) are known as widgets in Tkinter.

18 | P a g e ISHWAR PRAKASH
These are 19 widgets available in Python Tkinter module. Below we have all the widgets listed
down with a basic description:

Name of
Description
Widget

Button If you want to add a button in your application then Button widget will be used.

To draw a complex layout and pictures (like graphics, text, etc.)Canvas Widget will be
Canvas
used.

If you want to display a number of options as checkboxes then Checkbutton widget


CheckButton
is used. It allows you to select multiple options at a time.

19 | P a g e ISHWAR PRAKASH
Name of
Description
Widget

To display a single-line text field that accepts values from the user Entry widget will
Entry
be used.

In order to group and organize another widgets Frame widget will be used. Basically
Frame
it acts as a container that holds other widgets.

To Provide a single line caption to another widget Label widget will be used. It can
Label
contain images too.

Listbox To provide a user with a list of options the Listbox widget will be used.

To provides commands to the user Menu widget will be used. Basically these
Menu commands are inside the Menubutton. This widget mainly creates all kinds of
Menus required in the application.

Menubutton The Menubutton widget is used to display the menu items to the user.

The message widget mainly displays a message box to the user. Basically it is a multi-
Message
line text which is non-editable.

If you want the number of options to be displayed as radio buttons then the
Radiobutton
Radiobutton widget will be used. You can select one at a time.

Scale widget is mainly a graphical slider that allows you to select values from the
Scale
scale.

Scrollbar To scroll the window up and down the scrollbar widget in python will be used.

20 | P a g e ISHWAR PRAKASH
Name of
Description
Widget

The text widget mainly provides a multi-line text field to the user where users and
Text
enter or edit the text and it is different from Entry.

Toplevel The Toplevel widget is mainly used to provide us with a separate window container

The SpinBox acts as an entry to the "Entry widget" in which value can be input just
SpinBox
by selecting a fixed value of numbers.

The PanedWindow is also a container widget that is mainly used to handle


PanedWindow
different panes. Panes arranged inside it can either Horizontal or vertical

The LabelFrame widget is also a container widget used to mainly handle the
LabelFrame
complex widgets.

The MessageBox widget is mainly used to display messages in the Desktop


MessageBox
applications.

Q. Program to display the tkinter window.

from tkinter import Tk

root= Tk()

[Link]()

Form Design Python with tkinter is the fastest and easiest way to create the GUI applications.
Creating a GUI using tkinter is an easy task.

21 | P a g e ISHWAR PRAKASH
from tkinter import*

root = Tk()

[Link]('500x500')

[Link]("Admission Form")

label_0 = Label(root, text="Admission form",width=20,font=("bold", 20))

label_0.place(x=90,y=53)

label_1 = Label(root, text="FullName",width=20,font=("bold", 10))

label_1.place(x=80,y=130)

entry_1 = Entry(root)

entry_1.place(x=240,y=130)

22 | P a g e ISHWAR PRAKASH
label_2 = Label(root, text="Email",width=20,font=("bold", 10))

label_2.place(x=68,y=180)

entry_2 = Entry(root)

entry_2.place(x=240,y=180)

label_3 = Label(root, text="Gender",width=20,font=("bold", 10))

label_3.place(x=70,y=230)

var = IntVar()

Radiobutton(root, text="Male",padx = 5, variable=var, value=1).place(x=235,y=230)

Radiobutton(root, text="Female",padx = 20, variable=var, value=2).place(x=290,y=230)

label_4 = Label(root, text="Age:",width=20,font=("bold", 10))

label_4.place(x=70,y=280)

entry_2 = Entry(root)

entry_2.place(x=240,y=280)

Button(root, text='Submit',width=20,bg='brown',fg='white').place(x=180,y=380)

# it is use for display the registration form on the window

[Link]()

print("registration form seccussfully created...")

Q. Program to display a menu on the menu bar

from tkinter import Tk,Menu

root=Tk()

23 | P a g e ISHWAR PRAKASH
[Link]("NotePad")

menu_bar=Menu(root)

filemenu=Menu(menu_bar,tearoff=0)

filemenu.add_command(label="New", command=[Link])

filemenu.add_command(label="Open", command=[Link])

filemenu.add_command(label="Save", command=[Link])

menu_bar.add_cascade(label="File", menu=filemenu)

editmenu=Menu(menu_bar,tearoff=0)

editmenu.add_command(label="Cut", command=[Link])

editmenu.add_command(label="Copy", command=[Link])

editmenu.add_command(label="Paste", command=[Link])

menu_bar.add_cascade(label="Edit", menu=editmenu)

[Link](menu=menu_bar)

[Link]()

24 | P a g e ISHWAR PRAKASH

Common questions

Powered by AI

Recursive functions, such as those used to calculate Fibonacci series or GCD, can be elegant and intuitive solutions to problems that naturally fit recursive patterns, like divide-and-conquer algorithms or recursive data structures (e.g., trees). They can simplify the code significantly compared to iterative methods, by breaking down complex problems into simpler sub-problems. However, they may lead to performance overhead due to deep call stacks, making them less appropriate for deep recursion scenarios compared to iterative approaches .

Tkinter widgets, such as buttons, labels, and entry fields, are fundamental components in creating interactive and responsive GUI applications in Python. These widgets make GUI development straightforward by offering predefined elements, simplifying the process of designing interfaces. Compared to GUI development in other languages (like C++ with Qt or Java with Swing), Tkinter provides a simpler, more direct approach suitable for basic applications but might lack advanced features for more complex GUI demands .

Python's support for dynamic typing allows variables to change types and to be assigned without explicit type definitions, which simplifies code and makes it less verbose. High-level dynamic data types, such as lists and dictionaries, provide built-in methods to handle complex data manipulations effortlessly, increasing productivity and reducing the time developers spend on implementing basic functionality .

Python's loop constructs offer significant advantages in scenarios requiring repetition of similar operations, such as processing collections of data (like arrays or lists), or performing actions until a certain condition is met. This reduces code redundancy and potential errors, as the same block of code can execute multiple times with varying data. Additionally, loops make the program more readable and maintainable since logic is encapsulated within a single structure rather than scattered through repetitions .

Python handles program modularity through modules, which are files containing Python code (functions, classes, and variables) that can be imported into other Python programs. This allows for code reusability and organization, where commonly used functions or classes are stored in modules and reused across multiple programs. Modules help in dividing entire programs into smaller, manageable, and organized sections that can be developed and tested individually .

Python's flexibility is embodied in its clear syntax and robust community support. Its simple and readable syntax lowers the entry barrier for beginners, enabling them to develop basic programs quickly. For advanced users, Python's versatility is evident through its vast ecosystem of libraries and frameworks for web development, data science, and automation. Community resources, such as forums and documentation, further enhance learning and problem-solving, allowing programmers of all levels to continuously advance their skills .

Python being an interpreted language means that the code is processed line-by-line by an interpreter at runtime, which simplifies the programming process by eliminating the need to compile code before executing it. This affects its use by allowing for quick testing of code, facilitating debugging through immediate execution feedback, and making it more accessible to beginners due to the simpler development cycle .

Python's interpretive nature allows for rapid prototyping and iteration, which is advantageous in exploratory data analysis typical in data science and statistics. Combined with extensive libraries like NumPy, SciPy, and pandas, it offers powerful tools for data manipulation, analysis, and visualization, contributing to its popularity in the field. These libraries abstract complex operations into manageable code, enabling data scientists to focus more on insights rather than technical implementation .

Python's Turtle library is a graphics module that supports a wide range of applications from simple drawings and animations to educational programming for beginners. Its integration provides a visual means for tracking and understanding programming loops, control flow, and function calls. This makes it highly valuable pedagogically, as it provides a hands-on, visual learning experience that can facilitate the comprehension of complex programming concepts in an engaging way .

Python's exception handling, using try-except blocks, is similar to that of many modern programming languages but is noted for its user-friendly syntax and readability. Unlike languages with lower-level exception handling, Python's design encourages catching only specific exceptions rather than using catch-all constructs, which improves robustness by ensuring only expected and handled exceptions occur, reducing the risk of hidden errors .

You might also like