× Introduction Working with Python Basics Data Types Control statements Loops Functions Lists Tuples Strings Turtle eBooks

Python Fundamentals

Python Character Set

It is a set of valid characters that a language recognize.

  • Letters: A-Z, a-z
  • Digits : 0-9
  • Special Symbols: +,-, *, /, **, (),[],//, =, != etc
  • Whitespaces: Blank space, tabs, new line etc

Tokens

Token:Smallest individual unit in a program is known as token.

There are five types of token in python:

  1. Keyword
  2. Identifier(Names)
  3. Literal
  4. Operators
  5. Punctuators

1. Python Keywords

Keywords are reserved words. Each keyword has a specific meaning to the Python interpreter, and we can use a keyword in our program only for the purpose for which it has been defined.

and   for   raise   del   with   not   True   False   None   is   in  
def   class   continue   assert   if   else   elif   finally from   global   or  
pass   import   lambda   nonlocal   return   try   while   yield   break   except   print  

All the keywords are in lowercase except 03 keywords (True, False, None).

2. Identifier (Names):

The name given by the user to the entities like variable name, class-name, function-name etc.

Rules for identifiers:

  • It can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore.
  • It cannot start with a digit.
  • Keywords cannot be used as an identifier.
  • We cannot use special symbols like !, @, #, $, %, + etc. in identifier.
  • _ (underscore) can be used in identifier.
  • Commas or blank spaces are not allowed within an identifier.

Note:

  • Because Python is case sensitive, area, Area, and AREA are all different identifiers.
  • Descriptive identifiers make programs easy to read. Avoid using abbreviations for identifiers.
  • Use lowercase letters for variable names, as in radius and area. If a name consists of several words, concatenate them into one, making the first word lowercase and capitalizing the first letter of each subsequent word—for example, number Of Students. This naming style is known as the camelCase because the uppercase characters in the name resemble a camel's humps.

The following are valid identifiers:

studentName, student_name, row1, _ts, date12_2_2023, FILE13

The following are invalid identifiers:

student-Name, 1row, while, FILE,13

3. Literals / Values:

Literals (often referred to as constant values) are data items that have a fixed value.

Python allows foloowingliterals:

1) String literals

2) Numeric literals

3) Boolean literals

i) Special literal None

i) Literal Collections

4. Operators:

An operator performs the operation on operands (data). Basically there are two types of operators in python according to number of operands:

A. Unary Operator:Performs the operation on one operand.

B. Binary Operator:Performs operation on two operands.

5. Punctuators:

Punctuators are symbols that are used in programming launguages to organise sentance structures, and indicate the rhythm and emphasis of expressions, statements, and program structure.

Most common punctuators of Phython programming language are: ' " # \ ( ) [ ] { } @ , : =

Comments

A comment in a program is a note orDocumentation that a programmer writes for himself or other programmers who will look at his code. The computer ignores comments. There are two types of comments in python:

i. Single line comment

ii. Multi-line comment

i. Single line comment: This type of comments start in a line and when a line ends, it is automatically ends. Single line comment starts with # symbol.

Example:

# This is a single line comment in Python
print("Hello World") # This line prints "Hello World"

ii. Multi-Line comment: Multiline comments can be written in more than one lines. Triple quoted ‘ ’ ’ or “ ” ”) multi-line comments may be used in python. It is also known as docstring.

Example:

"""
This type of comment spans multiple lines.
These are mostly used for documentation of functions, classes and modules.
"""

Lines and Indentation

Python does not use braces({}) to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.

In Python, the same level of indentation associates statements into a single block of code. The interpreter checks indentation levels very strictly and throws up syntax errors if indentation is not correct. It is a common practice to use a single tab for each level of indentation.

The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount.

if ( num % 2 == 0):
  print ("Even")
else:
  print ("Odd")

Quotation in Python

Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string. The triple quotes are used to span the string across multiple lines.

