PYTHON Programming Language

Syllabus:

7.6 Introduction to python programming

7.7 Basic syntaxes

7.8 I/O statements and string formatting

7.9 Data types and variables

7.10 Concept of Type casting

7.11 Operators and expressions: Arithmetic, Relational, Logical, Assignment

 

7.6 Introduction to Python Programming 

Python:

Python is a high-level, interpreted programming language created by Guido van Rossum in 1991.

It is known for its simple and readable syntax, making it beginner-friendly and highly versatile.

Python is widely used in web development, data science and machine learning, artificial intelligence, data analysis, automation and scripting, game development, web scraping, cyber security, etc.

Python has a simple to understand coding style, applying indentation instead of braces to define blocks of code. For example, in a loop or conditional statement, indentation signifies the scope of the block.

 

Features of Python:

1)     Easy to read and write: Python uses simple and understandable syntax, making it easy for   programmers to write and understand the code.

2)     Versatile: Python can be used for a wide range of tasks like simple automating systems to complex web development, data analysis, and Artificial Intelligence.

3)     Beginner-friendly: Python uses simple syntax, making it a great choice for those who are new to programming.

4)     Extensive standard library: Python has an extensive standard library of pre-written code that offers programmers ready-made solutions, without requiring them to write code from ground level.

  

7.7 Basic Syntaxes in Python

Python’s syntax is straightforward and beginner-friendly. 

Comments in Python:

Comments are brief messages that programmers write in their code to explain what the code is doing, like leaving helpful hints for others to understand the program.

Single-line comments start with #, and multi-line comments are enclosed in triple quotes (''' or """).

Example:

# This is a single-line comment

 

"""

This is a

multi-line comment

"""

Keywords:

Keywords are reserved words that have predefined meanings and cannot be used as identifiers (variable names, function names, etc.).

Example: False, await, else, import, pass etc.

 

7.8 I/O statements and string formatting

 

Input/Output statements (I/O):

I/O statements help us to interact with the program. i.e. It allows us to provide our data and instructions to the program as well as display the output on screen.

 

Print Statement:

The print statement in Python is used to display information on the screen. We use a ‘print’ statement to display the output of data that we want to show.

Example: print(“Hello, Python!”)

 

Input Function:

The ‘input’ function allows to provide input to the program. We can give data to the program as we need.

Example: number = input(“Enter number: ”)

 

String Formatting:

String formatting in Python helps to insert values into a string, making it easier to create dynamic and personalized messages.

Using % Operator (Old Style):

This is the old style of string formatting, where we use % to insert values into a string.

Example:

name = "Charlie"

age = 22

message = "My name is %s and I am %d years old." % (name, age)

print(message)

Output:

My name is Charlie and I am 22 years old.

 

Using format( ) Method:

The format( ) method allows to insert values into a string using curly braces {} as placeholders.

Example:

name = "Bob"

age = 30

message = "My name is {} and I am {} years old.".format(name, age)

print(message)

Output:

My name is Bob and I am 30 years old.

We can also use numbered or named placeholders

Example:

message = "My name is {0} and I am {1} years old.".format(name, age)

print(message)

 

Using f-strings (Formatted String Literals)

f-strings are the most modern and efficient way to format strings. We can directly embed expressions inside curly braces {}. It was introduced in Python 3.6.

Example:

name = "Alice"

age = 25

message = f"My name is {name} and I am {age} years old."

print(message)

Output:

My name is Alice and I am 25 years old.

 

7.9 Data types and variables

Data type

The classification of data based on its nature is called data type. It defines the kind of data a variable can hold.

Python supports several data types:

Integer (int): It is a whole number ranging from negative infinity to positive infinity.

Examples: -,...,-3,-2,-1,0,1,2,3,....,

Float (float): It is numbers with decimals.

Examples: 3.14, -0.5, 1.567.

String (str): It consists of alphabets, special characters, alphanumeric values which are enclosed in double quotes.

Examples: “hello” , “Python@”, “Mahendranagar1”, “@#@#kathmandu”

