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

Python Jan 2025

A programming language is a structured set of instructions for computers, characterized by unique syntax, semantics, and features like variables and error handling. Python, developed by Guido van Rossum, is a widely used programming language known for its simplicity and versatility in web applications, workflows, and database connections. The document also covers various programming concepts, including the differences between compilers and interpreters, variable assignment, data types, comments, built-in functions, and practical coding exercises.

Uploaded by

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

Python Jan 2025

A programming language is a structured set of instructions for computers, characterized by unique syntax, semantics, and features like variables and error handling. Python, developed by Guido van Rossum, is a widely used programming language known for its simplicity and versatility in web applications, workflows, and database connections. The document also covers various programming concepts, including the differences between compilers and interpreters, variable assignment, data types, comments, built-in functions, and practical coding exercises.

Uploaded by

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

What is a programming language?

A programming language is a set of instructions written by a programmer to deliver


instructions to the computer to perform and accomplish a task.

Some characteristics of programming languages:

Syntax and semantics: Programming languages have a unique syntax and semantics, which are
usually defined by a formal language.
Vocabulary: Each programming language has a unique set of keywords that follow a special
syntax.
Features: Programming languages usually have features like variables, a type system, and
mechanisms for error handling.
Implementation: To execute programs, you need an implementation of a programming language,
such as a compiler or an interpreter.

There are many programming languages, but only a few are widely used. Some examples of
programming languages include: Python, JavaScript, Java, C, and SQL.
What do you understand by Python Language?
Python is the text-based programming language used by millions of professional coders at places
like Google, IBM, and even NASA!

Who developed python programming language?


It was created by Guido van Rossum during 1985- 1990.

What is the use of Python Language?


Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.

The features of Python language


Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
Databases − Python provides interfaces to all major commercial databases.
Portable − Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.
How does a computer program work?

SOURCE CODE (A Program) COMPILING PROCESS SOFTWARE OUTPUT ON CONSOLE


ENGLISH LIKE LANGUAGE (BINARY EXE FILE)

//A program in C
language

#include<stdio.h> 000010
int main()
COMPILER
111100 Hello World
OR
{ 1010101011
INTERPRETER
printf(“Hello World”); 1010100011
Return 0;
}
Differentiate between Compiler and Interpreter

Interpreter Complier
Translates program one statement at a Scans the entire program and translates
time. it as a whole into machine code.
Compilers usually take a large amount
Interpreters usually take less amount of time to analyze the source code.
of time to analyze the source code. However, the overall execution time is
However, the overall execution time is comparatively faster than interpreters.
comparatively slower than compilers.

Programming languages like


JavaScript, Python, Ruby use Programming languages like C, C++,
interpreters. Java use compilers.
What is the difference between script mode and interactive mode?

Interactive Mode Script Mode


The interactive mode involves running your In the script mode, you have to
codes directly on the Python shell which can create a file, give it a name with
be accessed from the terminal of the a .py the extension then runs
operating system. The interactive mode is your code.
suitable when running a few lines of code.
Explain the three types of quotations in python.

Python accepts single ('), double (") and triple (""" or """) quotes to denote string literals.
The triple quotes are used to span the string across multiple lines.

a) Single quotes(‘) : Used for Word


b) Double quotes (“ ”) : Used for Sentence
c) Triple quotes(‘‘‘ ’’’) : Used for Paragraph(apostrophe or double quotes can be
used)

Example
Word = ‘word’
Sentence = “This is a sentence.”
Paragraph = ‘‘‘ This is a paragraph. It is
made up of multiple lines
and sentences. ’’’
Variables in Python
Variable: In Python, variables are used to store data that can be referenced and manipulated
throughout a program. For Example:
Variable = Data #Datatype
Age = 25 # Integer
Name = "Alice" # String
Height = 5.7 # Float
is_student = True # Boolean

Rules for naming a variable:


