0% found this document useful (0 votes)
4 views12 pages

01 Python Basics

This document provides an introduction to Python programming, covering the basics of variables, types, and user input. It explains what variables are, how to name them, assign values, and the different data types in Python, including integers, floats, strings, and booleans. Additionally, it discusses type casting and the importance of converting between data types for effective programming.

Uploaded by

zansah31
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views12 pages

01 Python Basics

This document provides an introduction to Python programming, covering the basics of variables, types, and user input. It explains what variables are, how to name them, assign values, and the different data types in Python, including integers, floats, strings, and booleans. Additionally, it discusses type casting and the importance of converting between data types for effective programming.

Uploaded by

zansah31
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Notes Part 1

Python Basics: Variables, Types, and Input

Contents
1 Introduction to Python Programming 2

2 Variables 2
2.1 What are Variables? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Variable Naming Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.3 Assigning Values to Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.4 Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

3 Type Casting 6
3.1 Converting Between Data Types . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2 int(), float(), and str() Functions . . . . . . . . . . . . . . . . . . . . . . . . 7
3.3 Common Type Conversion Scenarios . . . . . . . . . . . . . . . . . . . . . . 8

4 User Input 10
4.1 The input() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.2 Processing User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.3 Converting Input Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

1
1 Introduction to Python Programming
Welcome to the world of Python programming! Python is one of the most popular and
versatile programming languages in use today. Created by Guido van Rossum and first
released in 1991, Python has grown to become the language of choice for beginners and
experts alike.
Why Learn Python? Python’s popularity stems from several key advantages. First,
it emphasizes code readability with its clean, English-like syntax. Second, it is incredibly
versatile, being used in web development, data science, artificial intelligence, automation,
scientific computing, and much more. Third, Python has an enormous and supportive com-
munity, meaning you’ll find abundant resources, libraries, and help when you need it.
What Makes Python Special? Unlike languages such as C++ or Java, Python is an
interpreted language, meaning your code runs line by line without needing to be compiled
first. This makes development faster and debugging easier. Python is also dynamically
typed, which means you don’t need to explicitly declare variable types—Python figures it
out for you.
In this comprehensive guide, we’ll start from the absolute basics and progressively build
your skills to handle real-world programming challenges. Each concept will be explained
clearly with practical examples, just as if you were sitting in a university lecture hall. Let’s
begin our journey!

2 Variables
2.1 What are Variables?
Imagine you’re solving a math problem and you write ”Let x = 5” at the top of your work.
You’ve just created a variable! In programming, a variable serves the same purpose—it’s a
container that stores a value so you can use it later in your program.
Think of a variable as a labeled box in your computer’s memory. The label is the variable
name, and inside the box is the value you’ve stored. Just like you can change what’s in a
physical box, you can change the value stored in a variable at any time during your program’s
execution.
Let’s look at a simple example:
1 age = 25
Here, we’ve created a variable named age and stored the value 25 in it. The equals sign
(=) is called the assignment operator—it assigns the value on the right to the variable on
the left.
Why do we need variables? Variables allow us to:
• Store information that we want to use multiple times
• Make our code more readable by giving meaningful names to values
• Perform calculations and store the results
• Create programs that can work with different inputs

2
2.2 Variable Naming Rules
Just as you can’t name your child with numbers or special symbols in most countries, Python
has rules for naming variables. Understanding these rules is crucial to writing valid Python
code.
Required Rules (Your code won’t run if you break these):

1. Must start with a letter or underscore: Variable names must begin with a letter
(a-z, A-Z) or an underscore ( ). They cannot start with a number.
1 # Valid
2 name = " Alice "
3 _count = 10
4 user1 = " Bob "
5
6 # Invalid
7 1 user = " Charlie " # Error ! Cannot start with number

