Python basics: syntax, data types, and control structures

Recommendation: Use NSDT scene editor to quickly build 3D application scenes

If Python is already installed in your development and environment, launch the Python REPL and code. Alternatively, if you want to skip the installation and start coding right away, I recommend heading over to Google Colab and coding together.

Hello, Python!

Before we write the classic "Hello, world!" program in Python, here's some information about the language. Python is an interpreted language . What does it mean?

In any programming language, all source code you write should be translated into machine language. While compiled languages ​​like C and C++ require the entire machine code before the program can be run, an interpreter parses the source code and interprets it dynamically.

Create a Python script, type the following code and run it:

print("Hello, World!")

In order to print out Hello, World! , we used the "print()" function, which is one of the many built-in functions in Python.

In this super simple example, note that "Hello, World!" is a sequence - a string of characters. Python strings are delimited by a pair of single or double quotes. So to print out any message string you can use "print("<message_string>")".

Read user input

Now let's go a step further and read some input from the user using the 'input()' function. Users should always be prompted to let them know what they are expected to enter .

This is a simple program that takes as input a username and greets them.

Comments help make code more readable by providing additional context to the user. Single-line comments in Python start with #.

Note that the string in the code snippet below has an "f" in front of it. Such strings are called format strings or f-strings . To replace the value of a variable in an f-string, specify the name of the variable within a pair of curly braces, as follows:

# Get user input
user_name = input("Please enter your name: ")

# Greet the user
print(f"Hello, {user_name}! Nice to meet you!")

When you run the program, you will first be prompted for input and then a greeting message will be printed:

Please enter your name: Bala
Hello, Bala! Nice to meet you!

Let's continue learning about variables and data types in Python.

Variables and data types in Python

In any programming language, variables are like containers for storing information . In the code we have written so far, we have created a variable 'user_name'. When a user enters their name (a string), it is stored in the "user_name" variable.

Basic data types in Python

Let's look at the basic data types in Python: "int", "float", "str" ​​and "bool", using a simple example of building on each other:

Integer ('int'): An integer is an integer without a decimal point . You can create integers and assign them to variables like this:

age = 25
discount= 10

These are assignment statements that assign values ​​to variables. In languages ​​like C, you must specify the data type when declaring a variable, but Python is a dynamically typed language . It infers the data type from the value. Therefore, you can reassign a variable to hold a value of a completely different data type:

number = 1
number = 'one'

You can check the data type of any variable in Python using the "type" function:

number = 1
print(type(number))

"number" is an integer:

Output >>> <class 'int'>

We now assign a string value to "number":

number = 'one'
print(type(number))
Output >>> <class 'str'>

Floating point ("float"): Floating point represents a real number with a decimal point . You can create a variable of "float" data type as follows:

height = 5.8
pi = 3.14159

You can perform various operations on numeric data types (addition, subtraction, lower bound division, exponentiation, etc.). Here are some examples:

# Define numeric variables
x = 10
y = 5

# Addition
add_result = x + y
print("Addition:", add_result)  # Output: 15

# Subtraction
sub_result = x - y
print("Subtraction:", sub_result)  # Output: 5

# Multiplication
mul_result = x * y
print("Multiplication:", mul_result)  # Output: 50

# Division (floating-point result)
div_result = x / y
print("Division:", div_result)  # Output: 2.0

# Integer Division (floor division)
int_div_result = x // y
print("Integer Division:", int_div_result)  # Output: 2

# Modulo (remainder of division)
mod_result = x % y
print("Modulo:", mod_result)  # Output: 0

# Exponentiation
exp_result = x ** y
print("Exponentiation:", exp_result)  # Output: 100000

String ('str'): A string is a sequence of characters enclosed in single or double quotes.

name = "Alice"
quote = 'Hello, world!'

Boolean ("bool"): A Boolean value represents "true" or "false" and represents the truth value of a condition.

is_student = True
has_license = False

Python's flexibility in handling different data types allows you to store, perform various operations, and manipulate data efficiently.

Here's an example that puts together all the data types we've learned so far:

# Using different data types together
age = 30
score = 89.5
name = "Bob"
is_student = True

