Python Write Your First Program¶
- When you start learning Python, the very first step is usually to write a simple program that displays a message on the screen.
- A common tradition is to print the phrase “Hello, World!” — it’s a friendly way to confirm that your Python setup works correctly.
# This is a comment. Python ignores anything written after the '#' symbol.
# Use comments to explain what your code does — it makes your code easier to read.
# Print "Hello, World!" to the console
print("Hello, World!")
Hello, World!
Here's what this code does:
Lines that start with # are comments. They are not executed and are used to provide explanations to human readers.
print("Hello, World!") is the code that prints the text "Hello, World!" to the console. In Python, print() is a built-in function used to display text or values on the screen.
Anything inside the quotation marks (" ") is treated as text (a string) and will be shown exactly as written.
Python Script Mode Programming¶
- Script mode in Python refers to writing Python code in a text file (typically with a .py extension) and then executing that file as a script. This is a common way to create Python programs that perform specific tasks or solve particular problems. Here's a step-by-step tutorial on how to write and execute Python scripts:
Step 1: Set Up Your Development Environment
Before you start, ensure you have Python installed on your computer. If not, download it from the official website.
You can write Python scripts using any text editor, but using an integrated development environment (IDE) like Visual Studio Code, PyCharm, or IDLE can make your coding experience more efficient.
Step 2: Write Your Python Script
- Open your chosen text editor or IDE and create a new file. Then, write your Python code in this file. Here's a simple example of a Python script that calculates the square of a number:
# This is a Python script to calculate the square of a number
# Input: Get a number from the user
number = float(input("Enter a number: "))
# Calculate the square
square = number ** 2
# Output: Display the result
print(f"The square of {number} is {square}")
Enter a number: 2 The square of 2.0 is 4.0
In this script:
We take user input using the input() function.
We calculate the square of the number entered by the user.
We use the print() function to display the result.
Step 3: Save Your Python Script
- Save your Python script with a .py file extension. For example, you can save it as square_calculator.py.
Step 4: Run Your Python Script
Now that your script is saved, open your command prompt or terminal and navigate to the directory where your script is located.
To run the script, use the python command followed by the name of your script file:
python square_calculator.py
- Your script will execute, and you should see the program prompting you for input and then displaying the calculated square.
Python Identifiers¶
- A Python identifier is a name used to identify a variable, function, class, module or other object.
Rules for Python Identifiers:¶
Must Begin with a Letter (a-z, A-Z) or an Underscore (_):
- Valid: my_variable, _private_variable
- Invalid: 123_variable, @special_var
Can Contain Letters, Digits (0-9), or Underscores and not allow punctuation characters such as @, $, and % etc:
- Valid: my_var2, count_123
- Invalid: my-var, my.var
Case-Sensitive:
- Python treats identifiers as case-sensitive, meaning myVar and myvar are different identifiers.
Cannot Be a Reserved Word:
- Python has reserved words (also known as keywords) that cannot be used as identifiers because they have special meanings in the language.
- For example, if, else, while, class, etc., are reserved words.
Naming conventions for Python identifiers¶
Python Class Names Start with an Uppercase Letter and All Other Identifiers Start with a Lowercase Letter:
- Class names in Python conventionally start with an uppercase letter to distinguish them from other identifiers. For example, MyClass or BankAccount.
- dentifiers other than class names typically start with a lowercase letter. This includes variables, functions, and module names. For example, my_variable, calculate_total_amount.
Starting an Identifier with a Single Leading Underscore Indicates It's Private:
- When an identifier starts with a single leading underscore (e.g., _private_var), it is considered a convention to indicate that the identifier is intended for internal use within a module or class and should not be accessed directly from outside.
Starting an Identifier with Two Leading Underscores Indicates Strongly Private:
- When an identifier starts with two leading underscores (e.g., __strongly_private_var), it indicates a stronger level of privacy. In this case, the identifier's name is "mangled" to make it less likely to clash with subclasses or other classes.
If the Identifier Also Ends with Two Trailing Underscores, It's a Language-Defined Special Name:
- Identifiers that start and end with double underscores (e.g.,
__init__
) are reserved for special methods or attributes defined by the Python language. These are often referred to as "magic methods" and have specific meanings in Python, such as__init__
for constructors and__str__
for string representations.
- Identifiers that start and end with double underscores (e.g.,
Python User Input¶
- In python we are able to ask the user for input.
- The input() function captures a line of text entered by the user through an input device, such as a keyboard, and returns it as a string.
Syntax:
input([prompt])
The
prompt
parameter is optional. It allows you to display a message or instruction to the user before they provide input.When the
input()
function is executed:- The program pauses and waits for the user to type a value.
- The user enters the value using the keyboard.
- The function then reads the entered value, converts it into a string, and returns it to the program.
Important Note:
No matter what the user types—whether it’s an integer, a floating-point number, or text—the
input()
function always returns the value as a string.If you need the input as a different data type (for example, an integer or a float), you must explicitly perform type conversion.
Example 1: Basic input() Usage¶
# Get user input and store it in a variable
user_input = input("Enter your name: ")
# Display the user's input
print("Hello, " + user_input + "!")
Enter your name: Raj Hello, Raj!
Example 2: Converting Input to Integer¶
# Prompt the user for a number
number = input("Enter a number: ")
# Display the type of the input
print("You entered:", number)
print("Data type before conversion:", type(number))
# Convert the string input to integer
number = int(number)
print("Data type after conversion:", type(number))
# Perform arithmetic operation
print("Square of the number is:", number ** 2)
Enter a number: 5 You entered: 5 Data type before conversion: <class 'str'> Data type after conversion: <class 'int'> Square of the number is: 25
Example 3: Converting Input to Float¶
# Prompt the user for a floating-point number
value = input("Enter a decimal number: ")
print("You entered:", value)
print("Data type before conversion:", type(value))
# Convert the string input to float
value = float(value)
print("Data type after conversion:", type(value))
# Perform arithmetic operation
print("Half of the number is:", value / 2)
Enter a decimal number: 7.5 You entered: 7.5 Data type before conversion: <class 'str'> Data type after conversion: <class 'float'> Half of the number is: 3.75
Python Printing to the Screen¶
- In Python, you can print text and variables to the screen or console using the print() function. This function is one of the most fundamental ways to display output from your Python programs.
- To print text or strings to the screen, simply pass the text as an argument to the print() function. For example:
print("Hello, World!")
Hello, World!