Boolean (bool): It only provides True or False values.

Example: is_student = True, has_mobile=False

 

Identifier

Identifiers are names given to program units such as variables, functions, classes, or other entities. They are not predefined in the programming language but are defined by programmers themselves.

 

Rules for identifier

An identifier name must start with a letter or the underscore character.

An identifier name cannot start with a number.

An identifier name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).

Python is case sensitive so identifier names are also case-sensitive. (age, Age and AGE are three different identifiers).

An identifier name cannot be any of the Python keywords.

 

Valid identifiers:

A1, B34, First_Name, x_1 etc.

 

Invalid identifiers:

1A, 34BA,198, int, print first-name. def etc.

 

Variables in Python:

A variable is like a container that holds a value which stores numbers, text, or other data types. A variable is created when the value is assigned to it.

Example:

name = "Alice"     # String variable

age = 25           # Integer variable

height = 5.5       # Float variable

is_student = True #Boolean variable

 

7.10 Concept of Type Casting

Type Casting (Type Conversion)

Type casting is the process of converting one data type into another. For example, if we assign an integer (int) value to a float variable, the compiler will convert the int value to a float.

Types of casting

a) Implicit casting

b) Explicit casting

 

Implicit casting

Implicit type casting, also known as automatic type conversion, occurs when the Python interpreter automatically converts one data type to another in certain situations.

Examples:

x = 10 # integer

y = 5.5 # float

z = x + y # the integer ‘x’ is cast to a float for the addition.

print(z)

 

Explicit casting

In explicit type casting, the user intentionally converts the data type of a variable to another data type.

·       int(): Converts a value to an integer.

·       float(): Converts a value to a float.

·       str(): Converts a value to a string.

·       bool(): Converts a value to a boolean (True or False).

Example:

int(x): Converts x to an integer.

x = 3.14

y = int(x)  # Converts float to int (removes decimal part)

print(y)     # Output: 3

 

x = 25

y = str(x)    # Converts integer to string

print(y)      # Output: "25"

 

7.11 Operators and Expressions: Arithmetic, Relational, Logical, Assignment

Operators: 

Operators in Python are symbols that perform specific operations on variables and values. Python supports various types of operators, including arithmetic, relational, logical, and assignment operators.

Arithmetic Operators:

Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, and more.

Example:

Simple program to find the sum of the two number for the user input

num1 = float(input(“Enter first number: “))

num2 = float(input(“Enter second number: “))

sum = num1 + num2

print(“The sum of {0} and {1} is {2}”.format(num1, num2, sum))

 

Relational operator

Relational operator is used to check and compare values. These operators check the relationship between two things and tell us if they are equal, greater than or less than each other.

 

Logical operator

Logical operators in Python are used to combine conditions and make decisions based on different situations. This operator is like a tool that helps us make decisions based on different situations. There are 3 main logical operators, ‘and’, ‘or’, and ‘not’.

 

AND

Both the conditions must be true for the result to be true in the “and” operator.

Example: x = (5<2) and (5>3)

Result: False

OR

Only one of the conditions needs to be true for the result to be true in the “or” operator.

Example: (5<2) or (5>3)

Result: True

NOT

The logical operator “not” provides the opposite result of a given condition.

Example: not(5<2)

Result: True

Assignment operator

Assignment operators are used to assign values to variables.

Expression

An expression is a combination of values, variables, operators, and functions that are evaluated to produce a result.

Example:

Maths expression: result = 5 + 3

Text expression: greeting = “Hello”

Combining expression: combined = (5 * 3) + “Python”

 

Operands

Operands are values or variables that operators operate on. Operands refer to the values or entities that are operated upon by an operator.

Example: add = 5 + 3

Here, ‘5’ and ‘3’ are operands and ‘+’ is an operator, and it is performing an  ‘addition’ operation.

Workout Example: 

1. Write a program to display the message: "Hello, welcome to Python programming".

Ans:

print("Hello, welcome to Python programming")

 

