Definition of Variables
- Variables are Containers
- Used for storing data values.
Creating Variables
-
No Declaration Command
- Python does not require a specific command to declare variables.
- A variable is created when you assign a value to it.
-
Examples:
-
x = 5 y = "John" print(x) print(y)
-
-
Dynamic Typing
- Variables do not need to have a fixed type and can change types after being set.
- Example:
x = 4 # x is of type int x = "Sally" # x is now of type str print(x)
Casting Variables
- Specifying Data Type
- Use casting to define a variable's data type explicitly.
- Example:
x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0
Getting the Type of a Variable
- Using
type()
Function- Check the data type of a variable.
- Example:
x = 5 y = "John" print(type(x)) # Output: <class 'int'> print(type(y)) # Output: <class 'str'>
Strings and Quotes
- Single or Double Quotes
- String variables can use either single (
'
) or double ("
) quotes interchangeably. - Example:
x = "John" y = 'John'
- String variables can use either single (
Case Sensitivity
- Variable Names are Case-Sensitive
- Variables with different cases are treated as distinct variables.
- Example:
a = 4 A = "Sally" # A will not overwrite a
Exercise
- Question: What is a correct way to declare a Python variable?
- Correct Answer:
x = 5
- Correct Answer:
Definition of Variable Names
- Short or Descriptive
- Variable names can be short (e.g.,
x
,y
) or descriptive (e.g.,age
,carname
,total_volume
).
- Variable names can be short (e.g.,
Rules for Python Variable Names
-
Starting Character
- Must start with a letter or an underscore (
_
).
- Must start with a letter or an underscore (
-
Cannot Start with a Number
- A variable name cannot begin with a digit.
-
Allowed Characters
- Can only contain alphanumeric characters (
A-Z
,a-z
,0-9
) and underscores (_
).
- Can only contain alphanumeric characters (
-
Case Sensitivity
- Variable names are case-sensitive. Examples:
age
,Age
, andAGE
are treated as different variables.
- Variable names are case-sensitive. Examples:
-
Python Keywords
- Variable names cannot be any of Python's reserved keywords.
Examples of Legal and Illegal Variable Names
Legal Variable Names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Illegal Variable Names:
2myvar = "John" # Cannot start with a number
my-var = "John" # Cannot contain special characters like "-"
my var = "John" # Cannot contain spaces
Reminder
- Case Sensitivity:
- Variable names like
myvar
,MyVar
, andMYVAR
are distinct due to Python's case sensitivity.
- Variable names like
Many Values to Multiple Variables
-
Assigning Multiple Values in One Line
- Python allows assigning multiple values to multiple variables in one line.
- Example:
x, y, z = "Orange", "Banana", "Cherry" print(x) # Orange print(y) # Banana print(z) # Cherry
-
Matching Variables and Values
- The number of variables must match the number of values; otherwise, an error will occur.
One Value to Multiple Variables
- Assigning the Same Value to Multiple Variables
- A single value can be assigned to multiple variables in one line.
- Example:
x = y = z = "Orange" print(x) # Orange print(y) # Orange print(z) # Orange
Unpack a Collection
-
Extracting Values from Collections
- Python allows extracting values from a collection (like a list or tuple) into variables, called unpacking.
- Example:
fruits = ["apple", "banana", "cherry"] x, y, z = fruits print(x) # apple print(y) # banana print(z) # cherry
-
Learn More About Unpacking
- You can learn more about unpacking in the Unpack Tuples Chapter.
Exercise
Question:
What is the correct syntax to assign the value 'Hello World'
to 3 variables in one statement?
Options:
x, y, z = 'Hello World'
x = y = z = 'Hello World'
✅x|y|z = 'Hello World'
Output Variables
-
Using
print()
to Output Variables- The
print()
function can be used to display the value of a variable. - Example:
x = "Python is awesome" print(x)
- The
-
Outputting Multiple Variables
- Multiple variables can be output using commas within the
print()
function. - Example:
x = "Python" y = "is" z = "awesome" print(x, y, z) # Python is awesome
- Multiple variables can be output using commas within the
-
Using the
+
Operator to Output Variables- The
+
operator can be used to concatenate strings. - Example:
x = "Python " y = "is " z = "awesome" print(x + y + z) # Python is awesome
- Note: If there are no spaces within the string variables, the result will appear as a single concatenated string (e.g.,
"Pythonisawesome"
).
- The
Working with Numbers
-
Mathematical Operation with
+
- The
+
operator adds numbers when used with numeric variables. - Example:
x = 5 y = 10 print(x + y) # 15
- The
-
Error When Combining Strings and Numbers
- Combining a string and a number with the
+
operator will result in a TypeError. - Example:
x = 5 y = "John" print(x + y) # Error
- Combining a string and a number with the
-
Using Commas for Different Data Types
- Using commas in the
print()
function allows you to combine different data types. - Example:
x = 5 y = "John" print(x, y) # 5 John
- Using commas in the
Exercise
Question:
Consider the following code:
print('Hello', 'World')
What will be the printed result?
Options:
- Hello, World
- Hello World ✅
- HelloWorld
Global Variables
Definition of Global Variables
- Global Variables are created outside of a function and can be used both inside and outside of functions.
Using Global Variables Inside Functions
- A global variable can be accessed directly within a function.
- Example:
x = "awesome" def myfunc(): print("Python is " + x) myfunc() # Output: Python is awesome
- Example:
Local Variables with the Same Name as Global Variables
- If a variable with the same name as a global variable is defined inside a function, it becomes a local variable and does not affect the global variable.
- Example:
x = "awesome" def myfunc(): x = "fantastic" # Local variable print("Python is " + x) myfunc() # Output: Python is fantastic print("Python is " + x) # Output: Python is awesome
- Example:
The global
Keyword
- Definition: The
global
keyword is used to define or modify a global variable inside a function.
Creating a Global Variable Inside a Function
- Using
global
within a function creates a global variable that can be accessed outside of the function.- Example:
def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x) # Output: Python is fantastic
- Example:
Modifying a Global Variable Inside a Function
- To change the value of an existing global variable inside a function, use the
global
keyword. - Example:
x = "awesome" def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x) # Output: Python is fantastic
If you're a beginner and want a simple way to handle subjects without using functions or loops, you can write the script like this:
Simplified Script:
# Welcome message
print("Welcome to the Student Exam Result Sheet App!")
# Input student details
name = input("Enter Student's Name: ").strip()
student_class = input("Enter Student's Class: ").strip()
# Input marks for each subject
math = float(input("Enter marks for Math: "))
science = float(input("Enter marks for Science: "))
history = float(input("Enter marks for History: "))
geography = float(input("Enter marks for Geography: "))
it = float(input("Enter marks for IT: "))
# Calculate total marks
total_marks = math + science + history + geography + it
# Print the result sheet
print("\n---- Student Exam Result Sheet ----")
print(f"Name: {name}")
print(f"Class: {student_class}")
print("\nSubjects and Marks:")
print(f"Math: {math}")
print(f"Science: {science}")
print(f"History: {history}")
print(f"Geography: {geography}")
print(f"IT: {it}")
print("\nTotal Marks:", total_marks)
print("-----------------------------------")
How It Works:
-
Input Student Details:
- Asks for the student's name and class.
-
Input Marks for Each Subject:
- Collects marks for "Math," "Science," "History," "Geography," and "IT" directly without using a loop.
-
Calculate Total Marks:
- Adds the marks of all subjects using simple arithmetic.
-
Display the Result Sheet:
- Prints the student details, each subject's marks, and the total marks in a readable format.
Example Input/Output:
Input:
Enter Student's Name: John Doe
Enter Student's Class: Grade 6
Enter marks for Math: 85
Enter marks for Science: 90
Enter marks for History: 75
Enter marks for Geography: 80
Enter marks for IT: 88
Output:
---- Student Exam Result Sheet ----
Name: John Doe
Class: Grade 6
Subjects and Marks:
Math: 85.0
Science: 90.0
History: 75.0
Geography: 80.0
IT: 88.0
Total Marks: 418.0
-----------------------------------
Why It’s Beginner-Friendly:
- No Functions or Loops: The script directly asks for each subject's marks and calculates the total.
- Step-by-Step: Each part of the script is written in a straightforward, sequential manner.
- Easily Expandable: To add more subjects, just add another input line and include it in the total.
Let me know if you'd like further simplifications or explanations!
Here's a Python script to develop a simple Student Exam Result Sheet App. The script will:
- Take input for the student's name and class.
- Take input for marks in each subject (Math, Science, History, Geography, IT).
- Calculate the total marks.
- Print the result sheet with the student's details, marks for each subject, and total marks.
Here's the complete Python script:
# Student Exam Result Sheet App
def get_student_details():
"""Get student's name and class"""
name = input("Enter Student's Name: ").strip()
student_class = input("Enter Student's Class: ").strip()
return name, student_class
def get_subject_marks():
"""Get marks for all subjects"""
subjects = ["Math", "Science", "History", "Geography", "IT"]
marks = {}
print("\nEnter marks for the following subjects:")
for subject in subjects:
while True:
try:
mark = float(input(f"{subject}: "))
if 0 <= mark <= 100: # Validating mark range
marks[subject] = mark
break
else:
print("Marks should be between 0 and 100. Please try again.")
except ValueError:
print("Invalid input! Please enter a valid number.")
return marks
def calculate_total_marks(marks):
"""Calculate the total marks"""
return sum(marks.values())
def display_result_sheet(name, student_class, marks, total_marks):
"""Display the result sheet"""
print("\n---- Student Exam Result Sheet ----")
print(f"Name: {name}")
print(f"Class: {student_class}")
print("\nSubjects and Marks:")
for subject, mark in marks.items():
print(f"{subject}: {mark:.2f}")
print("\nTotal Marks:", total_marks)
print("-----------------------------------")
def main():
"""Main function to run the app"""
print("Welcome to the Student Exam Result Sheet App!")
name, student_class = get_student_details()
marks = get_subject_marks()
total_marks = calculate_total_marks(marks)
display_result_sheet(name, student_class, marks, total_marks)
if __name__ == "__main__":
main()
How to Use the Script
- Copy and paste the script into a Python IDE or a text editor (e.g., VS Code, PyCharm, or a simple text editor).
- Save the file with a
.py
extension, e.g.,student_result_sheet.py
. - Run the script in your terminal or Python environment.
- Follow the prompts to enter:
- The student's name and class.
- Marks for each subject (input between 0 and 100).
- The script will display the result sheet.
Features
- Input validation ensures marks are between 0 and 100.
- Clear formatting for the result sheet.
- Easy-to-modify script (e.g., add more subjects).
You can extend this script by saving the results to a file (CSV or JSON) or using a database for persistent storage. Let me know if you'd like to add any advanced features!