Word= 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It ismade up of multiple lines and 
sentences."""

Variables, Assignment Statements, and Expressions

Variables are used to reference values that may be changed in the program. A variable in a program is uniquely identified by a name (identifier).

Variable in Python refers to an object — an item or element that is stored in the memory. Value of a variable can be a string (e.g., ‘b’, ‘Global Citizen’), numeric (e.g., 345) or any combination of alphanumeric characters (CD67).

gender = 'M'
message = "Keep Smiling"
price = 987.9

Rules for Python variables:

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscore (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)

Note: Variable declaration is implicit in Python, means variables are automatically declared and defined when they are assigned a value the first time. Variables must always be assigned values before they are used in expressions as otherwise it will lead to an error in the program. Wherever a variable name occurs in an expression, the interpreter replaces it with the value of that particular variable.

x = x + 1  # this statement leads to nameError: x is not defined

#To fix it, you may write the code like this:

x = 5
x = x + 1

Dynamic Typing

Variables do not need to be declared with any particular type and can even change type after they have been set. It is known as dynamic Typing.

x = 4  # x is of type int
x = "python" # x is now of type str 

Assignment statement

The statement for assigning a value to a variable is called an assignment statement. In Python, the equal sign (=) is used as the assignment operator. The syntax for assignment statements is as follows:

variable = expression

An expression represents a computation involving values, variables, and operators that, taken together, evaluate to a value. For example, consider the following code:

x = 1   # Assign 1 to variable x
radius = 1.0   # Assign 1.0 to variable radius
y = 10 * (4 / 1) + 4 * 5  # Assign the value of the expression to y
x = y + 1  # Assign the addition of y and 1 to x
area = radius * radius * 3.14159    # Compute area

You can use a variable in an expression. A variable can also be used in both sides of the = operator. For example,

x = x + 1

In this assignment statement, the result of x + 1 is assigned to x. If x is 1 before the statement is executed, then it becomes 2 after the statement is executed.

To assign a value to a variable, you must place the variable name to the left of the assignment operator. Thus, the following statement is wrong:

1 = x   # wrong

Note: In mathematics, x = 2 * x + 1 denotes an equation. However, in Python, x = 2 * x + 1 is an assignment statement that evaluates the expression 2 * x + 1 and assigns the result to x.

Assign multiple variables

If a value is assigned to multiple variables, you can use a syntax like this:

i = j = k = 1

which is equivalent to

k = 1

j = k

i = j

Simultaneous Assignments

Python also supports simultaneous assignment, that means you can assign multiple values to multiple variables.

var1, var2, ..., varn = exp1, exp2, ..., expn

It tells Python to evaluate all the expressions on the right and assign them to the corresponding variable on the left simultaneously.

x , y , z = 4, 5, "python"

4 is assigned to x, 5 is assigned to y and string "python" assigned to variable z respectively.

Swapping variable values

Swapping variable values is a common operation in programming and simultaneous assignment is very useful to perform this operation.

x = 12
y = 14
x,y = y,x
print(x,y)

Reading Input from the Console

In Python, we have the input() function for taking the user input. The input() function prompts the user to enter data. It accepts all user input as string. The user may enter a number or a string but the input() function treats them as strings only.

The syntax for input() is:

input ([Prompt])

Prompt is the string we may like to display on the screen prior to taking the input, and it is optional. When a prompt is specified, first it is displayed on the screen after which the user can enter data. The input() takes exactly what is typed from the keyboard, converts it into a string and assigns it to the variable on left-hand side of the assignment operator (=). Entering data for the input function is terminated by pressing the enter key.

fname = input("Enter your first name: ")

eval function

You can use the function eval to evaluate and convert the string to a numeric value. For example, eval("34.5") returns 34.5, eval("345") returns 345, eval("3 + 4") returns 7

ComputeAreaWithConsoleInput.py

# Prompt the user to enter a radius
radius = eval(input("Enter a value for radius: "))

# Compute area
area = radius * radius * 3.14159

# Display results
print("The area for the circle of radius", radius, "is", area)

print() function

Python uses the print() function to output data to standard output device — the screen.The function print() evaluates the expression before displaying it on the screen. The print() outputs a complete line and then moves to the next line for subsequent output.

print("Hello")  # Hello
print(10*2.5)  # 25.0
print("I" + "love" + "my" + "country")  # Ilovemycountry
print("I'm", 16, "years old")  #  I'm 16 years old

ComputeAverageWithSimultaneousAssignment.py

# Prompt the user to enter three numbers
number1, number2, number3 = eval(input(
"Enter three numbers separated by commas: "))

# Compute average
average = (number1 + number2 + number3) / 3

# Display result
print("The average of", number1, number2, number3
"is", average)

Named constants

A named constant is an identifier that represents a permanent value. Use all uppercase letters to name a constant, to distinguish a constant from a variable.

Example: PI = 3.14159

There are three benefits of using constants:

1. You don’t have to repeatedly type the same value if it is used multiple times.

2. If you have to change the constant’s value (e.g., from 3.14 to 3.14159 for PI), youneed to change it only in a single location in the source code.

3. Descriptive names make the program easy to read.

Example Programs

1. Write a program in main.py that prints the

Student Name: S.Srihari

Class: 7th

Roll No: 19

print("Student Name: S.Srihari")
print("Class: 7th")
print("Roll No: 19")

OUTPUT:
Student Name: S.Srihari
Class: 7th
Roll No: 19

2. Ask for the user’s first name and display the output message Hello, [First Name] .

firstName = input("Please enter your first name ")
print("Hello ", firstName)
OUTPUT:
Please enter your first name Rama
Hello  Rama

3. Ask for the user’s first name and then ask for their surname and display the output message Hello [First Name] [Surname].

firstName = input("Please enter your first name ")
surname = input("Please enter your surname ")
print("Hello, ", firstName, surname)

OUTPUT:
Please enter your first name Gopal
Please enter your surname K
Hello,  Gopal K

4. Ask the user to enter two numbers. Add them together and display the answer as The total is [answer].

num1 = eval(input("Please enter your first number "))
num2 = eval(input("Please enter your second number "))
total = num1 + num2
print("The Total is ", total)

OUTPUT:
Please enter your first number 10
Please enter your second number 20
The Total is  30

5. Ask the user to enter three numbers. Calculate the average and display the average.

number1 = eval(input("Enter the first number: "))
number2 = eval(input("Enter the second number: "))
number3 = eval(input("Enter the third number: "))

average = (number1 + number2 + number3) / 3

print("The average of", number1, number2, number3,
"is", average)

OUTPUT:
Enter the first number: 10
Enter the second number: 20
Enter the third number: 30
The average of 10 20 30 is 20.0
Simultaneous Assignments:
number1, number2, number3 = eval(input(
"Enter three numbers separated by commas: "))

average = (number1 + number2 + number3) / 3

print("The average of", number1, number2, number3,
"is", average)

OUTPUT:
Enter three numbers separated by commas: 10,20,30
The average of 10 20 30 is 20.0