# Checking if score is above passing threshold
passing_threshold = 60.0
is_passing = score >= passing_threshold

print(f"{name=}")
print(f"{age=}")
print(f"{is_student=}")
print(f"{score=}")
print(f"{is_passing=}")

This is the output:

Output >>>

name='Bob'
age=30
is_student=True
score=89.5
is_passing=True

Beyond basic data types

Let's say you're managing information about students in your classroom. It would be more helpful to create a collection (to store information for all students) than to repeatedly define variables for each student.

list

A list is an ordered collection of items enclosed in square brackets. The items in the list can all be of the same or different data types. Lists are mutable , which means you can change their contents after creation.

Here, "student_names" contains the students' names:

# List
student_names = ["Alice", "Bob", "Charlie", "David"]

tuple

Tuples are ordered collections similar to lists, but they are immutable , which means you cannot change their contents after they are created.

Suppose you want "student_scores" to be an immutable collection containing student test scores.

# Tuple
student_scores = (85, 92, 78, 88)

dictionary

A dictionary is a collection of key-value pairs. The keys of the dictionary should be unique and they map to corresponding values. They are mutable and allow you to associate information with a specific key.

Here, "student_info" contains information about each student (name and score) as key-value pairs:

student_info = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 88}

But wait, there's a more elegant way to create dictionaries in Python.

We are about to learn a new concept: dictionary comprehension . If it's not clear right away, don't worry. You can always learn more and work on it later.

But the understanding is a very intuitive understanding. If you wanted the "student_info" dictionary to have student names as keys and their corresponding test scores as values, you could create the dictionary like this:

# Using a dictionary comprehension to create the student_info dictionary
student_info = {name: score for name, score in zip(student_names, student_scores)}

print(student_info)

Notice how we use the 'zip()' function to iterate over both the 'student_names' list and the 'student_scores' tuple.

Output >>>

