Python learning 1 (variables and simple data types, if statements)

Posted by Imtehbegginer on Sun, 23 Jan 2022 15:29:44 +0100

Variables and simple data types

Next, use variable to represent variables.

variable

Precautions for variable naming:
1. Variable names can only contain letters, numbers, and underscores. Variable names can start with letters or underscores, but not numbers. For example, you can name the variable message_1, but it cannot be named 1_message
2. Variable names cannot contain spaces, but underscores can be used to separate words. For example, the variable name is greeting_message works, but the variable name greeting message raises an error.
3. Do not use Python keywords and function names as variable names, that is, do not use Python to retain words for special purposes, such as print.
4. Variable names should be short and descriptive. For example, name is better than n, student_name ratio s_n OK, name_length ratio_ of_ persons_ Name good.
5. Use the lowercase letter l and the uppercase letter O with caution because they may be mistaken for the numbers 1 and 0.

String operation

Several simple operations

Simple output:

# Simple output
message = 'liyberty,nice to meet you!'  # '' has the same effect as' '
print(message.title())  # Capitalize the first letter of each word
print(message.upper())  # All characters are output in uppercase
print(message.lower())  # All characters are output in lowercase
  • Use variable Title(), which means capitalize the first letter of each word in variable.
  • Use variable Upper() means to capitalize each letter in variable.
  • Use variable Lower(), indicating that each letter in variable is lowercase.
    Character splicing:
# Character splicing
first_name = "Bruise"
last_name = "Tom "
name = last_name + first_name
print(name)  # Use "+" to splice strings

Tabs and line breaks:

# Tab line break
print("\t"+name + "\n"+name)  # Tab line break

Eliminate blank:

# Eliminate blank
language = " English "
print(language)
print(language.rstrip() + "!")  # Delete end blank
print(language.lstrip())  # Delete leading blanks
print(language.strip() + "!")  # Remove whitespace at the beginning and end
  • Use variable Rstrip(), which means to delete the blank space at the end of variable.
  • Use variable Lstrip(), which means to delete the blank space at the beginning of variable.
  • Use variable Strip(), which means to delete the whitespace at the beginning and end of variable.

Operation results


Among them, add '!' after or in front of the blank elimination operation The certificate deleted the blank

Digital operation

Using str:

##Digital operation
#Use the function str() to avoid type errors
age = 23
message = "Happy " + str(age) + "rd Birthday!" #Using str () to output numbers can achieve the desired results
print(message)

print("1/2=" + str(1/2)) #You don't need to change to float to output expected results

import this  # This line of code can get some rules and styles for editing python code

If you want to use numeric variables with other character variables, you need to change it to str().

Operation results

if statement

Condition test

# Check whether a specific value is included in the list
requested_materials = ['onions', 'pineapple', 'apple', 'mushrooms']
if 'mushrooms' in requested_materials:    # Do remember to call
    print("The mushrooms have been here")

# Check whether a specific value is not included in the list
if 'lettuce' not in requested_materials:
    print("The lettuce hasn't been here")

# bool expression: true or false
print('mushrooms' in requested_materials)
print('lettuce' in requested_materials)

We can directly use a format similar to English grammar to judge some conditions. The grammar is shown in the above code.

if related statements

If else statement

Syntax:

if Judgment conditions:
    Execute statement
else: 
    Execute statement

example:

#If else statement block
age = 17
if age >= 18:
    print("You are old enough to vote!")
    print("Have you registered to vote yet?")
else:
    print("Sorry, you are too young to vote.")
    print("Please register to vote as soon as you turn 18!")

If elif else statement

Syntax:

if Judgment condition 1:
    Execute statement 1
elif Judgment condition 2:
    Execute statement 2
elif Judgment condition 3:
    Execute statement 3
else:
    Execute statement 4

example:

age = 12
if age < 4:
    price = 0
elif age < 18:
    price = 5
else:
    price = 10
print("Your admission cost is $" + str(price) + ".\n")

Python does not require an else code block after an if elif structure. In some cases, else code blocks are useful; In other cases, it is clearer to use an elif statement to deal with a specific situation.

In addition, if you need to judge multiple conditions, you can use multiple if statements.

Use the if statement to process the list

Next, we mainly apply if statements to find special elements and determine whether the list is empty.

# #Use the if statement to process the list
# Find special elements
# requested_materials = ['onions','pineapple','apple','mushrooms']
for requested_material in requested_materials:
    if requested_material == 'pineapple':
        print("Sorry,we are out of pineapple right now.")
    else:
        print("Adding " + requested_material + ".")

print("\nFinished making your dish!")

# Make sure the list is not empty
requested_toppings = []

if requested_toppings:    # Returns True when it contains at least one element and False when the list is empty
    for requested_topping in requested_toppings:
        print("Adding" + requested_topping + ".")
else:
    print("Are you sure you want a plain dish?")

Test:
The customer orders, if there is still inventory, add it, and if not, tell them they are sold out.

# Use multiple lists
# Compare the dishes provided with the dishes ordered to see if there are sold out dishes
requested_materials = ['onions','pineapple','apple','mushrooms']
available_material = ['onions', 'pineapple', 'extra cheese', 'mushrooms']
for requested_material in requested_materials:
    if requested_material in available_material:
        print("Adding " + requested_material + ".")
    else:
        print("Sorry,we don't have " + requested_material + ".")

print("\nFinished making your dish")

Test result:

Topics: Python Back-end