2. Can only contain letters, numbers, and underscores: After the first character, you
can use letters, numbers, and underscores, but no spaces or special characters like !, @,
#, etc.
1 # Valid
2 user_name = " Alice "
3 account2 = " Savings "
4 total_price_2024 = 299.99
5
6 # Invalid
7 user - name = " Bob " # Error ! Hyphens not allowed
8 total price = 100 # Error ! Spaces not allowed
9 email@ = " test " # Error ! @ symbol not allowed

3. Case-sensitive: Python treats uppercase and lowercase letters as different. This means
Age, age, and AGE are three completely different variables.
1 age = 25
2 Age = 30
3 AGE = 35
4
5 print ( age ) # Outputs : 25
6 print ( Age ) # Outputs : 30
7 print ( AGE ) # Outputs : 35

4. Cannot use Python keywords: Python has reserved words that have special meanings
in the language. You cannot use these as variable names. Examples include: if, for,
while, def, class, return, True, False, etc.
1 # Invalid
2 for = 10 # Error ! ’ for ’ is a keyword
3 class = " Math " # Error ! ’ class ’ is a keyword
4 if = True # Error ! ’ if ’ is a keyword

3
Best Practices (Optional but highly recommended):

• Use descriptive names: Instead of x or a, use names that describe what the variable
contains, like student age or total price.

• Use snake case: For multi-word variable names, use lowercase letters with underscores
between words (called snake case). For example: first name, total cost, user email.

• Avoid single letters except for counters: Single-letter variables like i, j, and k are
acceptable for loop counters, but otherwise use descriptive names.

• Don’t use built-in function names: Avoid using names of built-in Python functions
like print, sum, list, etc. While Python won’t give you an error, it will override the
built-in function and cause confusion.

2.3 Assigning Values to Variables


The process of giving a value to a variable is called assignment. In Python, we use the equals
sign (=) as the assignment operator. Remember: this is not the mathematical ”equals”—it
means ”store the value on the right into the variable on the left.”
Basic Assignment:
1 # Assigning different types of values
2 name = " Sarah " # String ( text )
3 age = 28 # Integer ( whole number )
4 height = 5.6 # Float ( decimal number )
5 is_student = True # Boolean ( True or False )

Multiple Assignments:
Python allows you to assign values to multiple variables in a single line:
1 # Assign same value to multiple variables
2 x = y = z = 0
3 print (x , y , z ) # Outputs : 0 0 0
4
5 # Assign different values to multiple variables
6 name , age , city = " Alice " , 25 , " Boston "
7 print ( name ) # Outputs : Alice
8 print ( age ) # Outputs : 25
9 print ( city ) # Outputs : Boston

Reassignment:
One of the most important concepts to understand is that variables can be reassigned.
The value in a variable is not permanent—you can change it at any time:
1 score = 0
2 print ( score ) # Outputs : 0
3
4 score = 10
5 print ( score ) # Outputs : 10
6
7 score = score + 5
8 print ( score ) # Outputs : 15

4
In the last example, score = score + 5, Python first evaluates the right side (score +
5, which is 10 + 5 = 15), then assigns that result back to score.
Augmented Assignment Operators:
Python provides shorthand operators for common operations:
1 count = 10
2
3 count += 5 # Same as : count = count + 5
4 print ( count ) # Outputs : 15
5
6 count -= 3 # Same as : count = count - 3
7 print ( count ) # Outputs : 12
8
9 count *= 2 # Same as : count = count * 2
10 print ( count ) # Outputs : 24
11
12 count /= 4 # Same as : count = count / 4
13 print ( count ) # Outputs : 6.0

2.4 Variable Types


In Python, every value has a type. The type determines what kind of data the variable
holds and what operations you can perform on it. Python automatically determines the
type based on the value you assign—this is called dynamic typing.
The Main Data Types:

1. Integer (int): Whole numbers, positive or negative, without decimals.


1 age = 25
2 temperature = -5
3 year = 2024

2. Float (float): Numbers with decimal points.


1 price = 19.99
2 pi = 3.14159
3 temperature = 98.6