{'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 88}

In this example, dictionary comprehension directly pairs each student name in the "student_names" list with the corresponding test score in the "student_scores" tuple to create a "student_info" dictionary with names as keys and scores as values.

Now that you are familiar with primitive data types and some sequence/iterable objects, let's move on to the next part of the discussion: control structures .

Control structures in Python

When you run a Python script, code execution occurs in the same order as the code executes within the script.

Sometimes you need to implement logic to control the flow of execution based on certain conditions, or to loop through an iterable object to process items within it.

We'll see how if-else statements facilitate branching and conditional execution. We will also learn how to use loops to iterate over a sequence, with loop control statements to interrupt and continue.

if statement

An "if" statement can be used when a block of code needs to be executed only when a specific condition is true. If the condition evaluates to false, the block of code is not executed.

Python basics: syntax, data types, and control structures


Image source: author

Consider the following example:

score = 75

if score >= 60:
    print("Congratulations! You passed the exam.")

In this example, the code in the "if" block will only be executed if "score" is greater than or equal to 60. Since the "score" is 75, the message "Congratulations! You passed the exam", will be printed.

Output >>> Congratulations! You passed the exam.

If-else conditional statement

The "if-else" statement allows you to execute one block of code if the condition is true and another block of code if the condition is false.

Python basics: syntax, data types, and control structures


Image source: author

Let's build on the test score example:

score = 45

if score >= 60:
    print("Congratulations! You passed the exam.")
else:
    print("Sorry, you did not pass the exam.")

Here, if the "score" is less than 60, the code in the "else" block will be executed:

Output >>> Sorry, you did not pass the exam.

If-elif-else Ladder

The "if-elif-else" statement is used when you have multiple conditions to check. It allows you to test multiple conditions and execute the corresponding code block for the first true condition encountered.

If the conditions in the 'if' and all 'elif' statements evaluate to false, the 'else' block is executed.

Python basics: syntax, data types, and control structures


Image source: author

score = 82

if score >= 90:
    print("Excellent! You got an A.")
elif score >= 80:
    print("Good job! You got a B.")
elif score >= 70:
    print("Not bad! You got a C.")
else:
    print("You need to improve. You got an F.")

In this example, the program checks a "score" based on multiple conditions. The code in the first true conditional block will be executed. Since the "score" is 82, we get:

Output >>> Good job! You got a B.

Nested If Statements

Use nested "if" statements when you need to check multiple conditions within another condition.

name = "Alice"
score = 78

if name == "Alice":
    if score >= 80:
        print("Great job, Alice! You got an A.")
    else:
        print("Good effort, Alice! Keep it up.")
else:
    print("You're doing well, but this message is for Alice.")

In this example, there is a nested "if" statement. First, the program checks if "name" is "Alice". If true, checks "score". Since the "score" is 78, the inner "else" block is executed, printing "Good effort, Alice! Keep it up.

Output >>> Good effort, Alice! Keep it up.

Python provides several loop constructs to iterate over collections or perform repetitive tasks.

for loop

In Python, the “for” loop provides a concise syntax that lets us iterate over an existing iterable object. We can iterate over the "student_names" list like this:

student_names = ["Alice", "Bob", "Charlie", "David"]

for name in student_names:
    print("Student:", name)

The above code outputs:

Output >>>

Student: Alice
Student: Bob
Student: Charlie
Student: David

And loop

If you want to execute a block of code if a condition is true, you can use a "while" loop.

Let's use the same "student_names" list:

# Using a while loop with an existing iterable

student_names = ["Alice", "Bob", "Charlie", "David"]
index = 0

while index < len(student_names):
    print("Student:", student_names[index])
    index += 1

In this example, we have a list "student_names" that contains student names. We use a "while" loop to iterate over the list by tracking the "index" variable.

The loop continues as long as the "index" is less than the length of the list. In the loop, we print each student's name and increment the "index" to move to the next student. Note the use of the "len()" function to get the length of the list.

This achieves the same result as using a "for" loop to iterate over the list:

Output >>>

Student: Alice
Student: Bob
Student: Charlie
Student: David

Let's use a 'while' loop to pop elements from the list until the list is empty:

student_names = ["Alice", "Bob", "Charlie", "David"]

while student_names:
    current_student = student_names.pop()
    print("Current Student:", current_student)

print("All students have been processed.")

The list method "pop" removes and returns the last element present in the list.

In this example, the "while" loop continues as long as there are elements in the "student_names" list. In the loop, the "pop()" method is used to remove and return the last element in the list and print the name of the current student.

The loop will continue until all students have been processed and the last message will be printed outside the loop.

Output >>>

Current Student: David
Current Student: Charlie
Current Student: Bob
Current Student: Alice
All students have been processed.

A "for" loop is generally cleaner and easier to read and is used to iterate over an existing iterable object (such as a list). However, "while" loops can provide more control when the loop conditions are more complex.

Loop control statement

"break" exits the loop prematurely, "continue" skips the remainder of the current iteration and moves to the next iteration.

Here's an example:

student_names = ["Alice", "Bob", "Charlie", "David"]

for name in student_names:
    if name == "Charlie":
        break
    print(name)

When "name" is Charlie, the control breaks out of the loop, giving us the output:

Output >>>
Alice
Bob

Simulating cyclic behavior during execution

In Python, there is no built-in "do-while" loop like in some other programming languages. However, you can achieve the same behavior using a "while" loop with a "break" statement. Here's how to simulate a "do-while" loop in Python:

while True:
    user_input = input("Enter 'exit' to stop: ")
    if user_input == 'exit':
        break

In this example, the loop will continue running indefinitely until the user enters "exit". The loop runs at least once because the condition is initially set to "True" and then within the loop the user's input is checked. If the user enters "exit", the "break" statement is executed and the loop exits.

Here is a sample output:

Output >>>
Enter 'exit' to stop: hi
Enter 'exit' to stop: hello
Enter 'exit' to stop: bye
Enter 'exit' to stop: try harder!
Enter 'exit' to stop: exit

Note that this approach is similar to "do-while" loops in other languages, where the body of the loop is guaranteed to execute at least once before checking the condition.

Summary and next steps

I hope you were able to code this tutorial without any difficulty. Now that you know the basics of Python, it's time to start writing some super simple projects that apply all the concepts you learned.

Original link: Python basics: syntax, data types and control structures (mvrlink.com)

Guess you like

Origin blog.csdn.net/ygtu2018/article/details/132808076