2. Write a program that asks the user for their name and then prints a greeting message using an f-string such as:

"Hello, [name]! Welcome!"

Ans:

# Ask the user for their name

name = input("What is your name? ")

# Print a greeting using an f-string

print(f"Hello, {name}! Welcome!")

 

3. Create a program where you: Assign a string value to a variable called greeting. Assign a number to a variable called age. Print both variables.

Ans:

# Assign a string value to the variable 'greeting'

greeting = "Hello, world!"

# Assign a number to the variable 'age'

age = 30

# Print both variables

print(greeting)

print(age)

 

4. Write a program that takes a string input from the user, converts it to an integer, and adds 10 to it. Print the result.

Ans:

s = input("Enter a number: ")

n = int(s)   # Convert string to integer

print(n + 10)

 

5. Write a program to calculate the sum, difference, and product of two numbers (use variables a and b).

Ans:

# Input two numbers

a = float(input("Enter first number: "))

b = float(input("Enter second number: "))

# Calculate results

sum = a + b

difference = a - b

product = a * b

# Print the results

print(f"Sum: {sum}")

print(f"Difference: {difference}")

print(f"Product: {product}")

 

6. Create a program that checks if a number is greater than 10 and less than 20 using a logical operator.

Ans:

num = int(input("Enter a number: "))  

if num > 10 and num < 20:  

    print(f"{num} is between 10 and 20.")

else:

    print(f"{num} is NOT between 10 and 20.")

 

7. Write a program that asks the user for a number and prints whether it is positive, negative, or zero.

Ans:

num = float(input("Enter a number: ")) 

if num > 0:

    print("Positive")

elif num < 0:

    print("Negative")

else:

    print("Zero")

 

8. Write a program that takes a user's age and prints:

 

"You are a minor" if age is less than 18,

 

"You are an adult" if age is between 18 and 65,

 

"You are a senior" if age is above 65.

Ans:

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

 

if age < 18:

    print("You are a minor")

elif 18 <= age <= 65:

    print("You are an adult")

else:

    print("You are a senior")

 

9. Write a for loop that prints the numbers from 1 to 5.

Ans:

for i in range(1, 6):

    print(i)

 

10. Write a for loop that prints all the even numbers up to 100.

Ans:

for num in range(2, 101, 2):  # Start at 2, end at 100, step by 2

    print(num)

 

11. Write a while loop that asks the user to enter a password until they enter the correct one (e.g., "python123").

Ans:

password = ""

while password != "python123":

    password = input("Enter password: ")

print("Access granted!")

 

12. Create a list of your three favorite colors. Print each color using a for loop.

Ans:

# List of favorite colors

favorite_colors = ["blue", "green", "purple"]

# Print each color using a for loop

for color in favorite_colors:

    print(color)

 

13. Create a dictionary with keys "name", "age", and "favorite color". Assign them values and print each key-value pair.

Ans:

# Create dictionary

person = {

    "name": "Alex",

    "age": 28,

    "favorite color": "blue"

}

# Print each key-value pair

for key, value in person.items():

    print(f"{key}: {value}")

 

14. Write a program that takes a word from the user and prints it in uppercase, lowercase, and centered within 20 characters.

Ans:

word = input("Enter a word: ")

print(word.upper())

print(word.lower())

print(word.center(20))

 

15. Write a program that: Sums up a list of numbers. Finds the square root of a number input by the user (hint: use math.sqrt() from the math module).

Ans:

import math

# Sum a list of numbers

numbers = [1, 2, 3, 4, 5]

total = sum(numbers)

print(f"Sum of numbers: {total}")

 

# Calculate square root of user input

num = float(input("Enter a number to find its square root: "))

sqr= math.sqrt(num)

print(f"Square root: {sqr}") 

 

16. Write a program that asks the user for a number and prints whether it is even or odd using f-strings.

Ans:

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

if(n % 2 == 0):

    print(f"{n} is even")

else:

    print(f"{n} is odd")

Comments

Popular posts from this blog

Advanced C with Madhav