3. String (str): Text data, enclosed in single quotes (”), double quotes (””), or triple quotes
(”’ ”’ or ””” ”””).
1 name = " Alice "
2 message = ’ Hello , World ! ’
3 paragraph = " " " This is a long
4 multi - line string . " " "

4. Boolean (bool): Represents True or False values. Note the capital T and F.
1 is_raining = True
2 has_license = False
3 is_adult = age >= 18 # Evaluates to True or False

5
Checking Variable Types:
You can use the type() function to check what type a variable is:
1 age = 25
2 name = " Alice "
3 height = 5.8
4 is_student = True
5

6 print ( type ( age ) ) # Outputs : < class ’ int ’>


7 print ( type ( name ) ) # Outputs : < class ’ str ’>
8 print ( type ( height ) ) # Outputs : < class ’ float ’>
9 print ( type ( is_student ) ) # Outputs : < class ’ bool ’>

Why Types Matter:


Different types support different operations. For example:
1 # You can add numbers
2 result = 10 + 5
3 print ( result ) # Outputs : 15
4
5 # You can add strings ( concatenation )
6 greeting = " Hello " + " " + " World "
7 print ( greeting ) # Outputs : Hello World
8
9 # But you cannot add a number and a string directly
10 # price = 10 + " dollars " # Error ! Cannot add int and str

This is where type casting becomes important, which we’ll explore in the next section.

3 Type Casting
3.1 Converting Between Data Types
Imagine you have a toolbox where each tool is designed for a specific job. A hammer is
great for nails, but you can’t use it to tighten a screw. Similarly, in Python, each data type
is designed for specific operations. Sometimes, however, we need to convert data from one
type to another—this process is called type casting or type conversion.
Type casting is essential because:

• User input is always received as a string, even if the user types a number

• Mathematical operations require numeric types

• Some functions expect specific data types

• We need to display numbers as text (strings) for output

Python provides three main functions for type casting: int(), float(), and str(). Let’s
explore each one in detail.

6
3.2 int(), float(), and str() Functions
1. Converting to Integer with int():
The int() function converts a value to an integer (whole number). When converting
from a float, it simply removes the decimal part—it does not round!
1 # Converting string to integer
2 age_str = " 25 "
3 age_int = int ( age_str )
4 print ( age_int ) # Outputs : 25
5 print ( type ( age_int ) ) # Outputs : < class ’ int ’>
6
7 # Converting float to integer ( truncates decimal )
8 price = 19.99
9 price_int = int ( price )
10 print ( price_int ) # Outputs : 19 ( not 20!)
11
12 # Another example
13 temperature = 98.7
14 temp_int = int ( temperature )
15 print ( temp_int ) # Outputs : 98

Important: The int() function cannot convert strings that contain decimal points or
non-numeric characters:
1 # This will cause an error :
2 # num = int ("25.5") # ValueError !
3 # num = int (" hello ") # ValueError !
4
5 # This works :
6 num = int ( float ( " 25.5 " ) ) # First convert to float , then to int
7 print ( num ) # Outputs : 25

2. Converting to Float with float():


The float() function converts a value to a floating-point number (decimal number).
1 # Converting string to float
2 price_str = " 19.99 "
3 price_float = float ( price_str )
4 print ( price_float ) # Outputs : 19.99
5 print ( type ( price_float ) ) # Outputs : < class ’ float ’>
6
7 # Converting integer to float
8 age = 25
9 age_float = float ( age )
10 print ( age_float ) # Outputs : 25.0
11
12 # Converting string without decimal
13 count = float ( " 100 " )
14 print ( count ) # Outputs : 100.0

3. Converting to String with str():


The str() function converts a value to a string (text). This is particularly useful when
you want to combine numbers with text.
1 # Converting integer to string