• A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name cannot be any of the Python keywords(and, import, global, for, etc).
• A variable name can only contain alpha-numeric characters & underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age & AGE are three different variables)
Different ways to assign variables
>>>A=10
>>>a=b=10(both a and b variables have value 10)
>>>a , b =10,’hello’(a will store 10 and b will store hello)
>>> a="""hello
how are you
good morning""“

Many Values to Multiple Variables


Python allows you to assign values to multiple variables in one line:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

Note: Make sure the number of variables matches the number of values, or else you will get an
error.
Different ways to assign variables
One Value to Multiple Variables
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)

Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.
Example: Unpack a list:
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
Explain any four data-types available in python.

Integer(int):integers are whole numbers without decimal point. They can be positive or
negative
Ex:793,-254,4

Floating-Point numbers: Floats are written with a decimal point that segregates the
integer from fractional number.
Ex:6.2e3 , 6200.2

Strings: are sequences of characters enclosed in single or double quote.


Ex: ’Hello Class’, ”Hello Class”

Boolean : There is one of two possible response:


True or False
What do you understand by comments in python? Explain with an example
Comments are descriptions that help programmers better understand the intent and
functionality of the program.
They are completely ignored by the Python interpreter.

Comments are declared by ‘#’ sign.

Ex: # hello python


Explain with help of an example the following in-built function
input() function : this function is used to take input from user
Ex: name=input(“Enter name”)

range() function: this function is useful in ‘for ’ loops


Ex: list(range(1,10))[1,2,3,4,5,6,7,8,9,10]
list(range(1,10,2))[1,,3,5,7,9]
print() function: is used to print the statements within the parenthesis.
Ex: print(“Hello world!!”)

type() function: to see the type of data, type function is used.


Ex: type(4)<class , int>

len() function: returns the length of an object or the number of item in a list given as argument.
>>> s=("sun","moon","star")
>>> len(s)
3
>>> len("Mayo college")
12
Lab Exercise
To print “Hello World ”
print("Hello, World!")

To input and get output


name = input("Enter your name: ")
print("Hello, " + name + "!")

To add two numbers


# Input two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# Add the numbers


sum = num1 + num2

# Print the result


print("The sum is:", sum)
To check even /odd
number = int(input("Enter a number: "))
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
To make a simple calculator
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print("Choose an operation: +, -, *, /")
operation = input("Enter operation: ")
if operation == "+":
print("Result:", num1 + num2)
elif operation == "-":
print("Result:", num1 - num2)
elif operation == "*":
print("Result:", num1 * num2)
elif operation == "/":
print("Result:", num1 / num2)
else:
print("Invalid operation!“)
To Find the Largest of Three Numbers
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("The largest number is:", a)
elif b >= a and b >= c:
print("The largest number is:", b)
else:
print("The largest number is:", c)

To Print Numbers from 1 to 10 (Using Loops)


for i in range(1, 11):
print(i)
To print factorial of a number
num = int(input("Enter a number: "))
factorial = 1
for i in range(1, num + 1):
factorial *= I
print("The factorial of", num, "is", factorial)
To guess the Number
import random
number_to_guess = random.randint(1, 10)
guess = 0
while guess != number_to_guess:
guess = int(input("Guess a number between 1 and 10: "))
if guess < number_to_guess:
print("Too low!")
elif guess > number_to_guess:
print("Too high!")

print("Congratulations! You guessed the number.")

To Check if a String is a Palindrome


text = input("Enter a word: ")
if text == text[::-1]:
print("It's a palindrome!")
else:
print("It's not a palindrome.“)
To create multiplication table of a Number
number = int(input("Enter a number to see its multiplication table: "))
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")

To count vowels in a string


string = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0
for char in string:
if char in vowels:
count += 1
print("Number of vowels:", count)

To create Fibonacci sequence


n = int(input("Enter the number of terms: "))
a, b = 0, 1

print("Fibonacci Sequence:")
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
To reverse a string
text = input("Enter a string: ")
reversed_text = text[::-1]
print("Reversed string:", reversed_text)
To reverse a numbers
num = int(input("Enter a number: "))
reverse = 0
while num > 0:
digit = num % 10
reverse = reverse * 10 + digit
num //= 10
print("Reversed number:", reverse)

To swap the values of two numbers


a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
print("Before swapping: a =", a, ", b =", b)
# Swap using a temporary variable
temp = a
a=b
b = temp
print("After swapping: a =", a, ", b =", b)
Write a program to obtain three numbers from user and print their sum.

num1=int(input("Enter first no:"))


num2=int(input("Enter second no:"))
num3=int(input("Enter third no:"))
sum=num1+num2+num3
print("sum=",sum)

Write a program to obtain length of a square and calculate its area and perimeter.
l=int(input("Enter length:"))
area=l*l
peri=4*l
print("area=",area)
print("perimeter=",peri)
Practice Question
• Write a program to take input of three numbers from user and print the
average and sum.
• Write a program which takes input of radius of circle and print its perimeter
• area=3.14*r*r
• Write a program which takes input of length and breadth from user of a
rectangle and calculate its area and perimeter.
area=length*breadth
peri=a*(length+breadth)

You might also like