7
2 age = 25
3 age_str = str ( age )
4 print ( age_str ) # Outputs : 25 ( looks the same but is text )
5 print ( type ( age_str ) ) # Outputs : < class ’ str ’>
6
7 # Converting float to string
8 price = 19.99
9 price_str = str ( price )
10 print ( price_str ) # Outputs : 19.99
11
12 # Combining numbers with text ( requires conversion )
13 age = 25
14 # message = " I am " + age + " years old " # Error !
15 message = " I am " + str ( age ) + " years old " # Correct
16 print ( message ) # Outputs : I am 25 years old

3.3 Common Type Conversion Scenarios


Let’s examine real-world situations where type casting is necessary.
Scenario 1: Performing Math with User Input
When you receive input from a user, it’s always a string. To perform mathematical
operations, you must convert it:
1 # Getting user input ( always a string !)
2 age_input = input ( " Enter your age : " ) # User types : 25
3 print ( type ( age_input ) ) # Outputs : < class ’ str ’>
4

5 # Convert to integer for math


6 age = int ( age_input )
7 years_until_30 = 30 - age
8 print ( " Years until 30: " , years_until_30 )
9
10 # More complete example
11 num1 = input ( " Enter first number : " ) # User types : 10
12 num2 = input ( " Enter second number : " ) # User types : 5
13
14 # Convert strings to integers
15 num1 = int ( num1 )
16 num2 = int ( num2 )
17
18 sum_result = num1 + num2
19 print ( " Sum : " , sum_result ) # Outputs : Sum : 15

Scenario 2: Formatting Output Messages


Often, you need to create messages that combine text and numbers:
1 name = " Alice "
2 age = 28
3 height = 5.6
4

5 # Method 1: Converting to string manually


6 message = " My name is " + name + " , I am " + str ( age ) + " years old "
7 print ( message )

8
8
9 # Method 2: Using f - strings ( easier and recommended !)
10 message = f " My name is { name } , I am { age } years old , and I am { height }
feet tall "
11 print ( message )
12
13 # Method 3: Using format ()
14 message = " My name is {} , I am {} years old " . format ( name , age )
15 print ( message )

Scenario 3: Converting Between Numeric Types


Sometimes you need to switch between integers and floats for precise calculations:
1 # Integer division vs . float division
2 total = 100
3 people = 3
4
5 # Integer division ( truncates )
6 share_int = total // people
7 print ( share_int ) # Outputs : 33
8
9 # Float division ( precise )
10 share_float = total / people
11 print ( share_float ) # Outputs : 33.333333...
12

13 # Converting for precise calculation


14 total_float = float ( total )
15 share_precise = total_float / people
16 print ( f " Each person gets $ { share_precise :.2 f } " ) # Outputs : $33 .33

Practical Example: Temperature Converter


Let’s combine what we’ve learned in a complete program:
1 # Temperature converter : Celsius to Fahrenheit
2 print ( " Temperature Converter " )
3

4 # Get input as string


5 celsius_str = input ( " Enter temperature in Celsius : " )
6
7 # Convert to float for precise calculation
8 celsius = float ( celsius_str )
9

10 # Perform calculation
11 fahrenheit = ( celsius * 9/5) + 32
12
13 # Display result ( convert numbers to strings for concatenation )
14 print ( " Temperature in Fahrenheit : " + str ( fahrenheit ) )
15

16 # Or use f - string ( easier !)


17 print ( f " { celsius } C is equal to { fahrenheit } F " )

Understanding type casting is fundamental to Python programming. As you progress,


you’ll find yourself using these conversions constantly, especially when working with user
input, file data, and mathematical operations.

9
4 User Input
4.1 The input() Function
Up until now, all the values in our programs have been hardcoded—written directly into the
code. But what makes programs truly interactive and useful is their ability to receive input
from users. The input() function is your gateway to creating interactive programs.
Think of input() as having a conversation with your program. The program asks a
question, waits for you to respond, and then uses your response to make decisions or perform
calculations.
Basic Syntax:
1 variable_name = input ( " Your prompt message : " )

The text inside the parentheses (called the prompt) is displayed to the user. The
program then pauses and waits for the user to type something and press Enter. Whatever
the user types is stored in the variable as a string.
Simple Example:
1 name = input ( " What is your name ? " )
2 print ( " Hello , " + name + " ! " )
3

4 # If user types : Alice


5 # Output : Hello , Alice !

Key Point: The input() function always returns a string, even if the user types a
number!
1 age = input ( " How old are you ? " ) # User types : 25
2 print ( type ( age ) ) # Outputs : < class ’ str ’>, not < class ’ int ’ >!

This is why type casting is so important when working with user input.

4.2 Processing User Input


Once you’ve received input from the user, you’ll typically need to process it in some way.
Let’s explore common processing techniques.
1. Storing and Using Simple Input:
1 # Greeting program
2 name = input ( " Enter your name : " )
3 print ( " Welcome , " + name + " ! " )
4
5 # Multiple inputs
6 first_name = input ( " Enter your first name : " )
7 last_name = input ( " Enter your last name : " )
8 full_name = first_name + " " + last_name
9 print ( " Your full name is : " , full_name )

2. Cleaning User Input:


Users might accidentally add extra spaces. Python provides methods to clean this up:
1 # User might type : " Alice " ( with extra spaces )
2 name = input ( " Enter your name : " )

10
3 name = name . strip () # Removes leading and trailing spaces
4 print ( " Hello , " + name + " ! " )
5
6 # Converting to specific case
7 name = input ( " Enter your name : " )
8 name = name . title () # Capitalizes first letter of each word
9 print ( " Hello , " + name + " ! " ) # " alice " becomes " Alice "

3. Providing Clear Prompts:


Good prompts help users understand what to enter:
1 # Unclear prompt
2 x = input ( " Enter : " ) # Enter what ?
3
4 # Clear prompt
5 age = input ( " Enter your age in years : " )
6 city = input ( " Enter your city of residence : " )
7 email = input ( " Enter your email address : " )

4.3 Converting Input Types


Since input() always returns a string, we must convert it to the appropriate type for our
needs. This is where our type casting knowledge becomes crucial.
Converting to Integer:
1 # Simple conversion
2 age_str = input ( " Enter your age : " ) # User types : 25
3 age = int ( age_str ) # Convert to integer
4 print ( f " Next year you will be { age + 1} " )
5

6 # More efficient : convert immediately


7 age = int ( input ( " Enter your age : " ) )
8 print ( f " In 5 years you will be { age + 5} " )

Converting to Float:
1 # For decimal numbers
2 height = float ( input ( " Enter your height in meters : " ) )
3 print ( f " Your height in centimeters is { height * 100} " )
4
5 price = float ( input ( " Enter the price : $ " ) )
6 tax = price * 0.08 # 8% tax
7 total = price + tax
8 print ( f " Total with tax : $ { total :.2 f } " )

Complete Example: Shopping Calculator


1 print ( " ===== Shopping Calculator ===== " )
2 print ()
3
4 # Get item information
5 item = input ( " Item name : " )
6 price = float ( input ( " Price per item : $ " ) )
7 quantity = int ( input ( " Quantity : " ) )
8

11
9 # Calculate costs
10 subtotal = price * quantity
11 tax_rate = 0.08 # 8% sales tax
12 tax = subtotal * tax_rate
13 total = subtotal + tax
14
15 # Display receipt
16 print ()
17 print ( " ===== RECEIPT ===== " )
18 print ( f " Item : { item } " )
19 print ( f " Price : $ { price :.2 f } " )
20 print ( f " Quantity : { quantity } " )
21 print ( " -" * 20)
22 print ( f " Subtotal : $ { subtotal :.2 f } " )
23 print ( f " Tax (8%) : $ { tax :.2 f } " )
24 print ( f " Total : $ { total :.2 f } " )
25 print ( " = " * 20)

The input() function is your primary tool for creating interactive programs. Master it
well, as you’ll use it in nearly every program you write as a beginner!

12

You might also like